<?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') exit;

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);
$emailInput = trim($input['email'] ?? "");
$level = intval($input['level'] ?? 1);

if (empty($emailInput)) {
    echo json_encode(["success" => false, "message" => "IB Email is required"]);
    exit;
}

if ($level < 1 || $level > 20) {
    echo json_encode(["success" => false, "message" => "Level must be between 1–20"]);
    exit;
}

$ibColumn = "ib$level";

// Fetch all clients under IB tier
$stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE $ibColumn = ?");
$stmt->bind_param("s", $emailInput);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows == 0) {
    echo json_encode(["success" => false, "message" => "No clients found under this level"]);
    exit;
}

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

$data = [];

while ($acc = $res->fetch_assoc()) {

    $trade_id = intval($acc['trade_id']);
    $email = $acc['email'];

    // Get User name
    $name = '';
    $stmt_user = $conn->prepare("SELECT first_name, last_name FROM loginusers WHERE email=?");
    $stmt_user->bind_param("s", $email);
    $stmt_user->execute();
    $r_user = $stmt_user->get_result();
    if ($ru = $r_user->fetch_assoc()) {
        $name = trim(($ru['first_name'] ?? "") . " " . ($ru['last_name'] ?? ""));
    }
    $stmt_user->close();

    // Closed Trades
    $closed_positions = [];
    $total = 0;

    $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 (($deal->VolumeClosed ?? 0) > 0) {
                    $closed_positions[] = [
                        "Ticket" => $deal->Order,
                        "Volume" => round(($deal->VolumeClosed * 0.0001), 2),
                        "Symbol" => $deal->Symbol,
                        "Action" => ($deal->Action == 1 ? "Sell" : "Buy"),
                        "OpenPrice" => $deal->PricePosition,
                        "ClosePrice" => $deal->Price,
                        "Profit" => $deal->Profit,
                        "Commission" => $deal->Commission,
                        "Swap" => $deal->Storage,
                        // "OpenTime" => date("Y-m-d H:i:s", $deal->Time),
                        "CloseTime" => date("Y-m-d H:i:s", $deal->Time),
                    ];
                }
            }
        }
    }

    // Open positions
    $open_positions = [];
    $pos_total = 0;
    $ret_pos = $mt5->api->PositionGetTotal($trade_id, $pos_total);

    if ($ret_pos == MTRetCode::MT_RET_OK && $pos_total > 0) {
        $positions = [];
        $ret_page2 = $mt5->api->PositionGetPage($trade_id, 0, $pos_total, $positions);

        if ($ret_page2 == MTRetCode::MT_RET_OK) {
            foreach ($positions as $pos) {
                $open_positions[] = [
                    "Symbol" => $pos->Symbol,
                    "Volume" => round(($pos->Volume * 0.0001), 2),
                    "Action" => ($pos->Action == 1 ? "Sell" : "Buy"),
                    "PriceOpen" => $pos->PriceOpen,
                    "PriceCurrent" => $pos->PriceCurrent,
                    "Profit" => $pos->Profit
                ];
            }
        }
    }

    $data[] = [
        "trade_id" => $trade_id,
        "email" => $email,
        "name" => $name,
        "closed_trades" => count($closed_positions),
        "open_trades" => count($open_positions),
        "closed_positions" => $closed_positions,
        "open_positions" => $open_positions
    ];
}

$mt5->api->Disconnect();

$response = [
    "success" => true,
    "ib_email" => $emailInput,
    "level" => $level,
    "total_clients" => count($data),
    "data" => $data
];

echo json_encode($response, JSON_PRETTY_PRINT);
exit;
?>
