<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}

$admin_id = $_GET['admin_id'];

// Fetch all clients where statuslive = 1 or 0
$clientQuery = "SELECT clientnumber, clientname FROM clientdetails WHERE statuslive=1";
$clientResult = mysqli_query($con, $clientQuery);

// Fetch current access for the admin
$accessQuery = "SELECT clientnumbers FROM admin_access WHERE admin_id = ?";
$stmt = $con->prepare($accessQuery);
$stmt->bind_param('i', $admin_id);
$stmt->execute();
$accessResult = $stmt->get_result()->fetch_assoc();
$clientAccess = json_decode($accessResult['clientnumbers'], true) ?? [];

// Create response array
$clients = [];
while ($row = mysqli_fetch_assoc($clientResult)) {
    $clients[] = [
        'clientnumber' => $row['clientnumber'],
        'clientname' => $row['clientname'],
        'statuslive' => $row['statuslive'],
        'access' => in_array($row['clientnumber'], $clientAccess)
    ];
}

// Return as JSON
echo json_encode(['clients' => $clients]);
?>