<?php
header("Content-Type: application/json");
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;

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

$input = file_get_contents("php://input");
$data  = json_decode($input, true);

$email = $data['email'] ?? null;

if (!$email) {
    echo json_encode(["status" => "error", "message" => "Missing email"]);
    exit;
}

// Fetch all liveaccounts for this user that are eligible to subscribe (EXCLUDE DEMO)
$stmt = $conn->prepare("
    SELECT id, trade_id, account_name, account_type
    FROM liveaccounts 
    WHERE email=? 
      AND masteracc != 1
      AND account_type != 'Demo'
      AND account_type != 6
");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();


$accounts = [];

// Connect to MT5
$api = new MTWebAPI("WebAPITesterLocal", "./logs", true);
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["status" => "error", "message" => "MT5 connection failed"]);
    exit;
}

while ($row = $result->fetch_assoc()) {
    $user = new MTUser();
    $balance = 0;

    if ($api->UserGet(intval($row['trade_id']), $user) == MTRetCode::MT_RET_OK) {
        $balance = $user->Balance;
    }

    $accounts[] = [
        "trade_id"     => $row['trade_id'],
        "account_name" => $row['account_name'],
        "Balance"      => $balance
    ];

    // Optionally, update DB deposit to match MT5
    $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=? WHERE id=?");
    $stmtUpdate->bind_param("di", $balance, $row['id']);
    $stmtUpdate->execute();
    $stmtUpdate->close();
}

$api->Disconnect();
$stmt->close();

echo json_encode([
    "status" => "success",
    "accounts" => $accounts
]);
exit;
?>
