<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

include('config.php'); // Your DB connection

$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 (just show value or null)
    $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') {
        // Fetch email of this IB1 user
        $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);
?>
