<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle OPTIONS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . "/config.php";    // DB constants + $conn
include_once __DIR__ . "/connection.php"; // MT5 API connection

const PRICE_DEC = 3;
const VOL_DEC   = 2;

function r($n, $dec = 2) { 
    return $n === null ? null : round((float)$n, $dec); 
}

function lot($raw) { 
    return r(((float)$raw) * 0.0001, VOL_DEC); 
}

function ts_kolkata($sec, $ms = null) {
    if ($sec === null) return null;
    if ($ms !== null) {
        $dt = (new DateTime('@'.floor($ms/1000)))->setTimezone(new DateTimeZone("Asia/Kolkata"));
        $msOnly = $ms % 1000;
        return $dt->format("Y-m-d H:i:s") . "." . $msOnly;
    }
    return (new DateTime('@'.$sec))->setTimezone(new DateTimeZone("Asia/Kolkata"))->format("Y-m-d H:i:s");
}

// Get POST JSON input
$input = json_decode(file_get_contents("php://input"), true);
$email = $input['email'] ?? null;
if (!$email) { 
    echo json_encode(["success"=>false,"message"=>"Email is required"]); 
    exit; 
}

// Fetch all MT5 logins for this email from loginusers / liveaccounts
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => "No MT5 accounts found for this email"]);
    exit;
}

$mt5_logins = [];
while ($row = $result->fetch_assoc()) {
    $mt5_logins[] = $row['trade_id'];
}

// Initialize MT5 API
$api = new MTWebAPI("WebAPI", "./logs", true);
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success"=>false,"message"=>"Failed to connect MT5","error_code"=>$ret]);
    exit;
}

// Prepare final stats
$all_accounts = [];
$total_profit = 0;
$total_loss = 0;
$profitable_count = 0;
$loss_count = 0;

foreach ($mt5_logins as $mt5_login) {
    $total = 0;
    $closed_positions = [];

    if (($err = $api->DealGetTotal((int)$mt5_login, 0, 0, $total)) == MTRetCode::MT_RET_OK && $total > 0) {
        $deals = [];
        if (($err = $api->DealGetPage((int)$mt5_login, 0, 0, 0, $total, $deals)) == MTRetCode::MT_RET_OK && is_array($deals)) {
            $account_profit = 0;
            foreach ($deals as $deal) {
                if (($deal->Order ?? 0) != 0 && lot($deal->VolumeClosed ?? 0) > 0) {
                    $profit = r($deal->Profit ?? 0, 2);
                    $closed_positions[] = [
                        // "OpenTime"   => ts_kolkata($deal->Time ?? null),
                        "Ticket"     => $deal->Order ?? null,
                        "Action"     => (($deal->Action ?? 0) == 1 ? "Sell" : "Buy"),
                        "Volume"     => lot($deal->VolumeClosed ?? 0),
                        "Symbol"     => $deal->Symbol ?? null,
                        "OpenPrice"  => r($deal->PricePosition ?? null, PRICE_DEC),
                        "ClosePrice" => r($deal->Price ?? null, PRICE_DEC),
                        // "CloseTime"  => ts_kolkata(null, $deal->TimeMsc ?? null),
                        "CloseTime"  => ts_kolkata($deal->Time ?? null, $deal->TimeMsc ?? null),
                        "Commission" => r($deal->Commission ?? 0, 2),
                        "Swap"       => r($deal->Storage ?? 0, 2),
                        "Profit"     => $profit
                    ];
                    $account_profit += $profit;
                }
            }

            if ($account_profit >= 0) {
                $profitable_count++;
                $total_profit += $account_profit;
            } else {
                $loss_count++;
                $total_loss += $account_profit;
            }
        }
    }

    $all_accounts[] = [
        "mt5_login" => $mt5_login,
        "total_closed_positions" => count($closed_positions),
        "closed_positions" => $closed_positions,
    ];
}

// Disconnect MT5
$api->Disconnect();

// Return final JSON
echo json_encode([
    "success" => true,
    "email" => $email,
    "total_accounts" => count($mt5_logins),
    "profitable_accounts" => $profitable_count,
    "loss_accounts" => $loss_count,
    "total_profit" => r($total_profit, 2),
    "total_loss" => r($total_loss, 2),
    "accounts" => $all_accounts
]);
