<?php
/**
 * نصب پورتال عمده‌فروشی B2B — قشم / مناطق آزاد
 * C:\xampp\php\php.exe run-wholesale-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;

require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

$pre     = $wpdb->prefix;
$charset = 'DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
$pass    = 'Wholesale1234';
$log     = [];

$ddl = [
    "CREATE TABLE IF NOT EXISTS {$pre}wholesale_applications (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        business_name VARCHAR(200) NOT NULL,
        business_type VARCHAR(30) NOT NULL DEFAULT 'retailer',
        contact_name VARCHAR(120) NULL,
        phone VARCHAR(30) NOT NULL,
        email VARCHAR(120) NULL,
        city VARCHAR(100) NULL,
        zone VARCHAR(30) NOT NULL DEFAULT 'mainland',
        tax_id VARCHAR(50) NULL,
        address TEXT NULL,
        notes TEXT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'pending',
        user_id BIGINT UNSIGNED NULL,
        reviewed_at DATETIME NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}wholesale_accounts (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id BIGINT UNSIGNED NOT NULL,
        business_name VARCHAR(200) NOT NULL,
        business_type VARCHAR(30) NOT NULL DEFAULT 'retailer',
        tier VARCHAR(30) NOT NULL DEFAULT 'retailer',
        zone VARCHAR(30) NOT NULL DEFAULT 'mainland',
        city VARCHAR(100) NULL,
        phone VARCHAR(30) NULL,
        email VARCHAR(120) NULL,
        tax_id VARCHAR(50) NULL,
        address TEXT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'approved',
        credit_limit DECIMAL(18,2) NOT NULL DEFAULT 0,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY idx_user (user_id),
        KEY idx_tier (tier),
        KEY idx_status (status)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}wholesale_products (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        sku VARCHAR(40) NOT NULL,
        name VARCHAR(200) NOT NULL,
        category VARCHAR(40) NOT NULL DEFAULT 'other',
        unit VARCHAR(30) NOT NULL DEFAULT 'عدد',
        moq INT UNSIGNED NOT NULL DEFAULT 1,
        origin_zone VARCHAR(30) NOT NULL DEFAULT 'qeshm_ftz',
        description TEXT NULL,
        image_emoji VARCHAR(10) NULL DEFAULT '📦',
        stock_qty INT NOT NULL DEFAULT 0,
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY idx_sku (sku),
        KEY idx_cat (category),
        KEY idx_active (is_active)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}wholesale_prices (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        product_id BIGINT UNSIGNED NOT NULL,
        tier VARCHAR(30) NOT NULL DEFAULT 'retailer',
        min_qty INT UNSIGNED NOT NULL DEFAULT 1,
        unit_price DECIMAL(18,2) NOT NULL,
        PRIMARY KEY (id),
        UNIQUE KEY idx_prod_tier_qty (product_id, tier, min_qty),
        KEY idx_product (product_id)
    ) {$charset}",

    "CREATE TABLE IF NOT EXISTS {$pre}wholesale_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        order_key VARCHAR(32) NOT NULL,
        user_id BIGINT UNSIGNED NOT NULL,
        account_id BIGINT UNSIGNED NOT NULL,
        tier VARCHAR(30) NOT NULL,
        items_json JSON NOT NULL,
        subtotal DECIMAL(18,2) NOT NULL DEFAULT 0,
        shipping_cost DECIMAL(18,2) NOT NULL DEFAULT 0,
        total DECIMAL(18,2) NOT NULL DEFAULT 0,
        currency VARCHAR(10) NOT NULL DEFAULT 'IRR',
        po_number VARCHAR(80) NULL,
        incoterm VARCHAR(20) NOT NULL DEFAULT 'DAP',
        payment_terms VARCHAR(30) NOT NULL DEFAULT 'prepaid',
        ship_to_address TEXT NULL,
        ship_to_city VARCHAR(100) NULL,
        customer_note TEXT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'submitted',
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY idx_order_key (order_key),
        KEY idx_user (user_id),
        KEY idx_status (status)
    ) {$charset}",
];

foreach ( $ddl as $sql ) {
    $wpdb->query( $sql );
    $log[] = 'table_ok';
}

foreach ( [
    [ 'wholesale.buy', 'خرید عمده B2B', 'wholesale' ],
    [ 'wholesale.manage', 'مدیریت عمده‌فروشی', 'wholesale' ],
] as [ $key, $label, $grp ] ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_permissions WHERE permission_key=%s", $key ) ) ) {
        $wpdb->insert( "{$pre}acl_permissions", [
            'permission_key' => $key, 'label' => $label, 'group_slug' => $grp, 'sort_order' => 0,
        ] );
        $log[] = "perm:{$key}";
    }
}

foreach ( [
    [ 'wholesale_buyer', 'خریدار عمده', 'مغازه / عمده‌فروش تأییدشده', 20 ],
    [ 'wholesale_admin', 'مدیر عمده‌فروشی', 'تأیید حساب و سفارش B2B', 21 ],
] as $r ) {
    if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $r[0] ) ) ) {
        $wpdb->insert( "{$pre}acl_roles", [
            'slug' => $r[0], 'name' => $r[1], 'description' => $r[2], 'sort_order' => $r[3], 'is_system' => 1,
        ] );
        $log[] = "role:{$r[0]}";
    }
}

$role_perms = [
    'wholesale_buyer' => [ 'wholesale.buy' ],
    'wholesale_admin' => [ 'wholesale.buy', 'wholesale.manage', 'shop.manage' ],
];
foreach ( $role_perms as $slug => $perms ) {
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $slug ) );
    foreach ( $perms as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)", $rid, $pk
        ) );
    }
}

$super = (int) $wpdb->get_var( "SELECT id FROM {$pre}acl_roles WHERE slug='super_admin' LIMIT 1" );
if ( $super ) {
    foreach ( [ 'wholesale.buy', 'wholesale.manage' ] as $pk ) {
        $wpdb->query( $wpdb->prepare(
            "INSERT IGNORE INTO {$pre}acl_role_permissions (role_id, permission_key) VALUES (%d, %s)", $super, $pk
        ) );
    }
}

function ws_user( string $login, string $name, string $role ): int {
    global $wpdb, $pass, $log, $pre;
    $id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->users} WHERE user_login=%s", $login ) );
    if ( ! $id ) {
        $id = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID),0) FROM {$wpdb->users}" ) + 1;
        $wpdb->insert( "{$wpdb->users}", [
            'ID' => $id, 'user_login' => $login, 'user_pass' => wp_hash_password( $pass ),
            'user_nicename' => sanitize_title( $login ), 'user_email' => $login . '@wholesale.test',
            'user_registered' => current_time( 'mysql' ), 'display_name' => $name, 'user_status' => 0,
        ] );
        $log[] = "user:created:{$login}";
    }
    $rid = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pre}acl_roles WHERE slug=%s", $role ) );
    if ( $rid && ! (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$pre}acl_user_roles WHERE user_id=%d AND role_id=%d", $id, $rid
    ) ) ) {
        $wpdb->insert( "{$pre}acl_user_roles", [
            'user_id' => $id, 'role_id' => $rid, 'scope_type' => 'global', 'scope_id' => null, 'granted_by' => 2,
        ] );
    }
    return $id;
}

$uid_shop = ws_user( 'wholesale_shop_demo', 'سوپرمارکت پارس — شیراز', 'wholesale_buyer' );
$uid_dist = ws_user( 'wholesale_dist_demo', 'توزیع‌پخش جنوب', 'wholesale_buyer' );
ws_user( 'wholesale_admin', 'مدیر عمده‌فروشی', 'wholesale_admin' );

function ws_account( int $uid, array $d ): void {
    global $wpdb;
    $t = Qeshm_Wholesale::accounts_table();
    $exists = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$t} WHERE user_id=%d", $uid ) );
    $row = array_merge( [
        'user_id' => $uid, 'status' => 'approved', 'credit_limit' => 0,
        'created_at' => current_time( 'mysql' ), 'updated_at' => current_time( 'mysql' ),
    ], $d );
    if ( $exists ) {
        unset( $row['created_at'] );
        $wpdb->update( $t, $row, [ 'id' => $exists ] );
    } else {
        $wpdb->insert( $t, $row );
    }
}

ws_account( $uid_shop, [
    'business_name' => 'سوپرمارکت پارس', 'business_type' => 'retailer', 'tier' => 'retailer',
    'zone' => 'mainland', 'city' => 'شیراز', 'phone' => '09171234001',
    'address' => 'بلوار زند، پلاک ۱۲', 'tax_id' => '1234567890',
] );
ws_account( $uid_dist, [
    'business_name' => 'توزیع‌پخش جنوب', 'business_type' => 'distributor', 'tier' => 'distributor',
    'zone' => 'mainland', 'city' => 'بندرعباس', 'phone' => '09171234002',
    'address' => 'بندرعباس — انبار مرکزی', 'tax_id' => '9876543210', 'credit_limit' => 500000000,
] );

$products = [
    [ 'sku' => 'QSM-EL-001', 'name' => 'هدفون بلوتوث (واردات قشم)', 'category' => 'electronics', 'unit' => 'کارتن', 'moq' => 10, 'stock' => 500, 'emoji' => '🎧',
      'prices' => [ 'retailer' => [ [1,8500000], [50,8200000] ], 'distributor' => [ [1,7800000], [100,7200000] ], 'vip' => [ [1,7000000] ] ] ],
    [ 'sku' => 'QSM-CO-002', 'name' => 'کرم مرطوب‌کننده (برند خارجی)', 'category' => 'cosmetics', 'unit' => 'کارتن', 'moq' => 5, 'stock' => 300, 'emoji' => '🧴',
      'prices' => [ 'retailer' => [ [1,4200000], [20,3900000] ], 'distributor' => [ [1,3600000], [50,3300000] ] ] ],
    [ 'sku' => 'QSM-FD-003', 'name' => 'روغن پalm وارداتی', 'category' => 'food', 'unit' => 'تن', 'moq' => 1, 'stock' => 50, 'emoji' => '🛢️',
      'prices' => [ 'retailer' => [ [1,280000000] ], 'distributor' => [ [1,265000000], [5,250000000] ] ] ],
    [ 'sku' => 'QSM-TX-004', 'name' => 'پارچه پیراهنی (واردات)', 'category' => 'textile', 'unit' => 'رول', 'moq' => 3, 'stock' => 120, 'emoji' => '🧵',
      'prices' => [ 'retailer' => [ [1,15000000] ], 'distributor' => [ [1,13500000], [10,12500000] ] ] ],
    [ 'sku' => 'QSM-HM-005', 'name' => 'ست ظروف آشپزخانه', 'category' => 'home', 'unit' => 'کارتن', 'moq' => 8, 'stock' => 200, 'emoji' => '🍳',
      'prices' => [ 'retailer' => [ [1,6200000], [30,5800000] ], 'distributor' => [ [1,5500000] ] ] ],
    [ 'sku' => 'QSM-EL-006', 'name' => 'شارژر موبایل bulk', 'category' => 'electronics', 'unit' => 'کارتن', 'moq' => 20, 'stock' => 800, 'emoji' => '🔌',
      'prices' => [ 'retailer' => [ [1,3100000], [100,2800000] ], 'distributor' => [ [1,2600000], [200,2400000] ], 'vip' => [ [1,2300000] ] ] ],
];

$pt = Qeshm_Wholesale::products_table();
$pr = Qeshm_Wholesale::prices_table();

foreach ( $products as $p ) {
    $existing = (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$pt} WHERE sku=%s", $p['sku'] ) );
    $data = [
        'sku' => $p['sku'], 'name' => $p['name'], 'category' => $p['category'],
        'unit' => $p['unit'], 'moq' => $p['moq'], 'origin_zone' => 'qeshm_ftz',
        'description' => 'واردات از منطقه آزاد قشم — قیمت B2B',
        'image_emoji' => $p['emoji'], 'stock_qty' => $p['stock'], 'is_active' => 1,
    ];
    if ( $existing ) {
        $wpdb->update( $pt, $data, [ 'id' => $existing ] );
        $pid = $existing;
    } else {
        $wpdb->insert( $pt, $data );
        $pid = (int) $wpdb->insert_id;
    }
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$pr} WHERE product_id=%d", $pid ) );
    foreach ( $p['prices'] as $tier => $breaks ) {
        foreach ( $breaks as [ $min_qty, $price ] ) {
            $wpdb->insert( $pr, [
                'product_id' => $pid, 'tier' => $tier, 'min_qty' => $min_qty, 'unit_price' => $price,
            ] );
        }
    }
    $log[] = "product:{$p['sku']}";
}

echo json_encode( [
    'ok'      => true,
    'message' => 'پورتال عمده‌فروشی B2B نصب شد — برای داده غنی: run-wholesale-seed.php',
    'demo'    => [
        'password' => $pass,
        'shop_buyer'  => [ 'login' => 'wholesale_shop_demo', 'password' => $pass, 'tier' => 'retailer' ],
        'distributor' => [ 'login' => 'wholesale_dist_demo', 'password' => $pass, 'tier' => 'distributor' ],
        'vip'         => [ 'login' => 'wholesale_vip_demo', 'password' => $pass, 'tier' => 'vip' ],
        'chain'       => [ 'login' => 'wholesale_chain_demo', 'password' => $pass, 'tier' => 'vip' ],
        'pending'     => [ 'login' => 'wholesale_pending_demo', 'password' => $pass, 'status' => 'pending' ],
        'admin'       => [ 'login' => 'wholesale_admin', 'password' => $pass ],
        'url'         => '/acc-engine/wholesale.php',
    ],
    'stats'   => Qeshm_Wholesale::stats(),
    'log'     => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
