<?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']) : '';
$patient_no = isset($_GET['patient_no']) ? trim($_GET['patient_no']) : '';
$payment_cat = isset($_GET['payment_cat']) ? trim($_GET['payment_cat']) : 'Cash';
$insurance_id = isset($_GET['insurance_id']) ? intval($_GET['insurance_id']) : 0;

if (empty($searchTerm)) { echo json_encode(['results' => []]); exit; }

$is_adult = true; 
if (!empty($patient_no)) {
    $ageStmt = $conn->prepare("SELECT dob FROM patient WHERE patient_no = ? LIMIT 1");
    if($ageStmt) {
        $ageStmt->bind_param("s", $patient_no);
        $ageStmt->execute();
        $ageRes = $ageStmt->get_result();
        if ($pRow = $ageRes->fetch_assoc()) {
            $dob = new DateTime($pRow['dob']);
            $now = new DateTime();
            $age = $now->diff($dob)->y;
            if ($age < 18) { $is_adult = false; }
        }
        $ageStmt->close();
    }
}

$sql = "SELECT s.id, s.service_name, s.service_type, d.department_name, 
               s.cash_price_adult, s.cash_price_child, 
               s.nhis_covered, s.is_copay_required, s.nhis_copay_adult, s.nhis_copay_child,
               sct.id AS corp_mapped, sct.is_copay_required AS corp_is_copay, 
               sct.copay_amount_adult AS corp_copay_adult, sct.copay_amount_child AS corp_copay_child
        FROM service_catalog s
        LEFT JOIN departments d ON s.department_id = d.id
        LEFT JOIN service_corporate_tariffs sct ON s.id = sct.service_id AND sct.insurance_type_id = ?
        WHERE s.is_active = 1 
        AND s.service_type IN ('Investigation', 'Procedure', 'Service')
        AND s.service_name LIKE ?
        LIMIT 40";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $likeTerm = "%" . $searchTerm . "%";
    $stmt->bind_param("is", $insurance_id, $likeTerm);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        
        $cash_rate = $is_adult ? $row['cash_price_adult'] : $row['cash_price_child'];
        $payable_amount = $cash_rate;

        if ($payment_cat === 'Corporate' && !empty($row['corp_mapped'])) {
            $payable_amount = ($row['corp_is_copay'] == 1) ? ($is_adult ? $row['corp_copay_adult'] : $row['corp_copay_child']) : 0.00;
        } 
        elseif ($payment_cat === 'NHIS' && $row['nhis_covered'] == 1) {
            $payable_amount = ($row['is_copay_required'] == 1) ? ($is_adult ? $row['nhis_copay_adult'] : $row['nhis_copay_child']) : 0.00;
        }

        $data[] = [
            'id' => $row['id'],
            'text' => $row['service_name'] . ' (' . $row['department_name'] . ')',
            'service_name' => $row['service_name'],
            'department' => $row['department_name'],
            'payable_amount' => number_format((float)$payable_amount, 2, '.', '')
        ];
    }
    echo json_encode(['results' => $data]);
    $stmt->close();
} else {
    echo json_encode(['results' => []]);
}
$conn->close();
?>