<?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']) || empty($input['trade_id'])) {
        echo json_encode(["success" => false, "error" => "Email and trade_id are required"]);
        exit;
    }

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

    // ✅ Step 1: Fetch user's live account
    $liveQuery = $conn->prepare("
        SELECT id, trade_id, email, account_type, account_name, leverage, currency, Balance, equity
        FROM liveaccounts
        WHERE email = ? AND trade_id = ?
        LIMIT 1
    ");
    $liveQuery->bind_param("ss", $email, $trade_id);
    $liveQuery->execute();
    $liveRes = $liveQuery->get_result();

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

    $liveAccount = $liveRes->fetch_assoc();

    // ✅ Step 2: Get 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: Fetch copy info
    $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: Fetch user profile
    $userQuery = $conn->prepare("
        SELECT first_name, last_name, phone, country, address, city, state, profile_image
        FROM loginusers
        WHERE email = ?
        LIMIT 1
    ");
    $userQuery->bind_param("s", $email);
    $userQuery->execute();
    $userRes = $userQuery->get_result();
    $userData = $userRes->fetch_assoc() ?: [];

    // ✅ Step 5: 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;

    $tradeId = (int)$liveAccount['trade_id'];
    $accountData = [
        "balance" => 0,
        "equity" => 0,
        "free_margin" => 0,
        "credit" => 0,
    ];

    $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,
            "credit" => (float)$mt5Account->Credit,
        ];
    }

    // ✅ Step 6: Fetch trades (30 days)
    $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) {
        $pageSize = 1000;
        $offset = 0;
        $deals = [];

        $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;
            }
        }
    }

    // ✅ Step 7: Fetch IB-related info (Determine correct level dynamically)
$referralQuery = $conn->prepare("
    SELECT id, trade_id, email, Balance, deposit,
           ib1, ib2, ib3, ib4, ib5, ib6, ib7, ib8, ib9, ib10
    FROM liveaccounts
    WHERE ib1 = ? OR ib2 = ? OR ib3 = ? OR ib4 = ? OR ib5 = ?
       OR ib6 = ? OR ib7 = ? OR ib8 = ? OR ib9 = ? OR ib10 = ?
");
$referralQuery->bind_param(
    "ssssssssss",
    $email, $email, $email, $email, $email,
    $email, $email, $email, $email, $email
);
$referralQuery->execute();
$refRes = $referralQuery->get_result();

$referrals = [];
$totalDeposits = 0.0;

while ($r = $refRes->fetch_assoc()) {
    // Determine correct level based on which IB column matches
    $level = 0;
    for ($i = 1; $i <= 10; $i++) {
        if ($r["ib$i"] === $email) {
            $level = $i;
            break;
        }
    }

    $referrals[] = [
        "client_id" => $r['id'],
        "trade_id" => $r['trade_id'],
        "email" => $r['email'],
        "balance" => (float)$r['Balance'],
        "deposit" => (float)$r['deposit'],
        "level" => $level
    ];

    $totalDeposits += (float)$r['deposit'];
}


    // ✅ Step 8: Fetch IB commission list (levels)
    $ibRes = $conn->query("SELECT trade_id, ib1, ib2, ib3, ib4, ib5, ib6, ib7, ib8, ib9, ib10, level FROM liveaccounts WHERE trade_id = '$trade_id' LIMIT 1");
    $ibData = $ibRes->fetch_assoc();
    $ibList = [];

    if ($ibData) {
        for ($i = 1; $i <= 10; $i++) {
            if (!empty($ibData["ib$i"]) && $ibData["ib$i"] !== 'noIB') {
                $ibList[] = [
                    "level" => $i,
                    "ib_trade_id" => $ibData["ib$i"]
                ];
            }
        }
    }

    // ✅ Step 9: Combine all data
    $finalData = [
        "account_id" => $liveAccount['id'],
        "trade_id" => $tradeId,
        "email" => $liveAccount['email'],
        "account_type" => $accountTypes[strtolower($liveAccount['account_type'])] ?? $liveAccount['account_type'],
        "account_name" => $liveAccount['account_name'],
        "copy_strategy_name" => $copyAccounts[$liveAccount['trade_id']]['strategyname'] ?? null,
        "master_trade" => $copyAccounts[$liveAccount['trade_id']]['mastertrade'] ?? null,
        "slave_trade" => $copyAccounts[$liveAccount['trade_id']]['slavetrade'] ?? null,
        "balance" => $accountData['balance'],
        "my_account_balance" => $accountData['balance'],
        "equity" => $accountData['equity'],
        "credit" => $accountData['credit'],
        "free_margin" => $accountData['free_margin'],
        "currency" => $liveAccount['currency'],
        "leverage" => (int)$liveAccount['leverage'],
        "total_trades" => $totalTrades,
        "total_trade_value" => round($totalTradeValue, 2),
        "referral_accounts" => count($referrals),
        "total_deposits" => round($totalDeposits, 2),
        "clients_list" => $referrals,
        // "ib_commission_list" => $ibList,
        "user_profile" => [
            "first_name" => $userData['first_name'] ?? null,
            "last_name" => $userData['last_name'] ?? null,
            "phone" => $userData['phone'] ?? null,
            "country" => $userData['country'] ?? null,
            "address" => $userData['address'] ?? null,
            "city" => $userData['city'] ?? null,
            "state" => $userData['state'] ?? null,
            "profile_image" => $userData['profile_image'] ?? null
        ]
    ];

    echo json_encode([
        "success" => true,
        "data" => $finalData
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

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