<?php
require '../includes/db.php';
require '../includes/auth.php';

header('Content-Type: application/json');
session_start();

// Custom function to respond with error
function respondWithError($code, $msg, $msgCode) {
    echo json_encode([
        'code' => $code,
        'msg' => $msg,
        'msgCode' => $msgCode,
        'serviceNowTime' => date('Y-m-d H:i:s')
    ]);
    exit;
}

// ✅ Allow only POST or AJAX requests
$isAjax = strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'xmlhttprequest';
$isFetch = isset($_SERVER['HTTP_SEC_FETCH_MODE']) && $_SERVER['HTTP_SEC_FETCH_MODE'] === 'cors';

if (
    !isset($_SESSION['user_id']) ||           // Not logged in
    (!$isAjax && !$isFetch)                   // Not AJAX/fetch call
) {
    http_response_code(403);
    respondWithError(11, 'Method not allowed', 12);
}

$user_id = $_SESSION['user_id'];

// Fetch user currency
$stmt = $pdo->prepare("SELECT currency FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Fetch pay-in transactions
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE user_id = ? AND type = 'payin' ORDER BY id DESC");
$stmt->execute([$user_id]);
$payins = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Add currency to each transaction
foreach ($payins as &$txn) {
    $txn['currency'] = $user['currency'];
}

// ✅ Respond with actual data
echo json_encode($payins);
