<?php
/**
 * AJAX search for procedures in consultation - PRODIGY NOTES Item #14
 * Returns procedures from service_pricing filtered by patient registration_type.
 * Cash (WALK_IN, PRO_BONO) → base_price; Insurance → insurance_price or base_price.
 */
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['results' => []]);
    exit();
}

$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$patient_reg_type = isset($_GET['reg_type']) ? strtoupper(trim($_GET['reg_type'])) : 'WALK_IN';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = 30;
$offset = ($page - 1) * $per_page;

// Determine price column: INSURANCE uses insurance_price, else base_price
$is_insurance = ($patient_reg_type === 'INSURANCE');
$price_sql = $is_insurance
    ? "COALESCE(NULLIF(sp.insurance_price, 0), sp.base_price) as display_price"
    : "sp.base_price as display_price";

$sql = "SELECT sp.pricing_id, sp.service_name, sp.base_price, sp.insurance_price,
               $price_sql,
               ept.procedure_code
        FROM service_pricing sp
        LEFT JOIN ent_procedure_types ept ON sp.service_id = ept.procedure_type_id
        WHERE sp.service_type = 'PROCEDURE' AND sp.is_active = 1";

$params = [];
$types = '';

if (strlen($search) >= 1) {
    $sql .= " AND (sp.service_name LIKE ? OR ept.procedure_code LIKE ?)";
    $term = "%{$search}%";
    $params = [$term, $term];
    $types = 'ss';
}

$sql .= " ORDER BY sp.service_name ASC LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$types .= 'ii';

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['results' => [], 'pagination' => ['more' => false]]);
    exit();
}
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$results = [];
while ($row = $result->fetch_assoc()) {
    $price = floatval($row['display_price'] ?? $row['base_price']);
    $label = $row['service_name'];
    if (!empty($row['procedure_code'])) {
        $label .= ' (' . $row['procedure_code'] . ')';
    }
    $label .= ' - KES ' . number_format($price, 2);

    $results[] = [
        'id' => $row['pricing_id'],
        'text' => $label,
        'pricing_id' => $row['pricing_id'],
        'service_name' => $row['service_name'],
        'procedure_code' => $row['procedure_code'] ?? '',
        'price' => $price,
        'base_price' => floatval($row['base_price'] ?? 0),
        'insurance_price' => $row['insurance_price'] ? floatval($row['insurance_price']) : null
    ];
}

// Pagination
$count_sql = "SELECT COUNT(*) as total FROM service_pricing sp
              LEFT JOIN ent_procedure_types ept ON sp.service_id = ept.procedure_type_id
              WHERE sp.service_type = 'PROCEDURE' AND sp.is_active = 1";
$count_params = [];
$count_types = '';
if (strlen($search) >= 1) {
    $count_sql .= " AND (sp.service_name LIKE ? OR ept.procedure_code LIKE ?)";
    $count_params = ["%{$search}%", "%{$search}%"];
    $count_types = 'ss';
}
$cstmt = $conn->prepare($count_sql);
if ($cstmt) {
    if ($count_params) {
        $cstmt->bind_param($count_types, ...$count_params);
    }
    $cstmt->execute();
    $total = (int)($cstmt->get_result()->fetch_assoc()['total'] ?? 0);
} else {
    $total = count($results);
}

echo json_encode([
    'results' => $results,
    'pagination' => ['more' => ($offset + $per_page) < $total]
]);
