<?php
/**
 * دمو کامل فروشگاه عرقیات — از انتخاب محصول تا حسابداری و انبار
 * php run-arag-full-demo.php
 *
 * پیش‌نیاز:
 *   php run-arag-seed.php
 *   php run-arag-erp-install.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;
$log = [];

require_once ACC_PATH . 'includes/helpers/arag-erp.php';
if ( ! class_exists( 'Acc_Event_Engine' ) ) {
    require_once ACC_PATH . 'includes/helpers/acc-event-engine.php';
}

const DEMO_ORDER_KEY = 'arag_full_demo_2026';

function demo_find_packages( $wpdb, string $pre ): array {
    $rows = $wpdb->get_results(
        "SELECT p.id, p.label, p.volume, p.price, p.inv_product_id,
                v.name AS variant_name, 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 f.slug = 'golab' AND v.slug = 'golab-asil' AND p.is_active = 1
         ORDER BY p.sort_order ASC
         LIMIT 2",
        ARRAY_A
    ) ?: [];
    if ( count( $rows ) >= 2 ) {
        return $rows;
    }
    return $wpdb->get_results(
        "SELECT p.id, p.label, p.volume, p.price, p.inv_product_id,
                v.name AS variant_name, 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 AND p.inv_product_id IS NOT NULL
         ORDER BY p.id ASC LIMIT 2",
        ARRAY_A
    ) ?: [];
}

function demo_cleanup( $wpdb, string $pre, string $order_key ): void {
    $oid = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$pre}arag_orders WHERE order_key = %s", $order_key
    ) );
    if ( ! $oid ) {
        return;
    }
    $ship_id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT ship_shipment_id FROM {$pre}arag_orders WHERE id = %d", $oid
    ) );
    $event_id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT acc_event_id FROM {$pre}arag_orders WHERE id = %d", $oid
    ) );
    $lead_id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT crm_lead_id FROM {$pre}arag_orders WHERE id = %d", $oid
    ) );

    if ( $ship_id ) {
        $vids = $wpdb->get_col( $wpdb->prepare(
            "SELECT id FROM {$pre}inv_vouchers WHERE ref_type = 'shipment' AND ref_id = %d", $ship_id
        ) ) ?: [];
        foreach ( $vids as $vid ) {
            $wpdb->delete( "{$pre}inv_voucher_items", [ 'voucher_id' => (int) $vid ] );
            $wpdb->delete( "{$pre}inv_vouchers", [ 'id' => (int) $vid ] );
        }
        $wpdb->delete( "{$pre}ship_stages", [ 'shipment_id' => $ship_id ] );
        $wpdb->delete( "{$pre}ship_items", [ 'shipment_id' => $ship_id ] );
        $wpdb->delete( "{$pre}ship_shipments", [ 'id' => $ship_id ] );
    }
    if ( $event_id ) {
        $wpdb->delete( "{$pre}arag_erp_journal", [ 'order_id' => $oid ] );
        $wpdb->delete( "{$pre}ai_acc_events", [ 'id' => $event_id ] );
    }
    if ( $lead_id && $wpdb->get_var( "SHOW TABLES LIKE '{$pre}crm_activities'" ) === "{$pre}crm_activities" ) {
        $wpdb->delete( "{$pre}crm_activities", [ 'lead_id' => $lead_id ] );
        $wpdb->delete( "{$pre}crm_leads", [ 'id' => $lead_id ] );
    }
    $wpdb->delete( "{$pre}arag_orders", [ 'id' => $oid ] );
}

/* ── 1. پیش‌نیازها ── */
$pkgs = demo_find_packages( $wpdb, $pre );
if ( count( $pkgs ) < 1 ) {
    echo wp_json_encode( [
        'success' => false,
        'message' => 'بسته فروشگاه یافت نشد — ابتدا run-arag-seed.php و run-arag-inv-install.php را اجرا کنید',
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
    exit;
}

$wh = Arag_Erp::default_warehouse_id();
if ( $wh <= 0 ) {
    echo wp_json_encode( [
        'success' => false,
        'message' => 'انبار پیش‌فرض تنظیم نشده — run-arag-inv-install.php را اجرا کنید',
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
    exit;
}

demo_cleanup( $wpdb, $pre, DEMO_ORDER_KEY );
$log[] = 'cleanup_previous_demo';

/* ── 2. مشتری نمونه ── */
$demo_phone = '09121112233';
$demo_name  = 'علی رضایی';
$demo_user_id = (int) $wpdb->get_var( $wpdb->prepare(
    "SELECT ID FROM {$wpdb->users} WHERE user_login = %s", 'arag_demo_customer'
) );
if ( ! $demo_user_id ) {
    $new_id = (int) $wpdb->get_var( "SELECT COALESCE( MAX( ID ), 0 ) + 1 FROM {$wpdb->users}" );
    $wpdb->insert( $wpdb->users, [
        'ID'              => $new_id,
        'user_login'      => 'arag_demo_customer',
        'user_pass'       => password_hash( 'Demo@2026', PASSWORD_BCRYPT ),
        'user_nicename'   => 'ali-rezaei',
        'user_email'      => 'demo.customer@acc.local',
        'user_registered' => current_time( 'mysql' ),
        'display_name'    => $demo_name,
    ] );
    $demo_user_id = $new_id;
    $log[] = 'user:arag_demo_customer';
}

/* ── 3. سبد / خط سفارش (مثل انتخاب در فروشگاه) ── */
$line_items = [];
$subtotal   = 0;
$cart_desc  = [];
$qtys       = [ 2, 1 ];
foreach ( $pkgs as $i => $pkg ) {
    $qty = $qtys[ $i ] ?? 1;
    $price = (float) $pkg['price'];
    $label = "{$pkg['family_name']} — {$pkg['variant_name']} — {$pkg['label']}";
    $line_items[] = [
        'package_id'     => (int) $pkg['id'],
        'qty'            => $qty,
        'price'          => $price,
        'label'          => $label,
        'family_name'    => $pkg['family_name'],
        'variant_name'   => $pkg['variant_name'],
        'package_label'  => $pkg['label'],
        'volume'         => $pkg['volume'],
        'inv_product_id' => (int) ( $pkg['inv_product_id'] ?? 0 ) ?: Arag_Erp::resolve_package_product( (int) $pkg['id'] ),
    ];
    $subtotal += $price * $qty;
    $cart_desc[] = "{$label} ×{$qty}";
}
$line_items = Arag_Erp::enrich_line_items( $line_items );
$stock = Arag_Erp::validate_order_stock( $line_items );
if ( empty( $stock['success'] ) ) {
    echo wp_json_encode( [
        'success' => false,
        'message' => $stock['message'] ?? 'موجودی کافی نیست',
        'hint'    => 'run-arag-inv-install.php را دوباره اجرا کنید',
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
    exit;
}
$log[] = 'cart_validated';

/* ── 4. ثبت سفارش (پرداخت در محل + تیپاکس) ── */
$order_number = 'AR-DEMO-' . date( 'Y' );
$wpdb->insert( "{$pre}arag_orders", [
    'order_key'       => DEMO_ORDER_KEY,
    'order_number'    => $order_number,
    'user_id'         => $demo_user_id,
    'items_json'      => wp_json_encode( $line_items, JSON_UNESCAPED_UNICODE ),
    'subtotal'        => $subtotal,
    'shipping_method' => 'tipax',
    'shipping_cod'    => 1,
    'payment_method'  => 'cod',
    'payment_status'  => 'cod',
    'order_status'    => 'processing',
    'billing_name'    => $demo_name,
    'billing_phone'   => $demo_phone,
    'billing_address' => 'تهران، خیابان ولیعصر، پلاک ۱۲، واحد ۴',
    'billing_city'    => 'تهران',
    'customer_note'   => 'دمو کامل — تحویل عصر، تماس قبل از ارسال',
] );
$order_id = (int) $wpdb->insert_id;
$log[] = 'order_created';

/* ── 5. ERP: CRM + محموله + رویداد حسابداری ── */
$erp = Arag_Erp::on_order_confirmed( $order_id );
$log[] = 'erp_synced';

/* ── 6. صدور سند حسابداری توسط حسابدار ── */
$posted = Arag_Erp::post_order_by_accountant( $order_id );
$log[] = 'accounting_posted';

/* ── 7. پیشرفت محموله تا تحویل + خروج انبار ── */
$order   = Arag_Erp::get_order( $order_id );
$ship_id = (int) ( $order['ship_shipment_id'] ?? 0 );
$ship_steps = [ 'preparing', 'packed', 'picked_up', 'in_transit', 'out_for_delivery', 'delivered' ];
$ship_log   = [];
foreach ( $ship_steps as $step ) {
    $adv = Arag_Erp::advance_shop_shipment( $ship_id, $step, "دمو — {$step}" );
    $ship_log[] = [ 'status' => $step, 'inventory' => $adv['inventory'] ?? null ];
}
$log[] = 'shipment_delivered';

$order_final = Arag_Erp::get_order( $order_id );

/* ── 8. موجودی پس از خروج ── */
$stock_after = [];
foreach ( $line_items as $it ) {
    $pid = (int) ( $it['inv_product_id'] ?? 0 );
    if ( $pid <= 0 ) continue;
    $qty_left = (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT qty FROM {$pre}inv_stock WHERE product_id = %d AND warehouse_id = %d", $pid, $wh
    ) );
    $stock_after[] = [
        'product_id' => $pid,
        'label'      => $it['label'],
        'qty_left'   => $qty_left,
    ];
}

echo wp_json_encode( [
    'success' => true,
    'message' => 'دمو کامل فروشگاه با موفقیت ایجاد شد',
    'flow'    => [
        '1_product_selection' => [
            'description' => 'مشتری در فروشگاه محصول را انتخاب و به سبد اضافه می‌کند',
            'items'         => $cart_desc,
            'subtotal'      => $subtotal,
        ],
        '2_checkout' => [
            'description'  => 'تکمیل سفارش — پرداخت در محل، ارسال تیپاکس',
            'payment'      => 'cod (پرداخت در محل)',
            'shipping'     => 'tipax (تیپاکس — کرایه پس‌پرداخت)',
            'customer'     => [ 'name' => $demo_name, 'phone' => $demo_phone ],
        ],
        '3_erp_crm' => [
            'description' => 'ثبت خودکار لید CRM',
            'result'      => $erp['crm'] ?? null,
        ],
        '4_erp_shipping' => [
            'description' => 'ایجاد محموله خروجی با انبار مبدأ و product_id',
            'result'      => $erp['shipping'] ?? null,
            'steps'       => $ship_log,
        ],
        '5_erp_accounting' => [
            'description' => 'رویداد SHOP_SALE + صدور سند (درآمد + بهای تمام‌شده)',
            'event_id'    => $order_final['acc_event_id'] ?? null,
            'posted'      => $posted,
        ],
        '6_erp_inventory' => [
            'description' => 'سند خروج انبار sale_issue هنگام تحویل',
            'voucher_id'  => $order_final['inv_voucher_id'] ?? null,
            'stock_after' => $stock_after,
        ],
    ],
    'ids' => [
        'order_id'      => $order_id,
        'order_number'  => $order_number,
        'crm_lead_id'   => $order_final['crm_lead_id'] ?? null,
        'shipment_id'   => $ship_id,
        'acc_event_id'  => $order_final['acc_event_id'] ?? null,
        'inv_voucher_id'=> $order_final['inv_voucher_id'] ?? null,
    ],
    'urls' => [
        'shop'       => '/acc-engine/shop.php',
        'account'    => '/acc-engine/account.php',
        'shop_erp'   => '/acc-engine/shop-erp.php',
        'portal_inv' => '/acc-engine/',
    ],
    'demo_users' => [
        'customer'   => [ 'login' => 'arag_demo_customer', 'password' => 'Demo@2026', 'phone' => $demo_phone ],
        'accountant' => [ 'login' => 'arag_accountant', 'password' => 'Demo@2026', 'panel' => '/acc-engine/shop-erp.php' ],
    ],
    'changes' => $log,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
