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

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

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

$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 account_type != 'demo'
         )
           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 account_type != 'demo'
         )
           AND Status = 1) AS total_withdraw
");

$stmt->bind_param("ii", $user_id, $user_id);
$stmt->execute();
$totalsDB = $stmt->get_result()->fetch_assoc();
// NEW: Cent-only deposits & withdrawals
// $stmtCent = $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 account_type LIKE '%Cent%')
//           AND Status = 1) AS cent_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 account_type LIKE '%Cent%')
//           AND Status = 1) AS cent_withdraw
// ");
// Cent totals excluding demo accounts
$stmtCent = $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 account_type LIKE '%Cent%' AND account_type != 'demo'
         )
           AND Status = 1) AS cent_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 account_type LIKE '%Cent%' AND account_type != 'demo'
         )
           AND Status = 1) AS cent_withdraw
");

$stmtCent->bind_param("ii", $user_id, $user_id);
$stmtCent->execute();
$centTotals = $stmtCent->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;
// NEW: Cent + Normal totals
$cent_balance = 0;
$cent_profit = 0;
$cent_equity = 0;

$normal_balance = 0;
$normal_profit = 0;
$normal_equity = 0;

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;
            $stats = get_mt5_stats($conn, $api, (int)$trade_id, 300, $force_refresh);
            $floating_profit = (float)$stats['sumProfit'];

            $equity = $balance + $floating_profit;
            // -------- NEW: detect Cent accounts --------
// Skip demo accounts entirely
if (strtolower($account_type) == 'demo') {
    continue; // skip this iteration
}

if (stripos($account_type, "Cent") !== false) {
    $cent_balance += $balance;
    $cent_profit += $floating_profit;
    $cent_equity += $equity;
} else {
    $normal_balance += $balance;
    $normal_profit += $floating_profit;
    $normal_equity += $equity;
}


        }
    } 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
];

// Do NOT double count
if (stripos($account_type, "Cent") !== false) {
    // Cent accounts
    $total_balance += $equity;
} else {
    // Normal accounts
    $total_balance += $equity;
}

// Total profit is sum of all
$total_profit_all = $cent_profit + $normal_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,

    // NEW: CENT TOTALS
    "cent_balance" => $cent_balance,
    "cent_equity" => $cent_equity,
    "cent_profit" => $cent_profit,
    "cent_deposit" => (float)$centTotals['cent_deposit'],
    "cent_withdraw" => (float)$centTotals['cent_withdraw'],

    // NEW: NORMAL TOTALS
    "normal_balance" => $normal_balance,
    "normal_equity" => $normal_equity,
    "normal_profit" => $normal_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
]);
?>
