<?php
// admin_getliveaccounts.php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Only GET method allowed"]);
    exit;
}

// Include DB config
require_once(__DIR__ . "/../config.php");

// Query to fetch all users and their live accounts
$sql = "
    SELECT 
        lu.id AS user_id,
        lu.first_name,
        lu.last_name,
        lu.email AS user_email,
        lu.country,
        lu.phone,
        lu.status AS user_status,
        lu.kyc_status,
        lu.client_status,
        lu.created_at AS user_created_at,
        la.id AS liveaccount_id,
        la.trade_id,
        la.server,
        la.account_type,
        la.account_name,
        la.leverage,
        la.volume,
        la.currency,
        la.Balance,
        la.equity,
        la.MarginFree,
        la.MarginLevel,
        la.deposit,
        la.withdraw,
        la.totalprofit,
        la.status AS live_status,
        la.Registered_Date,
        la.ib1,
        la.ib2,
        la.level,
        la.masteracc
    FROM 
        liveaccounts la
    INNER JOIN 
        loginusers lu 
    ON 
        la.user_id = lu.id
    ORDER BY 
        lu.id ASC, la.id ASC
";

$result = $conn->query($sql);

if (!$result) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database query failed", "error" => $conn->error]);
    exit;
}

$users = [];
while ($row = $result->fetch_assoc()) {
    $uid = $row['user_id'];

    // Create user entry if not already present
    if (!isset($users[$uid])) {
        $users[$uid] = [
            "user_id" => $row['user_id'],
            "first_name" => $row['first_name'],
            "last_name" => $row['last_name'],
            "email" => $row['user_email'],
            "country" => $row['country'],
            "phone" => $row['phone'],
            "user_status" => $row['user_status'],
            "kyc_status" => $row['kyc_status'],
            "client_status" => $row['client_status'],
            "created_at" => $row['user_created_at'],
            "live_accounts" => []
        ];
    }

    // Add live account under this user
    $users[$uid]['live_accounts'][] = [
        "liveaccount_id" => $row['liveaccount_id'],
        "trade_id" => $row['trade_id'],
        "server" => $row['server'],
        "account_type" => $row['account_type'],
        "account_name" => $row['account_name'],
        "leverage" => $row['leverage'],
        "volume" => $row['volume'],
        "currency" => $row['currency'],
        "balance" => $row['Balance'],
        "equity" => $row['equity'],
        "margin_free" => $row['MarginFree'],
        "margin_level" => $row['MarginLevel'],
        "deposit" => $row['deposit'],
        "withdraw" => $row['withdraw'],
        "total_profit" => $row['totalprofit'],
        "status" => $row['live_status'],
        "registered_date" => $row['Registered_Date'],
        "ib1" => $row['ib1'],
        "ib2" => $row['ib2'],
        "level" => $row['level'],
        "masteracc" => $row['masteracc']
    ];
}

// Format final output
if (!empty($users)) {
    echo json_encode([
        "status" => "success",
        "total_users" => count($users),
        "data" => array_values($users)
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode(["status" => "error", "message" => "No live accounts found"]);
}

$conn->close();
?>
