<?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,
    'clients' => []
];

// Fetch all clients
$userQuery = $conn->query("SELECT * FROM loginusers ORDER BY id DESC");

while ($user = $userQuery->fetch_assoc()) {
    $userId = $user['id'];
    $clientName = trim($user['first_name'] . ' ' . $user['last_name']);
    $clientEmail = $user['email'];
    $country = $user['country'];
    $phone = $user['phone'];
    $regDate = $user['reg_date'];
    $status = ($user['status'] == 1) ? "Active" : "Inactive";

    // 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'];
    }

    // Get parent email from IB1
    $parentEmail = null;
    if (!empty($user['ib1']) && $user['ib1'] != 'noIB' && $user['ib1'] != 'noIBu') {
        $ib1Value = $conn->real_escape_string($user['ib1']);
        // Match both uid and email to ensure correct parent
        $ibQuery = $conn->query("SELECT email FROM loginusers WHERE uid='$ib1Value' OR email='$ib1Value' LIMIT 1");
        if ($ib = $ibQuery->fetch_assoc()) {
            $parentEmail = $ib['email'];
        }
    }

    $response['clients'][] = [
        'client_name' => $clientName,
        'client_email' => $clientEmail,
        'country' => $country,
        'phone' => $phone,
        'reg_date' => $regDate,
        'status' => $status,
        'parent_email' => $parentEmail,
        'trade_ids' => $tradeIds
    ];
}

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

echo json_encode($response, JSON_PRETTY_PRINT);
?>
