<?php
$tenant = preg_replace('/[^A-Za-z0-9._-]/', '', (string)($_REQUEST['tenant'] ?? ''));
$configPath = '../../../' . $tenant . '/config.php';

if ($tenant !== '' && file_exists($configPath)) {
    require_once($configPath);
}

header('Content-Type: application/json');

if (empty($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['clients' => []]);
    exit;
}

function dashboardClientSearchIntList($values)
{
    $values = array_values(array_unique(array_filter(array_map('intval', (array)$values))));
    return implode(',', $values);
}

$query = trim((string)($_GET['q'] ?? ''));
$limit = max(1, min(50, (int)($_GET['limit'] ?? 30)));
$offset = max(0, (int)($_GET['offset'] ?? 0));

if ($query !== '' && strlen($query) < 2) {
    echo json_encode(['clients' => []]);
    exit;
}

$sessionAccess = (int)($_SESSION['access'] ?? 0);
$sessionUserId = (int)($_SESSION['userid'] ?? 0);
$contractorNumber = trim((string)($_SESSION['contractorNumber'] ?? ''));
$where = ["cd.`statuslive` = '1'"];
$types = '';
$params = [];

if ($query !== '') {
    $where[] = "cd.`clientname` LIKE ?";
    $like = '%' . $query . '%';
    $types .= 's';
    $params[] = $like;
}

if ($contractorNumber !== '') {
    $where[] = "cd.`contractor` = ?";
    $types .= 's';
    $params[] = $contractorNumber;
} elseif (($_SESSION['usertype'] ?? '') === 'surveyor' && $sessionAccess === 3 && $sessionUserId > 0) {
    $where[] = "cd.`clientnumber` IN (
        SELECT DISTINCT sa.`client_id`
        FROM `surveyor_assignments` sa
        WHERE sa.`surveyor` = ?
    )";
    $types .= 'i';
    $params[] = $sessionUserId;
} elseif ($sessionAccess === 1 && $sessionUserId > 0) {
    $stmt = $GLOBALS['con']->prepare("SELECT clientnumbers FROM admin_access WHERE admin_id = ?");
    if ($stmt) {
        $stmt->bind_param('i', $sessionUserId);
        $stmt->execute();
        $accessResult = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($accessResult) {
            $clientAccessArray = json_decode($accessResult['clientnumbers'] ?? '[]', true);
            $clientAccessSqlList = dashboardClientSearchIntList(is_array($clientAccessArray) ? $clientAccessArray : []);
            $where[] = $clientAccessSqlList !== '' ? "cd.`clientnumber` IN ($clientAccessSqlList)" : "1 = 0";
        }
    }
}

$sql = "
    SELECT cd.`clientnumber`, cd.`clientname`
    FROM `clientdetails` cd
    WHERE " . implode(' AND ', $where) . "
    ORDER BY
        CASE
            WHEN cd.`clientname` LIKE ? THEN 0
            ELSE 1
        END,
        cd.`clientname` ASC
    LIMIT ? OFFSET ?
";

$types .= 's';
$params[] = $query . '%';
$types .= 'ii';
$params[] = $limit + 1;
$params[] = $offset;

$stmt = $GLOBALS['con']->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['clients' => []]);
    exit;
}

$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
$clients = [];

while ($row = $result->fetch_assoc()) {
    $clients[] = [
        'clientnumber' => (int)$row['clientnumber'],
        'clientname' => $row['clientname']
    ];
}

$hasMore = count($clients) > $limit;
if ($hasMore) {
    array_pop($clients);
}

echo json_encode([
    'clients' => $clients,
    'hasMore' => $hasMore,
    'nextOffset' => $offset + count($clients)
]);

$stmt->close();
$GLOBALS['con']->close();
