<?php
/**
 * تست end-to-end پرداخت فروشگاه عرقیات (روش demo / sandbox)
 * اجرا: php run-arag-payment-test.php
 */
declare(strict_types=1);

define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

$api = 'http://localhost/acc-engine/api.php/acc/v1';
$phone = '09125555879'; /* مشتری 5879 */

function api_post(string $url, array $body, ?string $token = null): array {
    $ch = curl_init($url);
    $headers = ['Content-Type: application/json'];
    if ($token) $headers[] = 'Authorization: Bearer ' . $token;
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_POSTFIELDS     => json_encode($body, JSON_UNESCAPED_UNICODE),
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    return json_decode((string) $raw, true) ?: ['raw' => $raw];
}

function api_get(string $url, string $token): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $token],
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    return json_decode((string) $raw, true) ?: ['raw' => $raw];
}

global $wpdb;

$pkg = $wpdb->get_row(
    "SELECT p.id, p.price, p.label, v.name AS variant_name, f.name AS family_name
     FROM {$wpdb->prefix}arag_packages p
     INNER JOIN {$wpdb->prefix}arag_variants v ON v.id = p.variant_id
     INNER JOIN {$wpdb->prefix}arag_families f ON f.id = v.family_id
     WHERE p.is_active = 1
     ORDER BY p.id ASC LIMIT 1"
);

if (!$pkg) {
    echo json_encode(['ok' => false, 'error' => 'هیچ بسته فعالی در arag_packages نیست — ابتدا run-arag-seed.php را اجرا کنید'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

/* 1) OTP */
$otpSend = api_post($api . '/public/arag/auth/send-otp', ['phone' => $phone]);
$code = $otpSend['demo_code'] ?? $otpSend['code'] ?? null;
if (!$code) {
    echo json_encode(['ok' => false, 'step' => 'send-otp', 'response' => $otpSend], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

/* 2) Login */
$login = api_post($api . '/public/arag/auth/verify-otp', ['phone' => $phone, 'code' => $code]);
$token = $login['token'] ?? '';
$user  = $login['user'] ?? null;
if (!$token || !$user) {
    echo json_encode(['ok' => false, 'step' => 'verify-otp', 'response' => $login], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

/* 3) Create order — demo payment */
$order = api_post($api . '/public/arag/orders/create', [
    'items' => [['package_id' => (int) $pkg->id, 'qty' => 1]],
    'billing' => [
        'name'    => $user['display_name'] ?? 'مشتری تست',
        'phone'   => $phone,
        'address' => 'تهران، خیابان ولیعصر، پلاک ۱۲۳، واحد ۴',
        'city'    => 'تهران',
    ],
    'shipping_method' => 'post',
    'payment_method'  => 'demo',
    'user_id'         => (int) ($user['id'] ?? 0),
], $token);

$data = $order['data'] ?? [];
if (($data['payment_status'] ?? '') !== 'paid') {
    echo json_encode(['ok' => false, 'step' => 'create-order', 'response' => $order], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

/* 4) Dashboard + orders list */
$dashboard = api_get($api . '/public/arag/account/dashboard', $token);
$orders    = api_get($api . '/public/arag/account/orders', $token);
$found     = null;
foreach (($orders['data'] ?? []) as $o) {
    if ((int) ($o['id'] ?? 0) === (int) ($data['order_id'] ?? 0)) {
        $found = $o;
        break;
    }
}

echo json_encode([
    'ok'      => true,
    'message' => 'پرداخت آزمایشی با موفقیت ثبت شد — در داشبورد کاربر قابل مشاهده است',
    'user'    => [
        'id'           => $user['id'] ?? null,
        'display_name' => $user['display_name'] ?? null,
        'phone'        => $phone,
    ],
    'product' => [
        'package_id' => (int) $pkg->id,
        'label'      => "{$pkg->family_name} — {$pkg->variant_name} — {$pkg->label}",
        'price'      => (float) $pkg->price,
    ],
    'order' => [
        'id'             => $data['order_id'] ?? null,
        'order_number'   => $data['order_number'] ?? null,
        'total'          => $data['total'] ?? null,
        'payment_status' => $data['payment_status'] ?? null,
        'ref_id'         => $data['ref_id'] ?? null,
        'redirect_url'   => $data['redirect_url'] ?? null,
    ],
    'dashboard' => [
        'orders_count' => $dashboard['stats']['orders_count'] ?? null,
        'recent'       => $dashboard['recent_orders'] ?? [],
    ],
    'order_in_list' => $found ? [
        'id'             => $found['id'],
        'order_number'   => $found['order_number'],
        'payment_status' => $found['payment_status'],
        'order_status'   => $found['order_status'],
        'total'          => $found['total'],
    ] : null,
    'links' => [
        'shop_checkout' => 'http://localhost/acc-engine/shop.php?p=bidmeshk',
        'account'       => 'http://localhost/acc-engine/account.php#orders',
        'success'       => $data['redirect_url'] ?? null,
    ],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
