<?php
// C:\xampp\htdocs\rimax\application\dripend\systemSetup\service_catalog\searchCatalog.php

require_once dirname(__DIR__, 2) . '/includes/db.php';

// Check if a search term was provided
$searchTerm = isset($_GET['q']) ? $_GET['q'] : '';

// We only want active services. We are also excluding 'Consultation' 
// because consultations are usually billed at the Front Desk, not requested by the doctor during the visit.
$sql = "SELECT id, service_name, service_type, cash_price_adult 
        FROM service_catalog 
        WHERE is_active = 1 
        AND service_type != 'Consultation' ";

// If the user typed something, add the search filter
if (!empty($searchTerm)) {
    $sql .= " AND service_name LIKE ? ";
}

// Limit the results to 50 so the dropdown doesn't lag
$sql .= " ORDER BY service_name ASC LIMIT 50";

$stmt = $conn->prepare($sql);

if (!empty($searchTerm)) {
    // Add wildcards for partial matching (e.g., typing "blood" matches "Full Blood Count")
    $likeTerm = '%' . $searchTerm . '%';
    $stmt->bind_param("s", $likeTerm);
}

$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Format the text to show the service name, its type, and its price for the doctor's reference
    $displayText = $row['service_name'] . ' [' . $row['service_type'] . '] - GHS ' . number_format($row['cash_price_adult'], 2);
    
    $data[] = [
        'id' => $row['id'],
        'text' => $displayText
    ];
}

$stmt->close();
$conn->close();

// Return the JSON response for Select2
header('Content-Type: application/json');
echo json_encode($data);
?>