<?php
// api/coraza-rules-host-search.php — autocompletes hostnames against the WHP
// sites table for the host-exception modal.

require_once('/docker/whp/web/libs/permission_checker.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');

header('Content-Type: application/json');
if (!is_root_user()) { http_response_code(403); echo '[]'; return; }

$q = strtolower(trim((string)($_GET['q'] ?? '')));
if ($q === '' || strlen($q) < 2) { echo '[]'; return; }

$mysql = new mysqlmgmt();
$db = $mysql->getMySQLConnection();
if (!$db) { echo '[]'; return; }
$db->exec("USE whp");
$stmt = $db->prepare("SELECT DISTINCT domain FROM sites WHERE domain LIKE :q ORDER BY domain LIMIT 20");
$stmt->bindValue(':q', "%$q%", PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode(array_map('strval', $rows));
