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

// Include DB connection and MT5 API
include_once __DIR__ . "/config.php";      // DB connection ($conn)
include_once __DIR__ . "/connection.php";  // MT5 API constants and MT5Connection class

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);
$trade_id = $input['trade_id'] ?? null;

if (!$trade_id) {
    echo json_encode([
        "success" => false,
        "message" => "Trade ID is required",
        "trade" => null
    ]);
    exit;
}

// Check if the trade ID exists in liveaccounts table
$stmt = $conn->prepare("SELECT email FROM liveaccounts WHERE trade_id = ?");
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) {
    echo json_encode([
        "success" => false,
        "message" => "No MT5 account found for this trade ID",
        "trade" => null
    ]);
    exit;
}

$email = $row['email'];

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

// Fetch MT5 user details
$userMT5 = new MTUser();
$ret = $mt5->api->UserGet((int)$trade_id, $userMT5);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode([
        "success" => false,
        "message" => "Failed to fetch MT5 user details",
        "trade" => null
    ]);
    exit;
}

// --- Fetch all closed positions ---
$total = 0;
$closed_positions = [];

// Get total deals (all time)
$ret_total = $mt5->api->DealGetTotal($trade_id, 0, 0, $total);
if ($ret_total == MTRetCode::MT_RET_OK && $total > 0) {
    $deals = [];
    $ret_page = $mt5->api->DealGetPage($trade_id, 0, 0, 0, $total, $deals);
    if ($ret_page == MTRetCode::MT_RET_OK) {
        foreach ($deals as $deal) {
            if (isset($deal->VolumeClosed) && $deal->VolumeClosed > 0) {
                $openTime = isset($deal->Time) ? (new DateTime("@" . $deal->Time))
                    ->setTimezone(new DateTimeZone("Asia/Kolkata"))
                    ->format("Y-m-d H:i:s") : null;

                $closeTime = isset($deal->TimeMsc) ? (new DateTime("@" . floor($deal->TimeMsc / 1000)))
                    ->setTimezone(new DateTimeZone("Asia/Kolkata"))
                    ->format("Y-m-d H:i:s") : null;

                $closed_positions[] = [
                    "OpenTime"   => $openTime,
                    "Ticket"     => $deal->Order ?? null,
                    "Action"     => ($deal->Action ?? 0) == 1 ? "Sell" : "Buy",
                    "Volume"     => round(($deal->VolumeClosed ?? 0) * 0.0001, 2),
                    "Symbol"     => $deal->Symbol ?? null,
                    "OpenPrice"  => $deal->PricePosition ?? null,
                    "ClosePrice" => $deal->Price ?? null,
                    "CloseTime"  => $closeTime,
                    "Commission" => $deal->Commission ?? 0,
                    "Swap"       => $deal->Storage ?? 0,
                    "Profit"     => $deal->Profit ?? 0
                ];
            }
        }
    }
}

// --- Fetch open positions ---
$positions_data = [];
$total_positions = 0;
$ret_pos = $mt5->api->PositionGetTotal($trade_id, $total_positions);
if ($ret_pos == MTRetCode::MT_RET_OK && $total_positions > 0) {
    $positions = [];
    $ret_page = $mt5->api->PositionGetPage($trade_id, 0, $total_positions, $positions);
    if ($ret_page == MTRetCode::MT_RET_OK) {
        foreach ($positions as $pos) {
            $positions_data[] = [
                "Symbol"       => $pos->Symbol ?? null,
                "PriceOpen"    => $pos->PriceOpen ?? null,
                "PriceCurrent" => $pos->PriceCurrent ?? null,
                "PriceSL"      => $pos->PriceSL ?? null,
                "PriceTP"      => $pos->PriceTP ?? null,
                "Volume"       => isset($pos->Volume) ? round($pos->Volume * 0.0001, 2) : null,
                "Action"       => (isset($pos->Action) && $pos->Action == 1) ? "Sell" : "Buy",
                "Profit"       => $pos->Profit ?? null,
                "Storage"      => $pos->Storage ?? null,
                "TimeCreate"   => isset($pos->TimeCreate) ? gmdate("Y-m-d H:i:s", $pos->TimeCreate) : null
            ];
        }
    }
}

$mt5->api->Disconnect();

// Return JSON response
echo json_encode([
    "success" => true,
    "email" => $email,
    "trade_id" => $trade_id,
    "total_closed" => count($closed_positions),
    "closed_positions" => $closed_positions,
    "total_open" => count($positions_data),
    "open_positions" => $positions_data
]);
exit;
?>
