<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

// Enable PHP error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "config.php"; // DB connection
include "connection.php"; // MT5 connection

$data = json_decode(file_get_contents("php://input"), true);
$user_id = $data['user_id'] ?? 0;

if (!$user_id) {
    echo json_encode(["success" => false, "message" => "Missing user id"]);
    exit;
}

// Initialize MT5 connection
$mt5 = new MT5Connection(); 
if (!$mt5->connect()) {
    echo json_encode([
        "success" => false,
        "message" => "MT5 connection failed, error code: " . $mt5->lastError()
    ]);
    exit;
}

$api = $mt5->api; // $api is ready to use

// 1️⃣ Get total approved deposits and withdrawals from wallet tables
$stmt = $conn->prepare("
    SELECT 
        (SELECT COALESCE(SUM(CAST(deposit_amount AS DECIMAL(18,2))),0) 
         FROM wallet_deposit 
         WHERE trade_id IN (SELECT trade_id FROM liveaccounts WHERE user_id = ?)
           AND Status = 1) AS total_deposit,
        (SELECT COALESCE(SUM(CAST(withdraw_amount AS DECIMAL(18,2))),0) 
         FROM wallet_withdraw 
         WHERE trade_id IN (SELECT trade_id FROM liveaccounts WHERE user_id = ?)
           AND Status = 1) AS total_withdraw
");
$stmt->bind_param("ii", $user_id, $user_id);
$stmt->execute();
$totalsDB = $stmt->get_result()->fetch_assoc();

// 2️⃣ Get active MT5 accounts including account_type
$stmt2 = $conn->prepare("SELECT trade_id, account_name, leverage, Balance, account_type FROM liveaccounts WHERE user_id = ?");
$stmt2->bind_param("i", $user_id);
$stmt2->execute();
$result2 = $stmt2->get_result();

$activeAccounts = [];
$total_balance = 0;
$total_profit_all = 0; // <-- sum of all floating profits

while ($row = $result2->fetch_assoc()) {
    $trade_id = $row['trade_id'];
    $account_name = $row['account_name'];
    $leverage = $row['leverage'];
    $account_type = $row['account_type'];
    $balance_db = is_numeric($row['Balance']) ? (float)$row['Balance'] : 0;

    $balance = $balance_db;
    $floating_profit = 0;
    $equity = $balance_db;

    // Fetch live data from MT5 safely
    try {
        if (($error_code = $api->UserAccountGet($trade_id, $account)) == MTRetCode::MT_RET_OK && isset($account->Balance)) {
            $balance = (float)$account->Balance;
            $floating_profit = (float)($account->Floating ?? 0);
            $equity = $balance + $floating_profit;
        }
    } catch (Exception $e) {
        $balance = $balance_db;
        $floating_profit = 0;
        $equity = $balance;
    }

    $activeAccounts[] = [
        "trade_id" => $trade_id,
        "account_name" => $account_name,
        "account_type" => $account_type,
        "Balance" => $balance,
        "leverage" => $leverage,
        "total_profit" => $floating_profit,
        "equity" => $equity
    ];

    $total_balance += $equity;
    $total_profit_all += $floating_profit; // <-- sum profit
}

// 3️⃣ Totals including total profit
$totals = [
    "total_balance" => $total_balance,
    "total_deposit" => (float)$totalsDB['total_deposit'],
    "total_withdraw" => (float)$totalsDB['total_withdraw'],
    "total_profit" => $total_profit_all, // <-- added total profit
    "mt5_accounts" => count($activeAccounts)
];

// 4️⃣ Get recent transactions (only approved deposits and withdrawals)
$stmt3 = $conn->prepare("
    SELECT id, 'Deposit' AS type, deposit_amount AS amount, deposed_date AS date
    FROM wallet_deposit
    WHERE trade_id IN (SELECT trade_id FROM liveaccounts WHERE user_id = ?)
      AND Status = 1
    UNION ALL
    SELECT id, 'Withdrawal' AS type, withdraw_amount AS amount, withdraw_date AS date
    FROM wallet_withdraw
    WHERE trade_id IN (SELECT trade_id FROM liveaccounts WHERE user_id = ?)
      AND Status = 1
    ORDER BY date DESC
    LIMIT 5
");
$stmt3->bind_param("ii", $user_id, $user_id);
$stmt3->execute();
$result3 = $stmt3->get_result();

$recentTransactions = [];
while($row = $result3->fetch_assoc()){
    $recentTransactions[] = [
        "id" => $row['id'],
        "type" => $row['type'],
        "amount" => is_numeric($row['amount']) ? (float)$row['amount'] : 0,
        "date" => $row['date'],
        "status" => "Completed"
    ];
}

// 5️⃣ Return final JSON
echo json_encode([
    "success" => true,
    "totals" => $totals,
    "activeAccounts" => $activeAccounts,
    "recentTransactions" => $recentTransactions
]);
?>
