<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../dripend/includes/db.php';

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b;'>Fatal Error: Database connection failed.</div>");
}

$error_message = "";
$success_message = "";

// ==============================================================================
// 1. FETCH FACILITY PROFILE & SYSTEM DEFAULTS
// ==============================================================================
$facility = ['hospital_name' => 'Enterprise LIS Facility'];
$resFacility = $conn->query("SELECT hospital_name FROM facility_profile LIMIT 1");
if ($resFacility && $resFacility->num_rows > 0) {
    $facility = $resFacility->fetch_assoc();
}

// Fallback session enforcement for unauthenticated testing environments
if (!isset($_SESSION['user_full_name'])) {
    $qUser = "SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM staff WHERE is_active = 1 LIMIT 1";
    $resUser = $conn->query($qUser);
    $_SESSION['user_full_name'] = ($resUser && $resUser->num_rows > 0) ? $resUser->fetch_assoc()['full_name'] : 'System Admin';
}

// ==============================================================================
// 2. FORM PROCESSING & ENTERPRISE COMPLIANCE LOGIC
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patient_no = $_POST['patient_no'] ?? '';
    $doctor_id = !empty($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : null;
    $visit_date = $_POST['visit_date'] ?? date('Y-m-d');
    $visit_time = $_POST['visit_time'] ?? date('H:i');
    
    // Dynamic Visit Tracking
    $payment_category = $_POST['payment_category'] ?? 'Cash';
    $nhis_service_type = $_POST['nhis_service_type'] ?? 'Out-patient';
    $attendance_type = $_POST['attendance_type'] ?? 'Acute Episode';
    $ccc_code = $_POST['ccc_code'] ?? null;
    $notes = $_POST['notes'] ?? '';
    
    // Dynamic Master Record Update (Insurance)
    $dynamic_ins_no = $_POST['dynamic_ins_no'] ?? null;
    if ($payment_category === 'NHIS' && !empty($dynamic_ins_no)) {
        $upd = $conn->prepare("UPDATE patient SET nhis_no = ? WHERE patient_no = ?");
        $upd->bind_param("ss", $dynamic_ins_no, $patient_no); 
        $upd->execute();
    } elseif ($payment_category === 'Corporate' && !empty($dynamic_ins_no)) {
        $upd = $conn->prepare("UPDATE patient SET other_insurance_no = ? WHERE patient_no = ?");
        $upd->bind_param("ss", $dynamic_ins_no, $patient_no); 
        $upd->execute();
    }
    
    $cart_services = $_POST['cart_service_id'] ?? [];
    $cart_amounts = $_POST['cart_amount'] ?? [];
    $cart_tariffs = $_POST['cart_tariff'] ?? [];
    $cart_is_consult = $_POST['cart_is_consult'] ?? [];

    if (empty($cart_services)) {
        $error_message = "You must add at least one service to the cart.";
    } else {
        $conn->begin_transaction();
        try {
            $total_billed = 0.00;
            $specialty_code = 'OPDC'; // Default fallback
            $billing_structure = 'Unbundled'; // Default to Unbundled
            
            foreach ($cart_amounts as $index => $amt) {
                $total_billed += (float)$amt;
                
                // If there is ANY consultation, the visit becomes All Inclusive
                if ($cart_is_consult[$index] == 1) {
                    $billing_structure = 'All Inclusive';
                }
                
                // Auto-Extract Specialty Code from the first valid GDRG in the cart
                if (!empty($cart_tariffs[$index]) && $cart_tariffs[$index] !== 'CASH/CORP' && $specialty_code === 'OPDC') {
                    $extracted = substr($cart_tariffs[$index], 0, 4);
                    if (ctype_alpha($extracted)) $specialty_code = $extracted;
                }
            }

            // Auto-Calculate Visit Number for current month
            $vNumStmt = $conn->prepare("SELECT COUNT(id) as vcount FROM visit_master WHERE patient_no = ? AND MONTH(visit_date) = MONTH(?) AND YEAR(visit_date) = YEAR(?)");
            $vNumStmt->bind_param("sss", $patient_no, $visit_date, $visit_date);
            $vNumStmt->execute();
            $vRes = $vNumStmt->get_result()->fetch_assoc();
            $visit_number = ($vRes['vcount'] ?? 0) + 1;
            $vNumStmt->close();

            // Generate Appointment No
            $appt_no = 'APT-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

            // Insert Visit Master (100% DHIMS & NHIS Claim Form Compliant)
            $stmtM = $conn->prepare("INSERT INTO visit_master (appointment_no, patient_no, primary_doctor_id, visit_date, visit_time, payment_category, nhis_service_type, ccc_code, attendance_type, specialty_code, visit_number, billing_structure, total_billed, notes, status, clinical_outcome) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Scheduled', 'Pending')");
            $stmtM->bind_param("ssisssssssisds", $appt_no, $patient_no, $doctor_id, $visit_date, $visit_time, $payment_category, $nhis_service_type, $ccc_code, $attendance_type, $specialty_code, $visit_number, $billing_structure, $total_billed, $notes);
            $stmtM->execute();
            $visit_id = $conn->insert_id;
            $stmtM->close();

            // Insert Visit Details (Cart Items)
            $stmtD = $conn->prepare("INSERT INTO visit_details (visit_master_id, service_id, billed_amount, applied_tariff_code, is_consultation, status) VALUES (?, ?, ?, ?, ?, 'Pending')");
            for ($i = 0; $i < count($cart_services); $i++) {
                $s_id = (int)$cart_services[$i];
                $s_amt = (float)$cart_amounts[$i];
                $s_tar = !empty($cart_tariffs[$i]) ? $cart_tariffs[$i] : null;
                $s_isc = (int)$cart_is_consult[$i];
                $stmtD->bind_param("iidss", $visit_id, $s_id, $s_amt, $s_tar, $s_isc);
                $stmtD->execute();
            }
            $stmtD->close();

            // ==============================================================================
            // THE ENTERPRISE BILLING HOOK (Generates the Invoice for the Cashier)
            // ==============================================================================
            $inv_no = 'INV-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -4));
            
            // If the bill is 0.00 (e.g., 100% covered by insurance or Staff), auto-mark as Paid to skip cashier
            $inv_status = ($total_billed > 0) ? 'Unpaid' : 'Paid'; 
            
            $stmtInv = $conn->prepare("INSERT INTO patient_invoices (invoice_no, patient_no, department_origin, total_amount, balance_due, status) VALUES (?, ?, 'Front Desk / OPD', ?, ?, ?)");
            $stmtInv->bind_param("ssdds", $inv_no, $patient_no, $total_billed, $total_billed, $inv_status);
            $stmtInv->execute();
            $stmtInv->close();
            // ==============================================================================

            $conn->commit();
            $_SESSION['success'] = "Appointment $appt_no booked. Marked as Visit #$visit_number ($billing_structure).";
            header("Location: appointment_calendar.php");
            exit;

        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Booking failed: " . $e->getMessage();
        }
    }
}

// ==============================================================================
// 3. FETCH DATA FOR UI & JS PRICING ENGINE
// ==============================================================================
$patient_id = $_GET['patient_id'] ?? '';
$patient = null;
$def_cat = 'Cash'; // Safe fallback variable

if ($patient_id) {
    // SYNCHRONIZED QUERY: Matches the new Schema
    $stmt = $conn->prepare("
        SELECT 
            p.*,
            COALESCE(pr.prefix_name, '') AS prefix_name,
            COALESCE(g.gender_name, 'NA') AS gender_name,
            COALESCE(i.insurance_name, 'Retail') AS membership_type,
            COALESCE(i.insurance_name, 'Cash') AS insurance_name,
            TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
            '0.00' AS outstanding_balance, 
            COALESCE(p.allergies, 'None Reported') AS allergies, 
            COALESCE(p.medical_conditions, 'None Reported') AS medical_conditions,
            COALESCE(p.blood_group, 'Unknown') AS blood_group,
            COALESCE(p.is_staff, 0) AS is_staff,
            COALESCE(p.is_staff_dependent, 0) AS is_staff_dependent,
            CASE 
                WHEN p.is_staff = 1 OR p.is_staff_dependent = 1 THEN 'Staff'
                WHEN p.nhis_no IS NOT NULL AND p.nhis_no != '' THEN 'NHIS'
                WHEN p.other_insurance_id IS NOT NULL THEN 'Corporate'
                ELSE 'Cash'
            END AS default_payment_category
        FROM patient p
        LEFT JOIN prefix pr ON p.prefix_id = pr.id
        LEFT JOIN gender g ON p.gender_id = g.id
        LEFT JOIN insurance_type i ON p.other_insurance_id = i.id
        WHERE p.patient_no = ? LIMIT 1
    ");
    $stmt->bind_param("s", $patient_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    // Store critical data in protected variables before Header include overwrites $patient
    if ($patient) {
        $def_cat = $patient['default_payment_category'] ?? 'Cash';
    }
}

if (!$patient) die("<div style='padding:40px; text-align:center;'><h2>Patient Not Found</h2><a href='../patient/search_patient.php'>Back to Search</a></div>");

// CHECK FOR PREVIOUS CONSULTATIONS TODAY (For Same-Day Cash Override Logic)
$today = date('Y-m-d');
$cStmt = $conn->prepare("
    SELECT COUNT(vd.id) as c_count 
    FROM visit_details vd 
    JOIN visit_master vm ON vd.visit_master_id = vm.id 
    WHERE vm.patient_no = ? AND vm.visit_date = ? AND vd.is_consultation = 1
");
$cStmt->bind_param("ss", $patient_id, $today);
$cStmt->execute();
$cRes = $cStmt->get_result()->fetch_assoc();
$previous_consultations_today = (int)$cRes['c_count'];
$cStmt->close();

$doctors = [];
$docRes = $conn->query("SELECT staff_id AS id, CONCAT('Dr. ', first_name, ' ', last_name) AS name FROM staff WHERE is_doctor_id = 1 AND status_id = 1");
if ($docRes) while ($r = $docRes->fetch_assoc()) $doctors[] = $r;

$departments = [];
$depRes = $conn->query("SELECT id, department_name FROM departments WHERE is_active = 1");
if ($depRes) while ($r = $depRes->fetch_assoc()) $departments[] = $r;

// FETCH THE UPGRADED CATALOG (Exclude Physical Pharmacy Items)
$services = [];
$srvRes = $conn->query("
    SELECT id, department_id, service_name, service_type, is_consultation, 
           cash_price_adult, corporate_price, 
           gdrg_adult_code, tariff_adult, gdrg_child_code, tariff_child,
           is_copay_required, copay_amount,
           corp_is_copay_required, corp_copay_amount
    FROM service_catalog 
    WHERE is_active = 1 
    AND service_type != 'Drug' 
    AND service_type != 'Consumable'
");
if ($srvRes) while ($r = $srvRes->fetch_assoc()) $services[] = $r;

$services_json = json_encode($services);
// Safely encode JSON to prevent undefined key errors from overwrites
$patient_json = json_encode([
    'age' => (int)($patient['age'] ?? 0),
    'payment_category' => $def_cat
]);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Book Encounter | <?= htmlspecialchars($facility['hospital_name']) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-blue-light: #eff6ff; --e-green: #16a34a; --e-red: #dc2626; --bg-color: #f8fafc; --card-bg: #ffffff; --border-color: #e2e8f0; --text-main: #0f172a; --text-muted: #64748b; }
* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, sans-serif; }
body { background: var(--bg-color); color: var(--text-main); overflow-x: hidden; }
.page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; display: block !important; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
.page-title { font-size: 24px; font-weight: 800; color: var(--e-blue); text-transform: uppercase; margin: 0; }
.alert { padding: 15px; border-radius: 8px; font-weight: 600; margin-bottom: 20px; border-left: 5px solid; }
.alert-error { background: #fee2e2; color: #991b1b; border-color: #ef4444; }
.content-grid { display: grid; grid-template-columns: 350px 1fr; gap: 25px; }
.card { background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 10px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.02); }
.card-title { font-size: 16px; font-weight: 800; color: var(--e-blue); margin-bottom: 15px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; }
.form-group { margin-bottom: 15px; }
.form-group label { display: block; font-size: 12px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-bottom: 6px; }
.form-control { width: 100%; padding: 12px 14px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; outline: none; background: #fff; }
.form-control:focus { border-color: var(--e-blue); box-shadow: 0 0 0 3px var(--e-blue-light); }
.cart-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
.cart-table th { background: #f1f5f9; padding: 12px; text-align: left; font-size: 12px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; border-bottom: 2px solid var(--border-color); }
.cart-table td { padding: 15px 12px; border-bottom: 1px solid var(--border-color); font-size: 14px; color: var(--text-main); font-weight: 600; }
.type-badge { padding: 4px 8px; border-radius: 4px; font-size: 11px; background: #e2e8f0; color: #475569; }
.type-badge.consult { background: #dcfce7; color: #166534; }
.btn-remove { background: #fee2e2; color: #dc2626; border: none; padding: 8px 12px; border-radius: 6px; cursor: pointer; transition: 0.2s; }
.cart-summary { margin-top: 20px; padding: 20px; background: #f8fafc; border-radius: 8px; border: 1px dashed #cbd5e1; display: flex; justify-content: space-between; align-items: center; }
.cart-total { font-size: 28px; font-weight: 800; color: var(--e-green); }
.btn-add { background: var(--e-blue); color: #fff; border: none; padding: 12px 15px; border-radius: 6px; font-weight: 700; cursor: pointer; width: 100%; transition: 0.2s; }
.btn-submit { background: var(--e-green); color: #fff; border: none; padding: 14px 30px; border-radius: 8px; font-weight: 800; cursor: pointer; font-size: 16px; transition: 0.2s; }
.btn-submit:disabled { background: #94a3b8; cursor: not-allowed; }

/* MODAL STYLES */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(15, 23, 42, 0.6); display: none; align-items: center; justify-content: center; z-index: 9999; opacity: 0; transition: opacity 0.2s ease; backdrop-filter: blur(2px); }
.modal-overlay.active { display: flex; opacity: 1; }
.modal-box { background: #fff; width: 90%; max-width: 420px; border-radius: 12px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); transform: scale(0.95); transition: transform 0.2s ease; overflow: hidden; }
.modal-overlay.active .modal-box { transform: scale(1); }
.modal-header { padding: 18px 20px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; gap: 10px; font-weight: 800; font-size: 16px; }
.modal-header.alert-header { color: var(--e-blue); background: var(--e-blue-light); }
.modal-header.warn-header { color: #b45309; background: #fef3c7; }
.modal-body { padding: 20px; color: var(--text-main); font-size: 14px; line-height: 1.6; }
.modal-footer { padding: 15px 20px; background: #f8fafc; border-top: 1px solid var(--border-color); display: flex; justify-content: flex-end; gap: 12px; }
.btn-modal { padding: 10px 18px; border-radius: 6px; font-weight: 700; cursor: pointer; border: none; font-size: 13px; transition: 0.2s; }
.btn-modal-cancel { background: #e2e8f0; color: #475569; }
.btn-modal-cancel:hover { background: #cbd5e1; }
.btn-modal-primary { background: var(--e-blue); color: #fff; }
.btn-modal-primary:hover { background: #1e293b; }
.btn-modal-danger { background: var(--e-red); color: #fff; }
.btn-modal-danger:hover { background: #b91c1c; }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">
    <div class="page-header">
        <h1 class="page-title"><i class="fa-solid fa-notes-medical"></i> Book Encounter & Services</h1>
    </div>

    <?php if (!empty($error_message)): ?><div class="alert alert-error"><?php echo htmlspecialchars($error_message); ?></div><?php endif; ?>
    
    <!-- This include overwrites the $patient variable, but we have safely stored the defaults -->
    <?php include('../../dripend/statpages/patientProfileHeader.php'); ?>

    <form method="post" action="">
        <input type="hidden" name="patient_no" value="<?php echo htmlspecialchars($patient_id); ?>">
        
        <div class="content-grid">
            <div>
                <div class="card" style="margin-bottom: 20px;">
                    <div class="card-title"><i class="fa-regular fa-clock"></i> 1. Claim Form Attributes</div>
                    
                    <div class="form-group">
                        <label style="color:#0284c7;">Payment Category For THIS Visit</label>
                        <select name="payment_category" id="visitPaymentCat" class="form-control">
                            <!-- USING THE SAFE $def_cat VARIABLE HERE -->
                            <option value="Cash" <?= $def_cat === 'Cash' ? 'selected' : '' ?>>Cash / Out-of-Pocket</option>
                            <option value="NHIS" <?= $def_cat === 'NHIS' ? 'selected' : '' ?>>National Health Insurance (NHIS)</option>
                            <option value="Corporate" <?= $def_cat === 'Corporate' ? 'selected' : '' ?>>Corporate / Private Insurance</option>
                            <option value="Staff" <?= $def_cat === 'Staff' ? 'selected' : '' ?>>Staff / Internal Coverage</option>
                        </select>
                    </div>

                    <div class="form-group" id="dynamicInsBox" style="display:none; background:#e0f2fe; padding:12px; border-radius:6px; border:1px dashed #3b82f6;">
                        <label id="dynamicInsLabel" style="color:#0284c7;">Insurance ID Number</label>
                        <input type="text" name="dynamic_ins_no" id="dynamicInsInput" class="form-control" placeholder="Update ID number if missing...">
                        <div style="font-size:11px; margin-top:5px; color:#64748b;">(Entering a new number will update the master record)</div>
                        
                        <div id="nhisCccBox" style="margin-top:10px; display:none;">
                            <label style="color:#b45309;">NHIS Claim Check Code (CCC)</label>
                            <input type="text" name="ccc_code" id="cccInput" class="form-control" placeholder="Enter 5-8 digit CCC for this visit">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Type of Service (Facility Location)</label>
                        <select name="nhis_service_type" id="nhisServiceType" class="form-control">
                            <option value="Out-patient">Out-patient (OPD/Consultation)</option>
                            <option value="Diagnostic">Diagnostic (Labs/Imaging Only)</option>
                            <option value="Pharmacy">Pharmacy (Refills Only)</option>
                            <option value="In-patient">In-patient (Ward Admission)</option>
                        </select>
                    </div>

                    <div class="form-group" id="attendanceTypeBox" style="display:none;">
                        <label>NHIS Type of Attendance</label>
                        <select name="attendance_type" class="form-control">
                            <option value="Acute Episode">Acute Episode</option>
                            <option value="Chronic Follow-up">Chronic Follow-up</option>
                            <option value="Emergency">Emergency</option>
                            <option value="ANC">ANC</option>
                        </select>
                    </div>

                    <div class="form-group" style="border-top: 1px dashed #cbd5e1; padding-top: 15px; margin-top:10px;">
                        <label>Assign Provider (Optional)</label>
                        <select name="doctor_id" class="form-control">
                            <option value="">-- Unassigned (General Queue) --</option>
                            <?php foreach ($doctors as $doc): ?>
                                <option value="<?php echo $doc['id']; ?>"><?php echo htmlspecialchars($doc['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="display:flex; gap:10px;">
                        <div class="form-group" style="flex:1;">
                            <label>Date</label>
                            <input type="date" name="visit_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label>Time</label>
                            <input type="time" name="visit_time" class="form-control" value="<?php echo date('H:i'); ?>" required>
                        </div>
                    </div>
                </div>

                <div class="card" style="border-left: 5px solid var(--e-blue);">
                    <div class="card-title"><i class="fa-solid fa-plus-circle"></i> 2. Add Service to Cart</div>
                    <div class="form-group">
                        <label>Filter by Department</label>
                        <select id="deptSelect" class="form-control">
                            <option value="">-- Select Department --</option>
                            <?php foreach ($departments as $d): ?><option value="<?php echo $d['id']; ?>"><?php echo htmlspecialchars($d['department_name']); ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Select Service</label>
                        <select id="serviceSelect" class="form-control" disabled><option value="">Select a Department first...</option></select>
                    </div>
                    <button type="button" id="btnAddService" class="btn-add" disabled><i class="fa-solid fa-cart-plus"></i> Add to Request Cart</button>
                </div>
            </div>

            <div class="card">
                <div class="card-title"><i class="fa-solid fa-clipboard-list"></i> 3. Requested Services Cart</div>
                
                <table class="cart-table" id="cartTable">
                    <thead><tr><th>Service Requested</th><th>Type</th><th>Tariff Code</th><th>Patient Payable</th><th></th></tr></thead>
                    <tbody></tbody>
                </table>

                <div class="cart-summary">
                    <div>
                        <div style="font-size:12px; font-weight:700; color:var(--text-muted); text-transform:uppercase;">Total Payable Now</div>
                        <div class="cart-total" id="cartTotalDisplay">GHS 0.00</div>
                    </div>
                    <button type="submit" id="btnSubmitCart" class="btn-submit" disabled><i class="fa-solid fa-check-double"></i> Confirm & Book Visit</button>
                </div>

                <div class="form-group" style="margin-top:25px;">
                    <label>Reception Notes</label>
                    <textarea name="notes" class="form-control" rows="3" placeholder="Enter reason for visit or notes for the clinician..."></textarea>
                </div>
            </div>

        </div>
    </form>
</div>

<div id="alertModal" class="modal-overlay">
    <div class="modal-box">
        <div class="modal-header alert-header" id="alertTitle"><i class="fa-solid fa-circle-info"></i> System Notice</div>
        <div class="modal-body" id="alertBody"></div>
        <div class="modal-footer">
            <button class="btn-modal btn-modal-primary" onclick="closeAlertModal()">Okay</button>
        </div>
    </div>
</div>

<div id="confirmModal" class="modal-overlay">
    <div class="modal-box">
        <div class="modal-header warn-header" id="confirmTitle"><i class="fa-solid fa-triangle-exclamation"></i> Action Required</div>
        <div class="modal-body" id="confirmBody"></div>
        <div class="modal-footer">
            <button class="btn-modal btn-modal-cancel" onclick="closeConfirmModal(false)">Cancel</button>
            <button class="btn-modal btn-modal-danger" onclick="closeConfirmModal(true)">Proceed & Override</button>
        </div>
    </div>
</div>

<script>
const catalog = <?php echo $services_json; ?>;
const patient = <?php echo $patient_json; ?>;

// Safely pull from the overwritten array using null coalescing, defaulting to empty strings if missing
const p_NhisNo = "<?php echo htmlspecialchars($patient['nhis_no'] ?? ''); ?>";
const p_CorpNo = "<?php echo htmlspecialchars($patient['other_insurance_no'] ?? ''); ?>";

// Fetch database history to enforce "One Consultation Per Day" rule
const previousConsultationsToday = <?php echo $previous_consultations_today; ?>;

let cartItems = [];
let totalAmount = 0.00;
let consultationsInCart = 0; 

// --- CUSTOM MODAL CONTROLLERS ---
let confirmCallback = null;

function showSystemAlert(message, title = "System Notice") {
    document.getElementById('alertTitle').innerHTML = `<i class="fa-solid fa-circle-info"></i> ${title}`;
    document.getElementById('alertBody').innerHTML = message;
    document.getElementById('alertModal').classList.add('active');
}
function closeAlertModal() {
    document.getElementById('alertModal').classList.remove('active');
}

function showSystemConfirm(message, title, callback) {
    document.getElementById('confirmTitle').innerHTML = `<i class="fa-solid fa-triangle-exclamation"></i> ${title}`;
    document.getElementById('confirmBody').innerHTML = message;
    confirmCallback = callback;
    document.getElementById('confirmModal').classList.add('active');
}
function closeConfirmModal(result) {
    document.getElementById('confirmModal').classList.remove('active');
    if (confirmCallback) {
        confirmCallback(result);
        confirmCallback = null;
    }
}

// --- DYNAMIC UI TOGGLES ---
const visitPaymentCat = document.getElementById('visitPaymentCat');
const dynamicInsBox = document.getElementById('dynamicInsBox');
const dynamicInsLabel = document.getElementById('dynamicInsLabel');
const dynamicInsInput = document.getElementById('dynamicInsInput');
const nhisCccBox = document.getElementById('nhisCccBox');
const cccInput = document.getElementById('cccInput');
const attendanceTypeBox = document.getElementById('attendanceTypeBox');
const nhisServiceType = document.getElementById('nhisServiceType');

function togglePaymentFields() {
    const cat = visitPaymentCat.value;
    patient.payment_category = cat; 
    
    if (cartItems.length > 0) {
        cartItems = []; consultationsInCart = 0; renderCart();
        showSystemAlert("The cart was cleared to recalculate tariffs and co-pays based on the new payment method.", "Payment Method Updated");
    }
    
    if (cat === 'NHIS') {
        dynamicInsBox.style.display = 'block';
        attendanceTypeBox.style.display = 'block';
        nhisCccBox.style.display = 'block';
        dynamicInsLabel.textContent = "NHIS Member No.";
        dynamicInsInput.value = p_NhisNo;
        cccInput.required = true;
    } else if (cat === 'Corporate') {
        dynamicInsBox.style.display = 'block';
        attendanceTypeBox.style.display = 'none';
        nhisCccBox.style.display = 'none';
        dynamicInsLabel.textContent = "Corporate Insurance ID";
        dynamicInsInput.value = p_CorpNo;
        cccInput.required = false;
    } else if (cat === 'Staff') {
        dynamicInsBox.style.display = 'none';
        attendanceTypeBox.style.display = 'none';
        nhisCccBox.style.display = 'none';
        cccInput.required = false;
    } else {
        dynamicInsBox.style.display = 'none';
        attendanceTypeBox.style.display = 'none';
        nhisCccBox.style.display = 'none';
        cccInput.required = false;
    }
}
visitPaymentCat.addEventListener('change', togglePaymentFields);
window.addEventListener('DOMContentLoaded', togglePaymentFields);

// --- CART LOGIC ---
const deptSelect = document.getElementById('deptSelect');
const serviceSelect = document.getElementById('serviceSelect');
const btnAddService = document.getElementById('btnAddService');

deptSelect.addEventListener('change', function() {
    serviceSelect.innerHTML = '<option value="">-- Select Service --</option>';
    if (!this.value) { serviceSelect.disabled = true; btnAddService.disabled = true; return; }
    catalog.filter(s => s.department_id == this.value).forEach(s => {
        let opt = document.createElement('option');
        opt.value = s.id; opt.textContent = s.service_name;
        serviceSelect.appendChild(opt);
    });
    serviceSelect.disabled = false;
});

serviceSelect.addEventListener('change', function() { btnAddService.disabled = !this.value; });

btnAddService.addEventListener('click', function() {
    const service = catalog.find(s => s.id == serviceSelect.value);
    if (!service) return;

    if (cartItems.some(i => i.id == service.id)) {
        showSystemAlert("This service is already in the requested cart.", "Duplicate Entry"); return;
    }

    // --- SAME-DAY MULTIPLE CONSULTATION OVERRIDE LOGIC ---
    if (service.is_consultation == 1) {
        let totalConsults = previousConsultationsToday + consultationsInCart;
        if (totalConsults >= 1 && (patient.payment_category === 'NHIS' || patient.payment_category === 'Corporate')) {
            let msg = "<strong>The patient has already utilized their single insurance-covered consultation for today.</strong><br><br>This secondary consultation will NOT be covered by insurance and must be billed fully as Out-of-Pocket (Cash).<br><br>Do you want to proceed and bill the patient as Cash for this consultation?";
            
            showSystemConfirm(msg, "INSURANCE RULE TRIGGERED", function(proceed) {
                if (proceed) {
                    nhisServiceType.value = 'Out-patient';
                    processCartAddition(service, true); // Force Cash
                }
            });
            return;
        } else {
            nhisServiceType.value = 'Out-patient';
        }
    }

    processCartAddition(service, false);
});

// Extracted processing function to cleanly handle Co-Payment logic (NHIS, Corporate, Staff)
function processCartAddition(service, forceCashOverride) {
    let billedAmount = 0.00;
    let appliedCode = 'CASH/CORP';
    let isCoveredIns = false;

    // --- UNIVERSAL CO-PAYMENT & TARIFF PRICING ENGINE ---
    if (!forceCashOverride && patient.payment_category === 'Staff') {
        isCoveredIns = true;
        appliedCode = 'STAFF-COV';
        billedAmount = 0.00; // Fully covered internal staff
    } else if (!forceCashOverride && patient.payment_category === 'NHIS' && service.tariff_adult !== null) {
        isCoveredIns = true;
        
        // Determine Age Code for the backend claim
        if (patient.age >= 12) { appliedCode = service.gdrg_adult_code; } 
        else { appliedCode = service.gdrg_child_code; }
        
        if (service.is_copay_required == 1) {
            billedAmount = parseFloat(service.copay_amount); // Patient pays NHIS co-pay
        } else {
            billedAmount = 0.00; // Fully covered by NHIS
        }
    } else if (!forceCashOverride && patient.payment_category === 'Corporate') {
        isCoveredIns = true;
        
        // Check Corporate Co-Payment Rule
        if (service.corp_is_copay_required == 1) {
            billedAmount = parseFloat(service.corp_copay_amount); // Patient pays Corp co-pay
        } else {
            billedAmount = 0.00; // Fully covered by Corporate
        }
    } else {
        // Standard Cash billing (or forced cash due to duplicate rule)
        // Ensure we pull the correct cash_price_adult column based on the new schema
        billedAmount = parseFloat(service.cash_price_adult);
    }

    cartItems.push({
        id: service.id, name: service.service_name, type: service.service_type,
        amount: billedAmount, code: appliedCode, is_consult: service.is_consultation,
        is_ins: isCoveredIns, forced_cash: forceCashOverride
    });

    if (service.is_consultation == 1) consultationsInCart++;
    renderCart();
    
    serviceSelect.value = ''; 
    btnAddService.disabled = true;
}

function renderCart() {
    const tbody = document.querySelector('#cartTable tbody');
    tbody.innerHTML = ''; totalAmount = 0.00;

    cartItems.forEach((item, index) => {
        totalAmount += item.amount;
        let bClass = item.is_consult == 1 ? 'type-badge consult' : 'type-badge';
        
        // Visual cue for Co-pays, Covered services, and Forced Cash
        let displayAmount = item.amount.toFixed(2);
        if (item.forced_cash) {
            displayAmount += ' <br><span style="font-size:10px; color:#dc2626; font-weight:800;">(Additional Service)</span>';
        } else if (item.is_ins) {
            if (item.amount === 0) displayAmount += ' <span style="font-size:10px; color:#16a34a; font-weight:800;">(Covered)</span>';
            else displayAmount += ' <span style="font-size:10px; color:#b45309; font-weight:800;">(Co-pay)</span>';
        }

        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${item.name}
                <input type="hidden" name="cart_service_id[]" value="${item.id}">
                <input type="hidden" name="cart_amount[]" value="${item.amount}">
                <input type="hidden" name="cart_tariff[]" value="${item.code}">
                <input type="hidden" name="cart_is_consult[]" value="${item.is_consult}">
            </td>
            <td><span class="${bClass}">${item.type}</span></td>
            <td><span style="font-family:monospace; background:#f1f5f9; padding:2px 6px;">${item.code || '--'}</span></td>
            <td>${displayAmount}</td>
            <td><button type="button" class="btn-remove" onclick="removeFromCart(${index})"><i class="fa-solid fa-trash"></i></button></td>
        `;
        tbody.appendChild(tr);
    });
    document.getElementById('cartTotalDisplay').textContent = 'GHS ' + totalAmount.toFixed(2);
    document.getElementById('btnSubmitCart').disabled = cartItems.length === 0;
}

window.removeFromCart = function(index) {
    if (cartItems[index].is_consult == 1) consultationsInCart--; 
    cartItems.splice(index, 1); renderCart();
};
</script>
</body>
</html>