<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
ini_set('display_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;
}

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

$api = $mt5->api;

// ----------------------
// Fetch all live accounts
// ----------------------
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$accounts = $stmt->get_result();

$closed_trades = [];
$total_lot = 0;
$total_profit = 0;

while ($acc = $accounts->fetch_assoc()) {
    $trade_id = (int)$acc['trade_id'];

    if ($api->DealGetTotal($trade_id, 0, 0, $total_deals) == MTRetCode::MT_RET_OK && $total_deals > 0) {

        $deals = [];
        if ($api->DealGetPage($trade_id, 0, 0, 0, $total_deals, $deals) == MTRetCode::MT_RET_OK) {

            foreach ($deals as $deal) {

                if (($deal->Order ?? 0) == 0 || ($deal->VolumeClosed ?? 0) <= 0) continue;

                $lot = round(($deal->VolumeClosed ?? 0) * 0.0001, 2);
                $profit = $deal->Profit ?? 0;

                $closed_trades[] = [
                    "trade_id" => $trade_id,
                    "Ticket" => $deal->Order,
                    "Symbol" => $deal->Symbol,
                    "Action" => ($deal->Action == 1 ? "Sell" : "Buy"),
                    "Volume" => $lot,
                    "OpenPrice" => $deal->PricePosition,
                    "ClosePrice" => $deal->Price,
                    "Profit" => $profit,
                    "CloseTime" => gmdate("Y-m-d H:i:s", $deal->Time)
                ];

                $total_lot += $lot;
                $total_profit += $profit;
            }
        }
    }
}

$mt5->api->Disconnect();

echo json_encode([
    "success" => true,
    "total_lot" => $total_lot,
    "total_profit_loss" => $total_profit,
    "closed_trades_count" => count($closed_trades),
    "closed_trades" => $closed_trades
]);
exit;
?>
