<?php
/**
 * بارگذاری داده تستی غنی پورتال B2B
 * C:\xampp\php\php.exe run-wholesale-seed.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';

$seed = require ACC_PATH . 'includes/data/wholesale-seed.php';
$pre  = $wpdb->prefix;
$pass = $seed['password'] ?? 'Wholesale1234';
$log  = [];

function ws_seed_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}";
    } else {
        $wpdb->update( "{$wpdb->users}", [ 'display_name' => $name ], [ 'ID' => $id ] );
    }
    $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;
}

function ws_seed_account( int $uid, array $d ): int {
    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 ] );
        return $exists;
    }
    $wpdb->insert( $t, $row );
    return (int) $wpdb->insert_id;
}

$user_map = [];
foreach ( $seed['users'] as $u ) {
    $uid = ws_seed_user( $u['login'], $u['name'], $u['role'] );
    $user_map[ $u['login'] ] = $uid;
    if ( ! empty( $u['account'] ) ) {
        ws_seed_account( $uid, $u['account'] );
        $log[] = "account:{$u['login']}";
    }
}

$pt = Qeshm_Wholesale::products_table();
$pr = Qeshm_Wholesale::prices_table();
$sku_map = [];

foreach ( $seed['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' => $p['origin_zone'] ?? 'qeshm_ftz',
        'description' => $p['desc'] ?? 'واردات از منطقه آزاد قشم — قیمت B2B',
        'image_emoji' => $p['emoji'], 'stock_qty' => $p['stock'], 'sort_order' => $p['sort'] ?? 0, 'is_active' => 1,
    ];
    if ( $existing ) {
        $wpdb->update( $pt, $data, [ 'id' => $existing ] );
        $pid = $existing;
    } else {
        $wpdb->insert( $pt, $data );
        $pid = (int) $wpdb->insert_id;
    }
    $sku_map[ $p['sku'] ] = $pid;
    $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']}";
}

$at = Qeshm_Wholesale::applications_table();
foreach ( $seed['applications'] as $app ) {
    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$at} WHERE business_name=%s AND phone=%s", $app['business_name'], $app['phone']
    ) );
    if ( ! $exists ) {
        $wpdb->insert( $at, array_merge( $app, [ 'created_at' => current_time( 'mysql' ) ] ) );
        $log[] = "application:{$app['business_name']}";
    }
}

$ot = Qeshm_Wholesale::orders_table();
foreach ( $seed['orders'] as $ord ) {
    $login = $ord['user_login'];
    $uid   = $user_map[ $login ] ?? 0;
    if ( ! $uid ) continue;

    $acc = Qeshm_Wholesale::get_account_by_user( $uid );
    if ( ! $acc ) continue;

    $exists = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$ot} WHERE po_number=%s AND user_id=%d", $ord['po_number'], $uid
    ) );
    if ( $exists ) {
        $log[] = "order:skip:{$ord['po_number']}";
        continue;
    }

    $tier = $acc['tier'] ?? 'retailer';
    $lines = [];
    $subtotal = 0;
    foreach ( $ord['items'] as $it ) {
        $sku = $it['sku'];
        $pid = $sku_map[ $sku ] ?? 0;
        if ( ! $pid ) continue;
        $p = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$pt} WHERE id=%d", $pid ), ARRAY_A );
        if ( ! $p ) continue;
        $qty = (int) $it['qty'];
        $prices = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$pr} WHERE product_id=%d", $pid ), ARRAY_A ) ?: [];
        $resolved = Qeshm_Wholesale::resolve_price( $prices, $tier, $qty );
        $line_total = $resolved['unit_price'] * $qty;
        $subtotal += $line_total;
        $lines[] = [
            'product_id' => $pid, 'sku' => $p['sku'], 'name' => $p['name'], 'unit' => $p['unit'],
            'qty' => $qty, 'unit_price' => $resolved['unit_price'], 'line_total' => $line_total,
        ];
    }
    if ( ! $lines ) continue;

    $key = 'WS-' . strtoupper( substr( md5( $ord['po_number'] ), 0, 8 ) );
    $wpdb->insert( $ot, [
        'order_key'       => $key,
        'user_id'         => $uid,
        'account_id'      => (int) $acc['id'],
        'tier'            => $tier,
        'items_json'      => wp_json_encode( $lines, JSON_UNESCAPED_UNICODE ),
        'subtotal'        => $subtotal,
        'shipping_cost'   => 0,
        'total'           => $subtotal,
        'currency'        => 'IRR',
        'po_number'       => $ord['po_number'],
        'incoterm'        => $ord['incoterm'] ?? 'DAP',
        'payment_terms'   => $ord['payment_terms'] ?? 'prepaid',
        'ship_to_address' => $ord['ship_to'] ?? '',
        'ship_to_city'    => $acc['city'] ?? '',
        'status'          => $ord['status'] ?? 'submitted',
        'created_at'      => date( 'Y-m-d H:i:s', strtotime( '-' . rand( 2, 28 ) . ' days' ) ),
    ] );
    $log[] = "order:{$key}";
}

echo json_encode( [
    'ok'      => true,
    'message' => 'داده تستی B2B بارگذاری شد',
    'stats'   => Qeshm_Wholesale::stats(),
    'categories' => Qeshm_Wholesale::category_counts(),
    'demo'    => [
        'password' => $pass,
        'users' => array_map( static fn( $u ) => [
            'login' => $u['login'],
            'label' => $u['name'],
            'tier'  => $u['account']['tier'] ?? ( $u['role'] === 'wholesale_admin' ? 'admin' : '—' ),
            'status' => $u['account']['status'] ?? 'approved',
        ], $seed['users'] ),
        'url' => '/acc-engine/wholesale.php',
    ],
    'log' => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
