<?php
/**
 * نصب اتصال انبار فروشگاه عرقیات
 * php run-arag-inv-install.php
 */
declare(strict_types=1);

if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __DIR__ . '/standalone/bootstrap.php';
}

header( 'Content-Type: application/json; charset=utf-8' );
global $wpdb;
$pre     = $wpdb->prefix;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$log     = [];

require_once ACC_PATH . 'includes/helpers/arag-erp.php';

/* ── Schema: inv tables (minimal) ── */
$inv_tables = [
    "CREATE TABLE IF NOT EXISTS {$pre}inv_categories (
        id INT NOT NULL AUTO_INCREMENT, name VARCHAR(200) NOT NULL, parent_id INT DEFAULT NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) {$charset}",
    "CREATE TABLE IF NOT EXISTS {$pre}inv_products (
        id INT NOT NULL AUTO_INCREMENT, category_id INT DEFAULT NULL,
        code VARCHAR(100) NOT NULL DEFAULT '', name VARCHAR(300) NOT NULL,
        unit VARCHAR(30) NOT NULL DEFAULT 'عدد', unit2 VARCHAR(30) NOT NULL DEFAULT '',
        conversion_factor DECIMAL(10,4) NOT NULL DEFAULT 1, costing_method VARCHAR(10) NOT NULL DEFAULT 'avg',
        tracking VARCHAR(10) NOT NULL DEFAULT 'none', min_stock DECIMAL(14,4) NOT NULL DEFAULT 0,
        max_stock DECIMAL(14,4) NOT NULL DEFAULT 0, reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0,
        description TEXT, is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id), KEY idx_code (code)
    ) {$charset}",
    "CREATE TABLE IF NOT EXISTS {$pre}inv_warehouses (
        id INT NOT NULL AUTO_INCREMENT, code VARCHAR(50) NOT NULL DEFAULT '', name VARCHAR(200) NOT NULL,
        type VARCHAR(20) NOT NULL DEFAULT 'main', location VARCHAR(300) NOT NULL DEFAULT '',
        manager_name VARCHAR(200) NOT NULL DEFAULT '', is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id)
    ) {$charset}",
    "CREATE TABLE IF NOT EXISTS {$pre}inv_stock (
        id INT NOT NULL AUTO_INCREMENT, product_id INT NOT NULL, warehouse_id INT NOT NULL,
        qty DECIMAL(14,4) NOT NULL DEFAULT 0, avg_cost DECIMAL(18,4) NOT NULL DEFAULT 0,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id), UNIQUE KEY idx_product_wh (product_id, warehouse_id)
    ) {$charset}",
    "CREATE TABLE IF NOT EXISTS {$pre}inv_vouchers (
        id INT NOT NULL AUTO_INCREMENT, voucher_no VARCHAR(50) NOT NULL DEFAULT '',
        type VARCHAR(30) NOT NULL, status VARCHAR(15) NOT NULL DEFAULT 'draft',
        ref_id INT DEFAULT NULL, ref_type VARCHAR(50) NOT NULL DEFAULT '', ref_no VARCHAR(100) NOT NULL DEFAULT '',
        date DATE NOT NULL, description TEXT, created_by VARCHAR(200) NOT NULL DEFAULT '',
        confirmed_by VARCHAR(200) NOT NULL DEFAULT '', created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        confirmed_at DATETIME DEFAULT NULL, PRIMARY KEY (id), KEY idx_ref (ref_type, ref_id)
    ) {$charset}",
    "CREATE TABLE IF NOT EXISTS {$pre}inv_voucher_items (
        id INT NOT NULL AUTO_INCREMENT, voucher_id INT NOT NULL, product_id INT NOT NULL,
        from_warehouse_id INT DEFAULT NULL, to_warehouse_id INT DEFAULT NULL,
        qty DECIMAL(14,4) NOT NULL DEFAULT 0, unit_price DECIMAL(18,4) NOT NULL DEFAULT 0,
        total_price DECIMAL(18,4) NOT NULL DEFAULT 0, batch_id INT DEFAULT NULL,
        notes VARCHAR(500) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY idx_voucher (voucher_id)
    ) {$charset}",
];
foreach ( $inv_tables as $sql ) {
    $wpdb->query( $sql );
    $log[] = 'inv_table_ok';
}

/* ── Arag package → product link ── */
if ( ! $wpdb->get_var( "SHOW COLUMNS FROM {$pre}arag_packages LIKE 'inv_product_id'" ) ) {
    $wpdb->query( "ALTER TABLE {$pre}arag_packages ADD COLUMN inv_product_id INT NULL COMMENT 'محصول انبار'" );
    $log[] = 'arag_packages.inv_product_id';
}
if ( ! $wpdb->get_var( "SHOW COLUMNS FROM {$pre}arag_orders LIKE 'inv_voucher_id'" ) ) {
    $wpdb->query( "ALTER TABLE {$pre}arag_orders ADD COLUMN inv_voucher_id INT NULL COMMENT 'سند خروج انبار'" );
    $log[] = 'arag_orders.inv_voucher_id';
}

/* ── Category ── */
$cat_id = (int) $wpdb->get_var(
    "SELECT id FROM {$pre}inv_categories WHERE name = 'عرقیات' LIMIT 1"
);
if ( ! $cat_id ) {
    $wpdb->insert( "{$pre}inv_categories", [ 'name' => 'عرقیات' ] );
    $cat_id = (int) $wpdb->insert_id;
    $log[] = 'category:araghiat';
}

/* ── Warehouse ── */
$wh_id = (int) $wpdb->get_var(
    "SELECT id FROM {$pre}inv_warehouses WHERE code = 'WH-ARAG' LIMIT 1"
);
if ( ! $wh_id ) {
    $wpdb->insert( "{$pre}inv_warehouses", [
        'code'         => 'WH-ARAG',
        'name'         => 'انبار مرکزی عرقیات',
        'type'         => 'main',
        'location'     => 'کارخانه عرق‌گیری — اصفهان',
        'manager_name' => 'مسئول انبار فروشگاه',
    ] );
    $wh_id = (int) $wpdb->insert_id;
    $log[] = 'warehouse:WH-ARAG';
}

/* ── Map packages → inv_products + stock ── */
$packages = $wpdb->get_results(
    "SELECT p.id, p.label, p.volume, p.price, p.inv_product_id,
            v.name AS variant_name, v.slug AS variant_slug,
            f.name AS family_name, f.slug AS family_slug
     FROM {$pre}arag_packages p
     INNER JOIN {$pre}arag_variants v ON v.id = p.variant_id
     INNER JOIN {$pre}arag_families f ON f.id = v.family_id
     WHERE p.is_active = 1
     ORDER BY f.sort_order, v.sort_order, p.sort_order",
    ARRAY_A
) ?: [];

$mapped = 0;
$stocked = 0;
foreach ( $packages as $pkg ) {
    $pid = (int) ( $pkg['inv_product_id'] ?? 0 );
    $code = 'ARAG-' . strtoupper( $pkg['family_slug'] ) . '-' . strtoupper( preg_replace( '/[^a-z0-9]/', '', $pkg['variant_slug'] ) ) . '-P' . $pkg['id'];

    if ( $pid <= 0 ) {
        $existing = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$pre}inv_products WHERE code = %s LIMIT 1", $code
        ) );
        if ( $existing ) {
            $pid = $existing;
        } else {
            $name = $pkg['family_name'] . ' — ' . $pkg['variant_name'] . ' — ' . $pkg['label'] . ' ' . $pkg['volume'];
            $wpdb->insert( "{$pre}inv_products", [
                'category_id' => $cat_id,
                'code'        => $code,
                'name'        => $name,
                'unit'        => 'عدد',
                'avg_cost'    => 0,
                'min_stock'   => 5,
                'description' => 'محصول انبار متصل به بسته فروشگاه #' . $pkg['id'],
            ] );
            $pid = (int) $wpdb->insert_id;
            $log[] = "product:{$code}";
        }
        $wpdb->update( "{$pre}arag_packages", [ 'inv_product_id' => $pid ], [ 'id' => (int) $pkg['id'] ] );
        $mapped++;
    }

    $stk = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}inv_stock WHERE product_id = %d AND warehouse_id = %d", $pid, $wh_id
    ) );
    $seed_qty = 120;
    $avg_cost = round( (float) $pkg['price'] * 0.45, 0 );
    if ( $stk ) {
        $wpdb->update( "{$pre}inv_stock", [
            'qty'      => $seed_qty,
            'avg_cost' => $avg_cost,
        ], [ 'id' => $stk ] );
    } else {
        $wpdb->insert( "{$pre}inv_stock", [
            'product_id'   => $pid,
            'warehouse_id' => $wh_id,
            'qty'          => $seed_qty,
            'avg_cost'     => $avg_cost,
        ] );
        $stocked++;
    }
}

/* ── ERP config: default warehouse ── */
$cfg = Arag_Erp::get_config();
$cfg['default_warehouse'] = $wh_id;
$cfg['auto_issue_stock']  = true;
$cfg['check_stock']       = true;
Arag_Erp::save_config( $cfg );
$log[] = 'erp_config:default_warehouse';

/* ── Permission ── */
$perm = 'inv.view';
$ex = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT id FROM {$pre}acl_permissions WHERE perm_key = %s", $perm
) );
if ( ! $ex ) {
    $wpdb->insert( "{$pre}acl_permissions", [
        'perm_key' => $perm, 'label' => 'مشاهده انبار', 'module' => 'inv', 'resource' => 'inv', 'action' => 'view',
    ] );
    $ex = (int) $wpdb->insert_id;
    $log[] = "perm:{$perm}";
}
$acc_role = (int) $wpdb->get_var( "SELECT id FROM {$pre}acl_roles WHERE slug = 'accountant'" );
if ( $acc_role && $ex ) {
    $rp = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}acl_role_permissions WHERE role_id = %d AND permission_id = %d", $acc_role, $ex
    ) );
    if ( ! $rp ) {
        $wpdb->insert( "{$pre}acl_role_permissions", [ 'role_id' => $acc_role, 'permission_id' => $ex ] );
        $log[] = 'role:accountant:inv.view';
    }
}

echo wp_json_encode( [
    'success'          => true,
    'message'          => 'اتصال انبار فروشگاه تکمیل شد',
    'warehouse_id'     => $wh_id,
    'warehouse_code'   => 'WH-ARAG',
    'packages_mapped'  => $mapped,
    'stock_rows'       => $stocked,
    'total_packages'   => count( $packages ),
    'changes'          => array_values( array_unique( $log ) ),
    'next_step'        => 'php run-arag-full-demo.php',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
