<?php
// Set headers for JSON response
header('Content-Type: application/json');

// CORS headers
$origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
header("Access-Control-Allow-Origin: $origin");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Credentials: true");

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

include_once __DIR__ . "/../config.php";

$response = [
    'success' => true,
    'total_clients' => 0,
    'data' => []
];

// Fetch all users
$userQuery = $conn->query("SELECT id, first_name, last_name, email, 
    ib1, ib2, ib3, ib4, ib5, ib6, ib7, ib8, ib9, ib10,
    ib11, ib12, ib13, ib14, ib15, ib16, ib17, ib18, ib19, ib20
    FROM loginusers");

while ($user = $userQuery->fetch_assoc()) {
    $userId = $user['id'];
    $clientName = trim($user['first_name'] . ' ' . $user['last_name']);
    $clientEmail = $user['email'];

    // Fetch trade IDs for this user
    $tradeQuery = $conn->query("SELECT trade_id FROM liveaccounts WHERE user_id = $userId");
    $tradeIds = [];
    while ($trade = $tradeQuery->fetch_assoc()) {
        $tradeIds[] = $trade['trade_id'];
    }

    // Build IB hierarchy
    $ibs = [];
    for ($i = 1; $i <= 20; $i++) {
        $ibCol = 'ib' . $i;
        $ibs[$ibCol] = ($user[$ibCol] && $user[$ibCol] != 'noIB' && $user[$ibCol] != 'noIBu') ? $user[$ibCol] : null;
    }

    // Set parent as IB1 info
    $parentInfo = null;
    if (!empty($user['ib1']) && $user['ib1'] != 'noIB' && $user['ib1'] != 'noIBu') {
        $ib1Value = $conn->real_escape_string($user['ib1']);
        $ibQuery = $conn->query("SELECT email FROM loginusers WHERE uid = '$ib1Value' LIMIT 1");
        $ibEmail = null;
        if ($ib = $ibQuery->fetch_assoc()) {
            $ibEmail = $ib['email'];
        }

        $parentInfo = [
            'email' => $user['ib1'],
        ];
    }

    $response['data'][] = [
        'client_name' => $clientName,
        'client_email' => $clientEmail,
        'trade_ids' => $tradeIds,
        'parent' => $parentInfo,
        'ibs' => $ibs
    ];
}

$response['total_clients'] = count($response['data']);

echo json_encode($response, JSON_PRETTY_PRINT);
?>
