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

require __DIR__ . '/config.php';

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$page   = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$status = isset($_GET['status']) ? strtoupper(trim($_GET['status'])) : '';

if ($userId <= 0) {
    echo json_encode([
        'ok'    => false,
        'error' => 'شناسه کاربر نامعتبر است',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!isAdmin($userId)) {
    echo json_encode([
        'ok'    => false,
        'error' => 'فقط ادمین مجاز است',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $limit = 20;
    $offset = ($page - 1) * $limit;
    
    // ساخت کوئری با فیلتر وضعیت
    $whereClause = "";
    $params = [];
    
    if ($status && in_array($status, ['PENDING', 'APPROVED', 'REJECTED'])) {
        $whereClause = "WHERE o.status = :status";
        $params[':status'] = $status;
    }
    
    // تعداد کل سفارش‌ها
    $countSql = "SELECT COUNT(*) as count FROM orders o $whereClause";
    if ($status) {
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetch()['count'] ?? 0;
    } else {
        $total = $pdo->query("SELECT COUNT(*) as count FROM orders")->fetch()['count'] ?? 0;
    }
    $total_pages = ceil($total / $limit);
    
    $sql = "SELECT o.id, o.user_id, o.plan_code, o.plan_title, o.price, o.status, o.created_at, o.approved_at, o.rejected_at, 
                   u.username, u.first_name, u.last_name 
            FROM orders o 
            LEFT JOIN users u ON o.user_id = u.id 
            $whereClause
            ORDER BY o.id DESC 
            LIMIT :limit OFFSET :offset";
    
    $stmt = $pdo->prepare($sql);
    if ($status) {
        $stmt->bindValue(':status', $status, PDO::PARAM_STR);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'ok'    => true,
        'data'  => [
            'orders'      => $orders,
            'current_page'=> $page,
            'total_pages' => (int)$total_pages,
            'total_orders'=> (int)$total,
        ],
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode([
        'ok'    => false,
        'error' => 'خطا در خواندن سفارشات: ' . $e->getMessage(),
        'data'  => ['orders' => [], 'current_page' => $page, 'total_pages' => 0, 'total_orders' => 0],
    ], JSON_UNESCAPED_UNICODE);
}
