<?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");

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

// Includes: $conn (MySQLi), MT5Connection wrapper exposing ->api (MTWebAPI)
include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

/* ---------- helpers ---------- */
const PRICE_DEC = 3; // price decimals
const VOL_DEC   = 2; // lot decimals
function r($n, $dec = 2) { return $n === null ? null : round((float)$n, $dec); }
function lots_from_raw($raw) { return r(((float)$raw) * 0.0001, VOL_DEC); } // raw units -> lots
function ts_kolkata($sec, $ms = null) {
    if ($sec === null && $ms === null) return null;
    if ($ms !== null) {
        $dt = (new DateTime('@'.floor($ms/1000)))->setTimezone(new DateTimeZone("Asia/Kolkata"));
        return $dt->format("Y-m-d H:i:s") . "." . ($ms % 1000);
    }
    return (new DateTime('@'.$sec))->setTimezone(new DateTimeZone("Asia/Kolkata"))->format("Y-m-d H:i:s");
}
// Some bindings expose string enums; be robust
function is_deal_entry_out($entry) {
    return ($entry === 1 || $entry === 'DEAL_ENTRY_OUT' || $entry === 'Out' || $entry === 'out');
}

/* ---------- 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","accounts"=>[]]); exit; }

/* ---------- get logins for email ---------- */
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$res = $stmt->get_result();

$mt5_logins = [];
while ($row = $res->fetch_assoc()) {
    if (!empty($row['trade_id'])) $mt5_logins[] = (string)$row['trade_id'];
}
if (!$mt5_logins) { echo json_encode(["success"=>false,"message"=>"No MT5 accounts found for this email","accounts"=>[]]); exit; }

/* ---------- connect MT5 ---------- */
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode(["success"=>false,"message"=>"Failed to connect to MT5","error_code"=>$mt5->lastError()]); exit;
}

$all_accounts = [];
$from = strtotime("-30 days");
$to   = time();

/* ---------- per account ---------- */
foreach ($mt5_logins as $loginStr) {
    $login = (int)$loginStr;

    // ensure user exists
    $userMT5 = new MTUser();
    $ret = $mt5->api->UserGet($login, $userMT5);
    if ($ret != MTRetCode::MT_RET_OK) {
        $all_accounts[] = [
            "trade_id" => $loginStr,
            "error"    => "UserGet failed: $ret",
            "total_closed" => 0,
            "closed_positions" => [],
            "total_open" => 0,
            "open_positions" => []
        ];
        continue;
    }

    /* ---- CLOSED DEALS (robust) ---- */
    $closed_positions = [];
    $totalDeals = 0;
    $retTotal = $mt5->api->DealGetTotal($login, $from, $to, $totalDeals);
    if ($retTotal == MTRetCode::MT_RET_OK && $totalDeals > 0) {
        $deals = [];
        $retPage = $mt5->api->DealGetPage($login, $from, $to, 0, $totalDeals, $deals);
        if ($retPage == MTRetCode::MT_RET_OK && is_array($deals)) {
            foreach ($deals as $deal) {
                // Work out if this is a closing deal
                $entry  = $deal->Entry ?? null;
                $isOut  = is_deal_entry_out($entry);

                // VolumeClosed may be empty; fall back to Volume
                $rawVolClosed = isset($deal->VolumeClosed) ? (float)$deal->VolumeClosed : null;
                $rawVol       = isset($deal->Volume)       ? (float)$deal->Volume       : null;
                $usedRawVol   = ($rawVolClosed !== null && $rawVolClosed > 0) ? $rawVolClosed : $rawVol;
                $lots         = lots_from_raw($usedRawVol ?? 0);

                $hasOrder = isset($deal->Order) && (int)$deal->Order !== 0;
                $isClosed = ($isOut && $lots > 0) || ($hasOrder && $lots > 0); // fallback if Entry not set

                if (!$isClosed) continue;

                $closed_positions[] = [
                    "OpenTime"   => ts_kolkata($deal->Time ?? null),
                    "Ticket"     => $deal->Order ?? null,
                    "Action"     => (($deal->Action ?? 0) == 1 ? "Sell" : "Buy"),
                    "Volume"     => $lots,
                    "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),
                    "Commission" => r($deal->Commission ?? 0, 2),
                    "Swap"       => r($deal->Storage ?? 0, 2),
                    "Profit"     => r($deal->Profit ?? 0, 2)
                ];
            }
        }
    }

    // newest first
    if ($closed_positions) {
        usort($closed_positions, function($a, $b) {
            return strcmp($b['CloseTime'] ?? '', $a['CloseTime'] ?? '');
        });
    }

    /* ---- OPEN POSITIONS (rounded) ---- */
    $positions_data = [];
    $totalPos = 0;
    $retPos = $mt5->api->PositionGetTotal($login, $totalPos);
    if ($retPos == MTRetCode::MT_RET_OK && $totalPos > 0) {
        $positions = [];
        if ($mt5->api->PositionGetPage($login, 0, $totalPos, $positions) == MTRetCode::MT_RET_OK && is_array($positions)) {
            foreach ($positions as $pos) {
                $positions_data[] = [
                    "Symbol"       => $pos->Symbol ?? null,
                    "PriceOpen"    => r($pos->PriceOpen ?? null, PRICE_DEC),
                    "PriceCurrent" => r($pos->PriceCurrent ?? null, PRICE_DEC),
                    "PriceSL"      => r($pos->PriceSL ?? null, PRICE_DEC),
                    "PriceTP"      => r($pos->PriceTP ?? null, PRICE_DEC),
                    "Volume"       => lots_from_raw($pos->Volume ?? 0),
                    "Action"       => (($pos->Action ?? 0) == 1 ? "Sell" : "Buy"),
                    "Profit"       => r($pos->Profit ?? 0, 2),
                    "Storage"      => r($pos->Storage ?? 0, 2),
                    "TimeCreate"   => isset($pos->TimeCreate) ? ts_kolkata($pos->TimeCreate) : null
                ];
            }
        }
    }

    $all_accounts[] = [
        "trade_id"         => $loginStr,
        "total_closed"     => count($closed_positions),
        "closed_positions" => $closed_positions,
        "total_open"       => count($positions_data),
        "open_positions"   => $positions_data
    ];
}

$mt5->api->Disconnect();

echo json_encode([
    "success"        => true,
    "email"          => $email,
    "total_accounts" => count($all_accounts),
    "accounts"       => $all_accounts
]);
exit;
