<?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"; 
include "connection.php";

$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; // MTWebAPI instance ready

// ----------------------
// 1️⃣ Total Deposit & Withdraw
// ----------------------
$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️⃣ Fetch Active Accounts
// ----------------------
$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;
$total_liveaccounts = 0;

$all_open_trades = [];
$all_closed_trades = [];

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 account info from MT5
    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;
    }

    // // ✅ Fetch Open Positions (Live Trades)
    $open_positions = [];
    // $total_open_positions = 0;
    // if (($ret = $api->PositionGetTotal((int)$trade_id, $total_open_positions)) == MTRetCode::MT_RET_OK && $total_open_positions > 0) {
    //     $positions = [];
    //     if (($ret = $api->PositionGetPage((int)$trade_id, 0, $total_open_positions, $positions)) == MTRetCode::MT_RET_OK && is_array($positions)) {
    //         foreach ($positions as $pos) {
    //             $open_positions[] = [
    //                 "Symbol"       => $pos->Symbol ?? null,
    //                 "Action"       => (($pos->Action ?? 0) == 1 ? "Sell" : "Buy"),
    //                 "Volume"       => isset($pos->Volume) ? round($pos->Volume * 0.0001, 2) : 0,
    //                 "OpenPrice"    => $pos->PriceOpen ?? 0,
    //                 "CurrentPrice" => $pos->PriceCurrent ?? 0,
    //                 "Profit"       => $pos->Profit ?? 0,
    //                 "TimeCreate"   => isset($pos->TimeCreate) ? gmdate("Y-m-d H:i:s", $pos->TimeCreate) : null
    //             ];
    //         }
    //     }
    // }

    // // ✅ Fetch Closed Positions (Deals)
    $closed_positions = [];
    // $total_closed_positions = 0;
    // if (($err = $api->DealGetTotal((int)$trade_id, 0, 0, $total_closed_positions)) == MTRetCode::MT_RET_OK && $total_closed_positions > 0) {
    //     $deals = [];
    //     if (($err = $api->DealGetPage((int)$trade_id, 0, 0, 0, $total_closed_positions, $deals)) == MTRetCode::MT_RET_OK && is_array($deals)) {
    //         foreach ($deals as $deal) {
    //             if (($deal->Order ?? 0) != 0 && isset($deal->VolumeClosed) && $deal->VolumeClosed > 0) {
    //                 $closed_positions[] = [
    //                     "Ticket"     => $deal->Order ?? null,
    //                     "Symbol"     => $deal->Symbol ?? null,
    //                     "Action"     => (($deal->Action ?? 0) == 1 ? "Sell" : "Buy"),
    //                     "Volume"     => round(($deal->VolumeClosed ?? 0) * 0.0001, 2),
    //                     "OpenPrice"  => $deal->PricePosition ?? null,
    //                     "ClosePrice" => $deal->Price ?? null,
    //                     "Profit"     => $deal->Profit ?? 0,
    //                     "CloseTime"  => isset($deal->Time) ? gmdate("Y-m-d H:i:s", $deal->Time) : null
    //                 ];
    //             }
    //         }
    //     }
    // }

    // Merge for total user stats
    $all_open_trades = array_merge($all_open_trades, $open_positions);
    $all_closed_trades = array_merge($all_closed_trades, $closed_positions);

    $activeAccounts[] = [
        "trade_id" => $trade_id,
        "account_name" => $account_name,
        "account_type" => $account_type,
        "Balance" => $balance,
        "leverage" => $leverage,
        "total_profit" => $floating_profit,
        "equity" => $equity,
        // "open_trades_count" => count($open_positions),
        // "closed_trades_count" => count($closed_positions),
        // "open_trades" => $open_positions,
        // "closed_trades" => $closed_positions
    ];

    $total_balance += $equity;
    $total_profit_all += $floating_profit;
    $total_liveaccounts++;
}

// ----------------------
// 3️⃣ Totals Summary
// ----------------------
$totals = [
    "total_balance" => $total_balance,
    "total_deposit" => (float)$totalsDB['total_deposit'],
    "total_withdraw" => (float)$totalsDB['total_withdraw'],
    // "total_profit" => $total_profit_all,
    "total_liveaccounts" => $total_liveaccounts,
    // "total_open_trades" => count($all_open_trades),
    // "total_closed_trades" => count($all_closed_trades)
];

// ----------------------
// 4️⃣ Recent Transactions
// ----------------------
$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️⃣ Final Response
// ----------------------
$api->Disconnect();

echo json_encode([
    "success" => true,
    "totals" => $totals,
    "activeAccounts" => $activeAccounts,
    "recentTransactions" => $recentTransactions
]);
exit;
?>
