<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../functions/security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_admin();

$adminId = enrep_request_int('admin_id');
if ($adminId < 1) {
    enrep_fail(400, 'Invalid admin');
}

$clientResult = $GLOBALS['con']->query("SELECT `clientnumber`, `clientname`, `statuslive` FROM `clientdetails` WHERE `statuslive`=1 ORDER BY `clientname` ASC");
if (!$clientResult) {
    enrep_fail(500, 'Unable to load client access');
}

$clientAccess = [];
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumbers` FROM `admin_access` WHERE `admin_id`=? LIMIT 1");
if ($stmt) {
    $stmt->bind_param('i', $adminId);
    $stmt->execute();
    $accessResult = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $decoded = json_decode((string)($accessResult['clientnumbers'] ?? '[]'), true);
    if (is_array($decoded)) {
        $clientAccess = array_map('intval', $decoded);
    }
}

$clients = [];
while ($row = mysqli_fetch_assoc($clientResult)) {
    $clientnumber = (int)($row['clientnumber'] ?? 0);
    $clients[] = [
        'clientnumber' => $clientnumber,
        'clientname' => (string)($row['clientname'] ?? ''),
        'statuslive' => (int)($row['statuslive'] ?? 0),
        'access' => in_array($clientnumber, $clientAccess, true)
    ];
}

echo json_encode(['clients' => $clients], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
