<?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') {
    http_response_code(200);
    exit;
}

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

try {
    $conn->set_charset("utf8mb4");
    $conn->query("SET collation_connection = 'utf8mb4_unicode_ci'");

    $input = json_decode(file_get_contents("php://input"), true);
    if (empty($input['email'])) {
        echo json_encode(["success" => false, "error" => "Email is required"]);
        exit;
    }

    $email = $conn->real_escape_string($input['email']);

    // ✅ Step 1: Fetch user's live accounts (added masteracc)
    $liveQuery = "
        SELECT 
            id,
            trade_id,
            email,
            account_type,
            account_name,
            leverage,
            masteracc
        FROM liveaccounts
        WHERE email = '$email'
    ";
    $liveRes = $conn->query($liveQuery);

    if (!$liveRes || $liveRes->num_rows === 0) {
        echo json_encode(["success" => false, "message" => "No live accounts found"]);
        exit;
    }

    // ✅ Step 2: Account types
    $typesRes = $conn->query("SELECT ac_name FROM account_types");
    $accountTypes = [];
    while ($t = $typesRes->fetch_assoc()) {
        $accountTypes[mb_strtolower(trim($t['ac_name']), 'UTF-8')] = $t['ac_name'];
    }

    // ✅ Step 3: Copy accounts
    $copyRes = $conn->query("SELECT slavetrade, mastertrade, strategyname FROM copyaccounts");
    $copyAccounts = [];
    while ($c = $copyRes->fetch_assoc()) {
        $copyAccounts[$c['slavetrade']] = [
            'strategyname' => $c['strategyname'],
            'mastertrade' => $c['mastertrade'],
            'slavetrade' => $c['slavetrade']
        ];
    }

    // ✅ Step 4: Connect to MT5
    $mt5Conn = new MT5Connection();
    if (!$mt5Conn->connect()) {
        echo json_encode(["success" => false, "error" => "Failed to connect to MT5 server"]);
        exit;
    }
    $api = $mt5Conn->api;

    // ✅ Step 5: Merge results with MT5 live data
    $accounts = [];
    while ($row = $liveRes->fetch_assoc()) {
        $tradeId = (int)$row['trade_id'];
        $accountData = [
            "balance" => 0,
            "equity" => 0,
            "free_margin" => 0
        ];

        // 🔹 Fetch real-time MT5 account info
        $mt5Account = null;
        $ret = $api->UserAccountGet($tradeId, $mt5Account);
        if ($ret === MTRetCode::MT_RET_OK && $mt5Account) {
            $accountData = [
                "balance" => (float)$mt5Account->Balance,
                "equity" => (float)$mt5Account->Equity,
                "free_margin" => (float)$mt5Account->MarginFree
            ];
        }

        // 🔹 Fetch total number of trades and trade value
        $from = strtotime('-30 days');
        $to = time();
        $totalTrades = 0;
        $totalTradeValue = 0.0;

        $retDeals = $api->DealGetTotal($tradeId, $from, $to, $totalTrades);
        if ($retDeals === MTRetCode::MT_RET_OK && $totalTrades > 0) {
            $deals = [];
            $pageSize = 1000;
            $offset = 0;
            $retPage = $api->DealGetPage($tradeId, $from, $to, $offset, min($pageSize, $totalTrades), $deals);

            if ($retPage === MTRetCode::MT_RET_OK && !empty($deals)) {
                foreach ($deals as $deal) {
                    $totalTradeValue += isset($deal->Profit) ? (float)$deal->Profit : 0.0;
                }
            }
        }

        // 🔹 Determine type and copy info
        $normalizedType = mb_strtolower(trim($row['account_type']), 'UTF-8');
        $typeName = $accountTypes[$normalizedType] ?? $row['account_type'];
        $copy = $copyAccounts[$row['trade_id']] ?? null;

        $accounts[] = [
            "account_id" => $row['id'],
            "trade_id" => $tradeId,
            "email" => $row['email'],
            "account_type" => $typeName,
            "account_name" => $row['account_name'],
            "copy_strategy_name" => $copy['strategyname'] ?? null,
            "master_trade" => $copy['mastertrade'] ?? null,
            "slave_trade" => $copy['slavetrade'] ?? null,
            "balance" => $accountData['balance'],
            "equity" => $accountData['equity'],
            "free_margin" => $accountData['free_margin'],
            "leverage" => (int)$row['leverage'],
            // ✅ Added Master Account Flag
            "is_master_account" => ($row['masteracc'] == 2) ? true : false,
            "total_trades" => $totalTrades,
            "total_trade_value" => round($totalTradeValue, 2)
        ];
    }

    echo json_encode([
        "success" => true,
        "data" => $accounts
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "error" => $e->getMessage()
    ]);
}
?>
