<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/_vpn_helpers.php';
header('Content-Type: application/json; charset=utf-8');

try {
    $uid = (int)($_REQUEST['user_id'] ?? 0);
    if ($uid <= 0) { echo json_encode(['ok'=>false,'error'=>'user_id required'], JSON_UNESCAPED_UNICODE); exit; }
    $page = max(1, (int)($_GET['page'] ?? 1));
    $limit = 10;
    $offset = ($page - 1) * $limit;

    if (function_exists('vpnEnsureColumns')) vpnEnsureColumns($pdo);

    $statusLabels = [
        'WAITING_PAYMENT' => 'در انتظار پرداخت',
        'PENDING' => 'در انتظار بررسی',
        'QUEUED' => 'در صف تحویل',
        'DELIVERED' => 'تحویل‌شده',
        'CANCELLED' => 'لغوشده',
        'REJECTED' => 'ردشده',
        'FAILED' => 'ناموفق',
    ];

    $st = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_id=?");
    $st->execute([$uid]);
    $totalOrders = (int)$st->fetchColumn();

    $st = $pdo->prepare("SELECT * FROM orders WHERE user_id=? ORDER BY created_at DESC, id DESC LIMIT {$limit} OFFSET {$offset}");
    $st->execute([$uid]);
    $orders = [];
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $o) {
        $duration = (string)($o['duration'] ?? '1M');
        $orders[] = [
            'id' => (int)$o['id'],
            'status' => (string)($o['status'] ?? ''),
            'status_label' => $statusLabels[(string)($o['status'] ?? '')] ?? (string)($o['status'] ?? ''),
            'price' => (int)($o['price'] ?? 0),
            'price_formatted' => number_format((int)($o['price'] ?? 0)) . ' تومان',
            'duration' => $duration,
            'duration_label' => function_exists('getDurationLabel') ? getDurationLabel($duration) : $duration,
            'seats' => max(1, (int)($o['requested_seats'] ?? $o['seats'] ?? 1)),
            'service_type' => (string)($o['service_type'] ?? 'openvpn_l2tp'),
            'created_at' => $o['created_at'] ?? '',
            'created_jalali' => function_exists('jdate') && !empty($o['created_at']) ? jdate('Y/m/d H:i', strtotime($o['created_at'])) : (string)($o['created_at'] ?? ''),
        ];
    }

    $countSql = "SELECT COUNT(*) FROM deliveries d JOIN orders o ON o.id=d.order_id WHERE o.user_id=?";
    $st = $pdo->prepare($countSql);
    $st->execute([$uid]);
    $totalServices = (int)$st->fetchColumn();

    $sql = "SELECT d.*, c.protocol AS credential_protocol, o.duration AS order_duration, o.plan_title, o.requested_seats, o.service_type AS order_service_type, o.traffic_type AS order_traffic_type, o.traffic_limit_gb AS order_traffic_limit_gb, o.created_at AS order_created_at, pc.service_name AS category_service_name
            FROM deliveries d
            JOIN orders o ON o.id=d.order_id
            LEFT JOIN credentials c ON c.id=d.credential_id
            LEFT JOIN plan_categories pc ON pc.id=o.category_id
            WHERE o.user_id=?
            ORDER BY d.delivered_at DESC, d.id DESC
            LIMIT {$limit} OFFSET {$offset}";
    $st = $pdo->prepare($sql);
    $st->execute([$uid]);
    $sales = [];
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $d) {
        $username = (string)($d['username'] ?? $d['email'] ?? '');
        $password = (string)($d['password'] ?? '');
        $serviceType = (string)($d['service_type'] ?? $d['credential_protocol'] ?? $d['order_service_type'] ?? 'openvpn_l2tp');
        $serviceType = function_exists('gemaccServiceTypeFromHint') ? gemaccServiceTypeFromHint($serviceType) : $serviceType;
        $expires = (string)($d['expires_at'] ?? '');
        $status = (!empty($expires) && strtotime($expires) && strtotime($expires) < time()) ? 'EXPIRED' : 'ACTIVE';
        $trafficType = strtolower((string)($d['traffic_type'] ?? $d['order_traffic_type'] ?? 'unlimited'));
        $trafficLimit = $d['traffic_limit_gb'] ?? $d['order_traffic_limit_gb'] ?? null;
        $trafficLabel = $trafficType === 'limited' ? ('حجمی ' . (int)$trafficLimit . ' گیگ') : 'نامحدود';
        $item = [
            'id' => (int)$d['id'],
            'order_id' => (int)$d['order_id'],
            'username' => $username,
            'email' => $username,
            'password' => $password,
            'config_text' => (string)($d['config_text'] ?? ''),
            'qr_code_file_id' => (string)($d['qr_code_file_id'] ?? ''),
            'qr_code_path' => (string)($d['qr_code_path'] ?? ''),
            'qr_code_url' => ($serviceType === 'v2ray' && (!empty($d['qr_code_file_id']) || !empty($d['qr_code_path']))) ? ('api/v2ray_qr.php?delivery_id='.(int)$d['id']) : '',
            'service_type' => $serviceType,
            'service_name' => (string)($d['category_service_name'] ?? $d['plan_title'] ?? ''),
            'seats' => max(1, (int)($d['seats_allocated'] ?? $d['requested_seats'] ?? 1)),
            'status' => $status,
            'traffic_label' => $trafficLabel,
            'delivered_at' => $d['delivered_at'] ?? '',
            'delivered_jalali' => function_exists('jdate') && !empty($d['delivered_at']) ? jdate('Y/m/d H:i', strtotime($d['delivered_at'])) : (string)($d['delivered_at'] ?? ''),
            'expires_at' => $expires,
            'expires_jalali' => function_exists('jdate') && !empty($expires) ? jdate('Y/m/d', strtotime($expires)) : (string)$expires,
            'l2tp_server' => defined('L2TP_SERVER') ? L2TP_SERVER : '',
            'openvpn_config_url' => defined('OPENVPN_CONFIG_URL') ? OPENVPN_CONFIG_URL : '',
        ];
        if ($serviceType === 'windscribe' && function_exists('gemaccWindscribeNoticePlain')) {
            $item['rules_text'] = gemaccWindscribeNoticePlain($username, $password);
        }
        $sales[] = $item;
    }

    echo json_encode(['ok'=>true,'data'=>[
        'orders'=>$orders,
        'sales'=>$sales,
        'total_orders'=>$totalOrders,
        'total_services'=>$totalServices,
        'page'=>$page,
        'limit'=>$limit,
    ]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    error_log('[orders_api] '.$e->getMessage());
    echo json_encode(['ok'=>false,'error'=>$e->getMessage()], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
