<?php
/**
 * داده تست بازاریاب فروشگاه — یک بازاریاب + دو مغازه + چند فروش
 * http://localhost/acc-engine/run-arag-marketer-seed.php
 */
declare(strict_types=1);

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

require_once ACC_PATH . 'includes/helpers/arag-marketer.php';
require_once ACC_PATH . 'includes/helpers/arag-shop.php';

header( 'Content-Type: application/json; charset=utf-8' );
global $wpdb;
$pre = $wpdb->prefix;
$out = [ 'steps' => [] ];

/* 1) بازاریاب تست */
$mkt_phone = '09121112233';
$reg = Arag_Marketer::register( [
    'phone'        => $mkt_phone,
    'display_name' => 'علی رضایی — بازاریاب تست',
    'national_id'  => '0012345678',
    'city'         => 'شیراز',
    'address'      => 'خیابان زند، پلاک ۱۲۰',
    'bank_sheba'   => 'IR120170000000123456789001',
    'bank_card'    => '6037991234567890',
    'bank_name'    => 'ملی',
] );
$acc = $reg['account'] ?? Arag_Marketer::get_by_phone( $mkt_phone );
if ( ! $acc ) {
    echo json_encode( [ 'success' => false, 'message' => 'ثبت بازاریاب شکست', 'reg' => $reg ], JSON_UNESCAPED_UNICODE );
    exit;
}
$mid = (int) $acc['id'];
Arag_Marketer::set_status( $mid, 'active', 1, 'تایید خودکار — داده تست' );
Arag_Marketer::set_credit_limit( $mid, 10000000 );
Arag_Marketer::credit_topup( $mid, 2000000, 1, 'شارژ اولیه تست' );
$acc = Arag_Marketer::get_by_id( $mid );
$out['steps'][] = 'marketer_active';
$out['marketer'] = [
    'id'            => $mid,
    'phone'         => $acc['phone'],
    'display_name'  => $acc['display_name'],
    'marketer_code' => $acc['marketer_code'],
    'status'        => $acc['status'],
    'credit'        => $acc['credit_balance'],
    'login_hint'    => 'ورود پنل با OTP روی ' . $mkt_phone,
];

/* 2) دو مغازه */
$shops_def = [
    [
        'shop_phone' => '09131110001',
        'shop_name'  => 'سوپرمارکت بهار — زند',
        'owner_name' => 'حسین محمدی',
        'city'       => 'شیراز',
        'address'    => 'خیابان زند، نبش خیابان انوری',
        'notes'      => 'مغازه تست ۱',
    ],
    [
        'shop_phone' => '09131110002',
        'shop_name'  => 'هایپر میوه ستاره — معالی‌آباد',
        'owner_name' => 'زهرا کریمی',
        'city'       => 'شیراز',
        'address'    => 'معالی‌آباد، بلوار شهید چمران',
        'notes'      => 'مغازه تست ۲',
    ],
];

$shops = [];
foreach ( $shops_def as $sd ) {
    $r = Arag_Marketer::upsert_shop( $mid, $sd );
    if ( empty( $r['success'] ) ) {
        $out['shop_errors'][] = $r;
        continue;
    }
    $shops[] = $r['shop'];
}
$out['steps'][] = 'shops_created';
$out['shops']   = array_map( static fn( $s ) => [
    'id'         => (int) $s['id'],
    'shop_name'  => $s['shop_name'],
    'shop_phone' => $s['shop_phone'],
    'owner_name' => $s['owner_name'],
    'city'       => $s['city'],
], $shops );

if ( count( $shops ) < 2 ) {
    echo json_encode( [ 'success' => false, 'out' => $out ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
    exit;
}

/* 3) پکیج‌های فعال برای سفارش */
$pkgs = $wpdb->get_results(
    "SELECT p.id, p.label, p.price, p.volume, v.name AS variant_name, f.name AS family_name
     FROM {$pre}arag_packages p
     INNER JOIN {$pre}arag_variants v ON v.id = p.variant_id AND v.is_active = 1
     INNER JOIN {$pre}arag_families f ON f.id = v.family_id AND f.is_active = 1
     WHERE p.is_active = 1
     ORDER BY p.price ASC
     LIMIT 6",
    ARRAY_A
) ?: [];

if ( ! $pkgs ) {
    $out['warning'] = 'پکیج فعالی یافت نشد — فقط بازاریاب و مغازه ساخته شد';
    echo json_encode( [ 'success' => true, 'out' => $out ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
    exit;
}

/* پاکسازی سفارش‌های تست قبلی همین بازاریاب (اختیاری — فقط کلیدهای DEMO-MKT) */
$old = $wpdb->get_col( $wpdb->prepare(
    "SELECT id FROM {$pre}arag_orders WHERE sold_by_marketer_id=%d AND order_key LIKE 'demo_mkt_%%'",
    $mid
) );
foreach ( $old as $oid ) {
    $wpdb->delete( "{$pre}arag_marketer_commissions", [ 'order_id' => (int) $oid ] );
    $wpdb->delete( "{$pre}arag_orders", [ 'id' => (int) $oid ] );
}

/* ریست شمارنده‌های فروش برای داده تمیز تست */
$wpdb->update( "{$pre}arag_marketer_accounts", [
    'total_sales'     => 0,
    'total_earned'    => 0,
    'balance_pending' => 0,
    'balance_payable' => 0,
    'orders_count'    => 0,
], [ 'id' => $mid ] );
foreach ( $shops as $s ) {
    $wpdb->update( "{$pre}arag_marketer_shops", [
        'total_orders' => 0,
        'total_sales'  => 0,
    ], [ 'id' => (int) $s['id'] ] );
}

$orders_out = [];

$scenarios = [
    /* مغازه ۱ — دو سفارش (یکی پرداخت‌شده، یکی COD منتظر وصول) */
    [
        'shop'    => $shops[0],
        'pkg'     => $pkgs[0],
        'qty'     => 3,
        'pay'     => 'paid',
        'ship'    => 'post',
        'status'  => 'processing',
    ],
    [
        'shop'    => $shops[0],
        'pkg'     => $pkgs[ min( 1, count( $pkgs ) - 1 ) ],
        'qty'     => 2,
        'pay'     => 'cod',
        'ship'    => 'tipax',
        'status'  => 'processing',
    ],
    /* مغازه ۲ — دو سفارش پرداخت‌شده */
    [
        'shop'    => $shops[1],
        'pkg'     => $pkgs[ min( 2, count( $pkgs ) - 1 ) ],
        'qty'     => 4,
        'pay'     => 'paid',
        'ship'    => 'post',
        'status'  => 'shipped',
    ],
    [
        'shop'    => $shops[1],
        'pkg'     => $pkgs[0],
        'qty'     => 1,
        'pay'     => 'paid',
        'ship'    => 'pickup',
        'status'  => 'completed',
    ],
];

$n = 0;
foreach ( $scenarios as $sc ) {
    $n++;
    $pkg   = $sc['pkg'];
    $shop  = $sc['shop'];
    $qty   = (int) $sc['qty'];
    $price = (float) $pkg['price'];
    $sub   = $price * $qty;
    $items = [[
        'package_id'    => (int) $pkg['id'],
        'qty'           => $qty,
        'price'         => $price,
        'label'         => $pkg['family_name'] . ' — ' . $pkg['variant_name'] . ' — ' . $pkg['label'],
        'family_name'   => $pkg['family_name'],
        'variant_name'  => $pkg['variant_name'],
        'package_label' => $pkg['label'],
        'volume'        => $pkg['volume'],
    ]];
    $order_key = 'demo_mkt_' . $mid . '_' . $n . '_' . bin2hex( random_bytes( 3 ) );
    $order_num = 'AR-DEMO-MKT-' . str_pad( (string) $n, 3, '0', STR_PAD_LEFT );

    $buyer_uid = Arag_Marketer::ensure_user_for_phone( $shop['shop_phone'], $shop['owner_name'] );

    $wpdb->insert( "{$pre}arag_orders", [
        'order_key'       => $order_key,
        'order_number'    => $order_num,
        'user_id'         => $buyer_uid,
        'items_json'      => wp_json_encode( $items, JSON_UNESCAPED_UNICODE ),
        'subtotal'        => $sub,
        'coupon_code'     => '',
        'discount_amount' => 0,
        'total'           => $sub,
        'shipping_method' => $sc['ship'],
        'shipping_cod'    => $sc['ship'] !== 'pickup' ? 1 : 0,
        'payment_method'  => $sc['pay'] === 'cod' ? 'cod' : 'demo',
        'payment_status'  => $sc['pay'] === 'cod' ? 'cod' : 'paid',
        'order_status'    => $sc['status'],
        'ref_id'          => $sc['pay'] === 'paid' ? ( 'DEMO-MKT-' . $n ) : null,
        'billing_name'    => $shop['owner_name'],
        'billing_phone'   => $shop['shop_phone'],
        'billing_address' => $shop['address'],
        'billing_city'    => $shop['city'],
        'customer_note'   => 'سفارش تست بازاریاب',
        'sold_by_marketer_id' => $mid,
    ] );
    $oid = (int) $wpdb->insert_id;

    Arag_Marketer::attach_to_order( $oid, $mid );
    if ( $sc['pay'] === 'paid' ) {
        Arag_Marketer::on_payment_received( $oid );
    }

    $comm = $wpdb->get_row( $wpdb->prepare(
        "SELECT * FROM {$pre}arag_marketer_commissions WHERE order_id=%d",
        $oid
    ), ARRAY_A );

    $orders_out[] = [
        'order_id'         => $oid,
        'order_number'     => $order_num,
        'shop'             => $shop['shop_name'],
        'total'            => $sub,
        'payment_status'   => $sc['pay'] === 'cod' ? 'cod' : 'paid',
        'order_status'     => $sc['status'],
        'marketer_amount'  => $comm['marketer_amount'] ?? 0,
        'site_amount'      => $comm['site_amount'] ?? 0,
        'commission_status'=> $comm['status'] ?? null,
    ];
}

$acc = Arag_Marketer::get_by_id( $mid );
$out['steps'][] = 'orders_created';
$out['orders']  = $orders_out;
$out['summary'] = [
    'marketer'         => $acc['display_name'],
    'code'             => $acc['marketer_code'],
    'phone_login'      => $mkt_phone,
    'shops'            => (int) $acc['shops_count'],
    'orders_count'     => (int) $acc['orders_count'],
    'total_sales'      => (float) $acc['total_sales'],
    'total_earned'     => (float) $acc['total_earned'],
    'balance_payable'  => (float) $acc['balance_payable'],
    'credit_balance'   => (float) $acc['credit_balance'],
    'panel'            => ACC_URL . 'shop-marketer.php',
    'admin_tab'        => ACC_URL . 'shop-admin.php',
];
$out['success'] = true;

echo json_encode( $out, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
