<?php
// miniapp/api/orders.php
error_reporting(0);
header('Content-Type: application/json; charset=utf-8');

require __DIR__ . '/config.php';

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;

if ($userId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'User ID required'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    // سفارش‌های کاربر
    $stmt1 = $pdo->prepare("
        SELECT id,
               plan_title,
               price,
               status,
               created_at,
               approved_at,
               rejected_at
        FROM orders
        WHERE user_id = ?
        ORDER BY created_at DESC
        LIMIT 100
    ");
    $stmt1->execute([$userId]);
    $orders = $stmt1->fetchAll(PDO::FETCH_ASSOC);

    // سرویس‌های این کاربر
    $stmt2 = $pdo->prepare("
        SELECT id,
               plan_title,
               price,
               delivered_at,
               expires_at,
               is_active
        FROM sales
        WHERE user_id = ?
        ORDER BY delivered_at DESC, id DESC
        LIMIT 100
    ");
    $stmt2->execute([$userId]);
    $sales = $stmt2->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'ok'   => true,
        'data' => [
            'orders' => $orders ?: [],
            'sales'  => $sales ?: [],
        ],
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode([
        'ok'   => false,
        'error'=> 'DB Error: ' . $e->getMessage(),
        'data' => ['orders' => [], 'sales' => []],
    ], JSON_UNESCAPED_UNICODE);
}
