<?php
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/rimax/application/dripend/includes/db.php';
header('Content-Type: application/json');

$searchTerm = isset($_GET['q']) ? trim($_GET['q']) : '';
if (empty($searchTerm)) { echo json_encode(['results' => []]); exit; }

$sql = "SELECT patient_no, first_name, last_name, mobile, ghana_card_no, nhis_no, other_insurance_id, other_insurance_no 
        FROM patient 
        WHERE is_active = 1 
        AND (first_name LIKE ? OR last_name LIKE ? OR mobile LIKE ? OR patient_no LIKE ?) 
        LIMIT 20";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $likeTerm = "%" . $searchTerm . "%";
    $stmt->bind_param("ssss", $likeTerm, $likeTerm, $likeTerm, $likeTerm);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $default_payer = 'Cash';
        if (!empty($row['other_insurance_id'])) { $default_payer = 'Corporate'; }
        elseif (!empty($row['nhis_no'])) { $default_payer = 'NHIS'; }

        $data[] = [
            'id' => $row['patient_no'],
            'text' => $row['first_name'] . ' ' . $row['last_name'] . ' - ' . $row['mobile'] . ' (' . $row['patient_no'] . ')',
            'default_payer' => $default_payer,
            'nhis_no' => $row['nhis_no'],
            'insurance_id' => $row['other_insurance_id'],
            'insurance_no' => $row['other_insurance_no']
        ];
    }
    echo json_encode(['results' => $data]);
    $stmt->close();
} else {
    echo json_encode(['results' => []]);
}
$conn->close();
?>