<?php
// C:\xampp\htdocs\rimax\application\dripend\systemSetup\patient\searchPatient.php

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

// Grab the search term typed by the user in Select2
$searchTerm = isset($_GET['q']) ? $_GET['q'] : '';

// Base query: Only active patients
$sql = "SELECT patient_no, first_name, last_name, mobile 
        FROM patient 
        WHERE is_active = 1 ";

// If a search term exists, search across Name, ID, or Phone Number
if (!empty($searchTerm)) {
    $sql .= " AND (patient_no LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR mobile LIKE ?) ";
}

$sql .= " ORDER BY first_name ASC LIMIT 50";

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

if (!empty($searchTerm)) {
    $likeTerm = '%' . $searchTerm . '%';
    // Bind the term 4 times because we have 4 question marks in the query
    $stmt->bind_param("ssss", $likeTerm, $likeTerm, $likeTerm, $likeTerm);
}

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

$data = [];
while ($row = $result->fetch_assoc()) {
    // Format the display text beautifully: "John Doe (DDC-K2026-...) - 0244444444"
    $displayText = $row['first_name'] . ' ' . $row['last_name'] . ' (' . $row['patient_no'] . ')';
    if (!empty($row['mobile'])) {
        $displayText .= ' - ' . $row['mobile'];
    }
    
    // Select2 REQUIRES an array of objects with 'id' and 'text' keys
    $data[] = [
        'id' => $row['patient_no'], // We pass the patient_no back to the JS as the ID
        'text' => $displayText
    ];
}

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

// Return the JSON payload back to the frontend
header('Content-Type: application/json');
echo json_encode($data);
?>