<?php
// fetch_liveaccounts.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 OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Get user_id from query string
$userId = $_GET['user_id'] ?? 0;

if (empty($userId)) {
    echo json_encode(['success' => false, 'error' => 'Missing user_id']);
    exit;
}

// Include DB config
require_once __DIR__ . '/config.php';

try {
    $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false
    ]);

    // Fetch live accounts for this user
    $stmt = $dbh->prepare("SELECT * FROM liveaccounts WHERE user_id = :user_id ORDER BY Registered_Date DESC");
    $stmt->execute([':user_id' => $userId]);
    $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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