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

// Verify API Hash
verifyAPIHash();

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'];

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

// Get user transactions
$stmt = $pdo->prepare("
    SELECT id, type, amount, description, created_at
    FROM transactions
    WHERE user_id = ?
    ORDER BY created_at DESC
    LIMIT " . (int)$limit . " OFFSET " . (int)$offset
);
$stmt->execute([$userId]);
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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