<?php
// ------------------------------------------
// admin_fetch_masters_list.php
// ------------------------------------------

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

// ✅ Include DB config (use correct relative path)
include __DIR__ . "/../config.php";

$response = [
    "success" => false,
    "message" => "",
    "masters" => []
];

try {
    // ✅ Test DB connection
    if (!isset($conn) || !$conn instanceof mysqli || $conn->connect_error) {
        throw new Exception("Database connection failed: " . $conn->connect_error);
    }

    // ✅ Query for master accounts
    $sql = "SELECT id, user_id, trade_id, email, leverage 
            FROM liveaccounts 
            WHERE masteracc = 2";

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

    if ($result && $result->num_rows > 0) {
        $masters = [];
        while ($row = $result->fetch_assoc()) {
            $masters[] = [
                "id" => $row["id"],
                "user_id" => $row["user_id"],
                "trade_id" => $row["trade_id"],
                "email" => $row["email"],
                "leverage" => $row["leverage"]
            ];
        }

        $response["success"] = true;
        $response["message"] = "Master accounts fetched successfully.";
        $response["masters"] = $masters;
    } else {
        $response["message"] = "No master accounts found.";
    }

} catch (Throwable $e) {
    $response["message"] = "Internal Server Error: " . $e->getMessage();
}

echo json_encode($response);
?>
