<?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");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/config.php'; // Make sure $conn is defined here

// Read email from request body
$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 = [];

    // -----------------------------
    // 1️⃣ Deposit Requests (only 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
        FROM deposit_requests dr
        JOIN loginusers lu ON dr.user_id = lu.id
        LEFT JOIN liveaccounts la ON la.trade_id = dr.trade_id
        WHERE lu.email = ? AND dr.status='pending'
        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[] = $row;
    }

    // -----------------------------
    // 2️⃣ Wallet Deposits (approved transactions)
    // -----------------------------
    $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
        FROM wallet_deposit wd
        LEFT JOIN liveaccounts la ON la.trade_id = wd.trade_id
        WHERE wd.email = ?
        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[] = $row;
    }

    // -----------------------------
    // 3️⃣ Wallet Withdrawals (approved transactions)
    // -----------------------------
    $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
        FROM wallet_withdraw ww
        LEFT JOIN liveaccounts la ON la.trade_id = ww.trade_id
        WHERE ww.email = ?
        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[] = $row;
    }

    // -----------------------------
    // 4️⃣ Withdrawal Requests (only 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
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts la ON la.trade_id = wr.trade_id
        WHERE wr.email = ? AND wr.status='pending'
        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[] = $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
        FROM internal_transfers it
        LEFT JOIN liveaccounts la ON la.trade_id = it.from_trade
        WHERE it.user_id = (SELECT id FROM loginusers WHERE email = ?)
        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[] = $row;
    }

    // -----------------------------
    // 🧮 Totals Calculation Section
    // -----------------------------
    $totals = [
        "total_deposits" => 0,
        "total_withdraws" => 0,
        "total_internal_transfers" => 0
    ];

    // Total Deposits
    $totalDepositQuery = "SELECT IFNULL(SUM(deposit_amount), 0) AS total_deposits FROM wallet_deposit WHERE email = ?";
    $stmt6 = $conn->prepare($totalDepositQuery);
    $stmt6->bind_param("s", $email);
    $stmt6->execute();
    $result6 = $stmt6->get_result()->fetch_assoc();
    $totals["total_deposits"] = (float)$result6['total_deposits'];

    // Total Withdraws
    $totalWithdrawQuery = "SELECT IFNULL(SUM(withdraw_amount), 0) AS total_withdraws FROM wallet_withdraw WHERE email = ?";
    $stmt7 = $conn->prepare($totalWithdrawQuery);
    $stmt7->bind_param("s", $email);
    $stmt7->execute();
    $result7 = $stmt7->get_result()->fetch_assoc();
    $totals["total_withdraws"] = (float)$result7['total_withdraws'];

    // Total Internal Transfers
    $totalInternalQuery = "
    SELECT IFNULL(SUM(amount), 0) AS total_internal_transfers
    FROM internal_transfers
    WHERE user_id = (SELECT id FROM loginusers WHERE email = ?)
    AND status = 'approved'
";

    $stmt8 = $conn->prepare($totalInternalQuery);
    $stmt8->bind_param("s", $email);
    $stmt8->execute();
    $result8 = $stmt8->get_result()->fetch_assoc();
    $totals["total_internal_transfers"] = (float)$result8['total_internal_transfers'];

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

    // -----------------------------
    // Return JSON
    // -----------------------------
    echo json_encode([
        "success" => true,
        "recentTransactions" => $recentTransactions,
        "totals" => $totals
    ]);

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