<?php
require_once '../../includes/functions.php';
setCORSHeaders();

// Verify API Hash using enhanced method
verifyAPIHashEnhanced();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

// Get authorization header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
    sendError('Authorization token required', 401);
}

$token = $matches[1];
$payload = verifyJWT($token);

if (!$payload || !isset($payload['user_id'])) {
    sendError('Invalid or expired token', 401);
}

$userId = $payload['user_id'];

error_log("=== User Orders API Called ===");
error_log("User ID: $userId");

// Get query parameters
$limit = (int)($_GET['limit'] ?? 20);
$offset = (int)($_GET['offset'] ?? 0);

error_log("Limit: $limit, Offset: $offset");

// Get user orders
$stmt = $pdo->prepare("
    SELECT o.id, o.quantity, o.total_coins, o.coin_type, o.telegram_link, o.status, o.created_at,
           p.id as product_id, p.name as product_name, p.price_coins as product_price, p.image_url
    FROM orders o
    JOIN products p ON o.product_id = p.id
    WHERE o.user_id = ?
    ORDER BY o.created_at DESC
    LIMIT " . (int)$limit . " OFFSET " . (int)$offset
);
$stmt->execute([$userId]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

error_log("Orders found: " . count($orders));
error_log("Orders data: " . json_encode($orders));

// Get total count
$stmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ?");
$stmt->execute([$userId]);
$totalCount = $stmt->fetchColumn();

error_log("Total orders count: $totalCount");

sendResponse([
    'success' => true,
    'data' => $orders,
    'pagination' => [
        'total' => $totalCount,
        'limit' => $limit,
        'offset' => $offset,
        'has_more' => ($offset + $limit) < $totalCount
    ]
]);
?>
