<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include '../includes/db.php';

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$q = $conn->real_escape_string($q);

if ($q != '') {
    $sql = "SELECT id, test_name, description
            FROM services
            WHERE is_visible = 1
              AND LOWER(test_name) LIKE LOWER(CONCAT('%', ?, '%'))
            ORDER BY test_name ASC
            LIMIT 10";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $q);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo '<ul style="list-style:none; margin:0; padding:0;">';
        while ($row = $result->fetch_assoc()) {
            $name = htmlspecialchars($row['test_name'], ENT_QUOTES);
            $desc = $row['description'];
            // Highlight matched part
            $highlightedName = preg_replace("/(" . preg_quote($q, '/') . ")/i", "<mark>$1</mark>", $name);

            echo '<li style="padding:8px; border-bottom:1px solid #eee; cursor:pointer;" ';
            echo "onclick=\"window.location.href='service-details.php?id={$row['id']}'\">";
            echo "<strong>{$highlightedName}</strong><br><small>{$desc}</small>";
            echo '</li>';
        }
        echo '</ul>';
    } else {
        echo '<div style="padding:8px;">No services found</div>';
    }

    $stmt->close();
}

$conn->close();
?>
