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

// Verify API Hash
verifyAPIHash();

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

// Get user token from headers
$headers = getallheaders();
$token = $headers['Authorization'] ?? '';

if (empty($token)) {
    sendError('Authorization token required', 401);
}

// Verify JWT token
$payload = verifyJWT($token);
if (!$payload) {
    sendError('Invalid or expired token', 401);
}

$userId = $payload['user_id'];

try {
    // Log the request
    error_log("User Purchases API - User ID: $userId");
    
    // Get pagination parameters
    $page = (int)($_GET['page'] ?? 1);
    $limit = (int)($_GET['limit'] ?? 20);
    $offset = ($page - 1) * $limit;
    
    // Get user's coin purchases
    $stmt = $pdo->prepare("
        SELECT cp.id, cp.product_id, cp.purchase_token, cp.order_id, cp.coins, cp.price, 
               cp.currency, cp.status, cp.purchase_time, cp.created_at,
               pkg.name as package_name
        FROM coin_purchases cp
        JOIN coin_packages pkg ON cp.package_id = pkg.id
        WHERE cp.user_id = ?
        ORDER BY cp.created_at DESC
        LIMIT " . (int)$limit . " OFFSET " . (int)$offset . "
    ");
    $stmt->execute([$userId]);
    $purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get total count
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM coin_purchases WHERE user_id = ?");
    $stmt->execute([$userId]);
    $totalCount = $stmt->fetchColumn();
    
    error_log("User Purchases API - Total purchases found: $totalCount");
    
    // Calculate pagination info
    $totalPages = ceil($totalCount / $limit);
    $hasNextPage = $page < $totalPages;
    $hasPrevPage = $page > 1;
    
    sendResponse([
        'success' => true,
        'message' => 'User purchases retrieved successfully',
        'data' => [
            'purchases' => $purchases,
            'pagination' => [
                'current_page' => $page,
                'total_pages' => $totalPages,
                'total_count' => $totalCount,
                'limit' => $limit,
                'has_next_page' => $hasNextPage,
                'has_prev_page' => $hasPrevPage
            ]
        ]
    ]);
    
} catch (Exception $e) {
    error_log("User Purchases API Error: " . $e->getMessage());
    error_log("User Purchases API Stack Trace: " . $e->getTraceAsString());
    sendResponse([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'data' => null
    ], 500);
}
?>
