<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/config.php';

// Read email from request
$data = json_decode(file_get_contents("php://input"), true);
$email = trim($data['email'] ?? '');

if (!$email) {
    echo json_encode([
        "success" => false,
        "message" => "Email is required",
        "recentTransactions" => []
    ]);
    exit;
}

try {
    $recentTransactions = [];

    // Helper function to convert CENT → USD
    // Helper function to format amount (NO cent conversion)
function convertCentAmount($row) {
    if (isset($row['amount'])) {
        $row['amount'] = number_format(floatval($row['amount']), 2, '.', '');
    }
    return $row;
}


    // -----------------------------
    // 1️⃣ Deposit Requests (pending)
    // -----------------------------
    $depositQuery = "
        SELECT 'deposit_requests' AS source, dr.id, dr.user_id, dr.trade_id, dr.amount,
               dr.type, dr.comment, dr.transaction_proof, dr.status, dr.admin_comment,
               dr.created_at AS date, lu.email, la.account_name, la.account_type
        FROM deposit_requests dr
        JOIN loginusers lu ON dr.user_id = lu.id
        JOIN liveaccounts la ON la.trade_id = dr.trade_id
        WHERE lu.email = ?
          AND dr.status='pending'
          AND la.account_type != 'Demo'
        ORDER BY dr.created_at DESC
    ";

    $stmt = $conn->prepare($depositQuery);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $recentTransactions[] = convertCentAmount($row);
    }

    // -----------------------------
    // 2️⃣ Wallet Deposits
    // -----------------------------
    $walletQuery = "
        SELECT 'wallet_deposit' AS source, wd.id, wd.email, wd.trade_id,
               wd.deposit_amount AS amount, wd.deposit_type AS type,
               wd.image AS transaction_proof, wd.Status AS status,
               wd.AdminRemark AS admin_comment, wd.deposed_date AS date,
               la.account_name, la.account_type
        FROM wallet_deposit wd
        JOIN liveaccounts la ON la.trade_id = wd.trade_id
        WHERE wd.email = ?
          AND la.account_type != 'Demo'
        ORDER BY wd.deposed_date DESC
    ";

    $stmt2 = $conn->prepare($walletQuery);
    $stmt2->bind_param("s", $email);
    $stmt2->execute();
    $result2 = $stmt2->get_result();

    while ($row = $result2->fetch_assoc()) {
        $recentTransactions[] = convertCentAmount($row);
    }

    // -----------------------------
    // 3️⃣ Wallet Withdrawals
    // -----------------------------
    $walletWithdrawQuery = "
        SELECT 'wallet_withdraw' AS source, ww.id, ww.email, ww.trade_id,
               ww.withdraw_amount AS amount, ww.withdraw_type AS type,
               ww.Status AS status, ww.AdminRemark AS admin_comment,
               ww.withdraw_date AS date, la.account_name, la.account_type
        FROM wallet_withdraw ww
        JOIN liveaccounts la ON la.trade_id = ww.trade_id
        WHERE ww.email = ?
          AND la.account_type != 'Demo'
        ORDER BY ww.withdraw_date DESC
    ";

    $stmt3 = $conn->prepare($walletWithdrawQuery);
    $stmt3->bind_param("s", $email);
    $stmt3->execute();
    $result3 = $stmt3->get_result();

    while ($row = $result3->fetch_assoc()) {
        $recentTransactions[] = convertCentAmount($row);
    }

    // -----------------------------
    // 4️⃣ Withdrawal Requests (pending)
    // -----------------------------
    $withdrawQuery = "
        SELECT 'withdrawal_requests' AS source, wr.id, wr.user_id, wr.trade_id,
               wr.amount, wr.type, wr.comment, wr.withdrawal_method,
               wr.status, wr.admin_comment, wr.created_at AS date,
               wr.email, la.account_name, la.account_type
        FROM withdrawal_requests wr
        JOIN liveaccounts la ON la.trade_id = wr.trade_id
        WHERE wr.email = ?
          AND wr.status='pending'
          AND la.account_type != 'Demo'
        ORDER BY wr.created_at DESC
    ";

    $stmt4 = $conn->prepare($withdrawQuery);
    $stmt4->bind_param("s", $email);
    $stmt4->execute();
    $result4 = $stmt4->get_result();

    while ($row = $result4->fetch_assoc()) {
        $recentTransactions[] = convertCentAmount($row);
    }

    // -----------------------------
    // 5️⃣ Internal Transfers
    // -----------------------------
    $internalQuery = "
        SELECT 'internal_transfers' AS source, it.id, it.user_id, it.from_trade AS trade_id,
               it.to_trade, it.amount, it.ticket_from, it.ticket_to,
               it.status, it.notes, it.created_at AS date,
               la.account_name, la.account_type
        FROM internal_transfers it
        JOIN liveaccounts la ON la.trade_id = it.from_trade
        WHERE it.user_id = (SELECT id FROM loginusers WHERE email = ?)
          AND la.account_type != 'Demo'
        ORDER BY it.created_at DESC
    ";

    $stmt5 = $conn->prepare($internalQuery);
    $stmt5->bind_param("s", $email);
    $stmt5->execute();
    $result5 = $stmt5->get_result();

    while ($row = $result5->fetch_assoc()) {
        $recentTransactions[] = convertCentAmount($row);
    }

    // Sort all transactions by date DESC
    usort($recentTransactions, function($a, $b) {
        return strtotime($b['date']) - strtotime($a['date']);
    });

    echo json_encode([
        "success" => true,
        "recentTransactions" => $recentTransactions
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error fetching transactions: " . $e->getMessage(),
        "recentTransactions" => []
    ]);
}
?>
