<?php
// admin_getliveaccounts.php

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("config.php");

// Get email from query string
if (!isset($_GET['email']) || empty(trim($_GET['email']))) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "email is required"]);
    exit;
}

$email = trim($_GET['email']);

// Query: fetch liveaccounts by email
$sql = "SELECT la.* 
        FROM liveaccounts la
        INNER JOIN loginusers lu ON la.user_id = lu.id
        WHERE lu.email = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

$accounts = [];
while ($row = $result->fetch_assoc()) {
    $accounts[] = $row;
}

if (count($accounts) > 0) {
    echo json_encode(["status" => "success", "data" => $accounts], JSON_PRETTY_PRINT);
} else {
    echo json_encode(["status" => "error", "message" => "No live accounts found for this email"]);
}

$stmt->close();
$conn->close();
?>
