<?php
include('visit_ticket_action.php'); // Provides $csrf, $ticket, $existingLabOrders, $labProducts, $doctors

// Function to get last 3 updates for each section
function getRecentUpdates($section, $limit = 3) {
    global $pdo, $ticket_id;
    
    if (!$ticket_id) return '';
    
    try {
        $stmt = $pdo->prepare("
            SELECT h.*, u.username, u.user_role 
            FROM visit_ticket_history h
            LEFT JOIN users u ON h.changed_by = u.id
            WHERE h.visit_ticket_id = ? AND h.section = ?
            ORDER BY h.changed_at DESC
            LIMIT ?
        ");
        $stmt->execute([$ticket_id, $section, $limit]);
        $updates = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($updates)) {
            return "<small class='text-muted'>No updates yet</small>";
        }
        
        $html = '<div class="recent-updates">';
        foreach ($updates as $update) {
            $username = htmlspecialchars($update['username'] ?? 'System');
            $role = htmlspecialchars($update['user_role'] ?? 'System');
            $time = date('M d, H:i', strtotime($update['changed_at']));
            
            // Get role badge color
            $roleBadgeClass = 'badge-secondary';
            $userRole = strtolower($role);
            if (strpos($userRole, 'admin') !== false) $roleBadgeClass = 'badge-danger';
            elseif (strpos($userRole, 'doctor') !== false) $roleBadgeClass = 'badge-primary';
            elseif (strpos($userRole, 'nurse') !== false) $roleBadgeClass = 'badge-info';
            elseif (strpos($userRole, 'lab') !== false) $roleBadgeClass = 'badge-warning';
            
            $html .= "<div class='update-item mb-1'>
                <span class='badge {$roleBadgeClass}'>{$role}</span>
                <strong>{$username}</strong> 
                <small class='text-muted'>{$time}</small>
            </div>";
        }
        $html .= '</div>';
        
        return $html;
    } catch (Exception $e) {
        return "<small class='text-muted'>Update info unavailable</small>";
    }
}
?>

<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>

<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
    <div class="content-wrapper">
        <h2 class="card-title text-center">PATIENT TREATMENT FORM</h2>
        <hr>

        <?php include('visit_ticket_info.php'); ?>

        <?php $disabled = $isVisitClosed ? 'disabled readonly' : ''; ?>

        <!-- History Modals Container -->
        <div id="historyModals"></div>

        <div class="row">
            <div class="card col-md-4 col-sm-12">
                <?php include('patient_history.php'); ?>
                <!-- Admit to Hospital Button -->
                <div class="admit-btn-container">
                    <a href="admit_patient.php?patient_id=<?= $visit['patient_id'] ?>&visit_id=<?= $visit_id ?>&ticket_id=<?= $ticket_id ?>" 
                       class="btn btn-warning btn-block">
                        <i class="icon-home"></i> Admit to Hospital
                    </a>
                </div>
            </div>
            
            <div class="col-md-8 col-sm-12">
                <!-- Catchment & New Case -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="catchment">
                    
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Catchment Area / New Case? <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="catchment">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <label>Catchment Area <span class="text-danger">*</span></label>
                                    <select name="catchment_area" class="form-control required-field" <?= $disabled ?> required>
                                        <option value="" <?= empty($ticket['catchment_area']) ? 'selected' : '' ?>>-- Select Catchment Area --</option>
                                        <option value="Zone" <?= ($ticket['catchment_area'] ?? '') === 'Zone' ? 'selected' : '' ?>>Zone</option>
                                        <option value="Out of Zone" <?= ($ticket['catchment_area'] ?? '') === 'Out of Zone' ? 'selected' : '' ?>>Out of Zone</option>
                                        <option value="Not Mentioned" <?= ($ticket['catchment_area'] ?? '') === 'Not Mentioned' ? 'selected' : '' ?>>Not Mentioned</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label>New Case? <span class="text-danger">*</span></label>
                                    <select name="new_case" class="form-control required-field" <?= $disabled ?> required>
                                        <option value="" <?= empty($ticket['new_case']) ? 'selected' : '' ?>>-- New Case --</option>
                                        <option value="Yes" <?= ($ticket['new_case'] ?? '') === 'Yes' ? 'selected' : '' ?>>Yes</option>
                                        <option value="No" <?= ($ticket['new_case'] ?? '') === 'No' ? 'selected' : '' ?>>No</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <div>
                                <!-- No add button for this section -->
                            </div>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('catchment') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Catchment Info
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Vital Signs -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="vital_signs">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Vital Signs <span class="text-danger">*</span> (Temperature and Weight Required)</h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="vital_signs">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3"><label>Systolic</label><input type="number" step="0.1" name="systolic" class="form-control" value="<?= htmlspecialchars((string)($ticket['systolic'] ?? '')) ?>" <?= $disabled ?>></div>
                                <div class="col-md-3"><label>Diastolic</label><input type="number" step="0.1" name="diastolic" class="form-control" value="<?= htmlspecialchars((string)($ticket['diastolic'] ?? '')) ?>" <?= $disabled ?>></div>
                                <div class="col-md-3"><label>Heart Rate</label><input type="number" step="0.1" name="heart_rate" class="form-control" value="<?= htmlspecialchars((string)($ticket['heart_rate'] ?? '')) ?>" <?= $disabled ?>></div>
                                <div class="col-md-3"><label>Temperature <span class="text-danger">*</span></label><input type="number" step="0.1" name="temperature" class="form-control required-field" value="<?= htmlspecialchars((string)($ticket['temperature'] ?? '')) ?>" <?= $disabled ?> required></div>
                            </div>
                            <div class="row">
                                <div class="col-md-3"><label>Resp. Rate</label><input type="number" step="0.1" name="resp_rate" class="form-control" value="<?= htmlspecialchars((string)($ticket['resp_rate'] ?? '')) ?>" <?= $disabled ?>></div>
                                <div class="col-md-3"><label>SpO<sub>2</sub> (%)</label><input type="number" step="0.1" name="spo2" class="form-control" value="<?= htmlspecialchars((string)($ticket['spo2'] ?? '')) ?>" <?= $disabled ?>></div>
                                <div class="col-md-3"><label>Weight (kg) <span class="text-danger">*</span></label><input type="number" step="0.1" name="weight" class="form-control required-field" value="<?= htmlspecialchars((string)($ticket['weight'] ?? '')) ?>" <?= $disabled ?> required></div>
                                <div class="col-md-3"><label>Height (cm)</label><input type="number" step="0.1" name="height" class="form-control" value="<?= htmlspecialchars((string)($ticket['height'] ?? '')) ?>" <?= $disabled ?>></div>
                            </div>
                            <div class="form-group">
                                <label>Comment / Observation</label>
                                <textarea rows="3" class="form-control" name="vital_comment" <?= $disabled ?>><?= htmlspecialchars((string)($ticket['vital_comment'] ?? '')) ?></textarea>
                            </div>
                        </div>
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <div>
                                <!-- No add button for this section -->
                            </div>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('vital_signs') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Vital Signs
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Chief Complaints -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="chief_complaints">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Chief Complaints <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="chief_complaints">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body">
                            <textarea rows="5" class="form-control required-field" name="chief_complaints" <?= $disabled ?> required><?= htmlspecialchars((string)($ticket['chief_complaints'] ?? '')) ?></textarea>
                        </div>
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <div>
                                <!-- No add button for this section -->
                            </div>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('chief_complaints') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Chief Complaints
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Physical examination -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="physical_examination">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Physical examination: <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="physical_examination">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body">
                            <textarea rows="5" class="form-control required-field" name="physical_examination" <?= $disabled ?> required><?= htmlspecialchars((string)($ticket['physical_examination'] ?? '')) ?></textarea>
                        </div>
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <div>
                                <!-- No add button for this section -->
                            </div>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('physical_examination') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Physical Examination
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Differential Diagnosis -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="differential_diagnosis">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Differential Diagnosis <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="differential_diagnosis">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body">
                            <textarea rows="5" class="form-control required-field" name="differential_diagnosis" <?= $disabled ?> required><?= htmlspecialchars((string)($ticket['differential_diagnosis'] ?? '')) ?></textarea>
                        </div>
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <div>
                                <!-- No add button for this section -->
                            </div>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('differential_diagnosis') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Differential Diagnosis
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Lab Orders Card -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="lab_orders">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Lab Orders</h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="lab_orders">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body" id="lab-orders-container">
                            <?php if(!empty($existingLabOrders)): ?>
                                <?php foreach($existingLabOrders as $lo): ?>
                                    <?php
                                    // Safely handle sub_tests
                                    $subTests = $lo['sub_tests'] ?? null;
                                    if (!empty($subTests)) {
                                        if (is_string($subTests)) {
                                            $subTestsArray = json_decode($subTests, true) ?: [];
                                        } elseif (is_array($subTests)) {
                                            $subTestsArray = $subTests;
                                        } else {
                                            $subTestsArray = [];
                                        }
                                    } else {
                                        $subTestsArray = [];
                                    }
                                    $hasSub = !empty($subTestsArray);
                                    ?>
                                    <div class="lab-order-row row mb-1 align-items-center">
                                        <div class="col-md-3">
                                            <select name="lab_test_id[]" class="form-control lab-select" <?= $disabled ?>>
                                                <option value="">Select Lab Test</option>
                                                <?php foreach($labProducts as $lp): ?>
                                                    <option value="<?= $lp['id'] ?>" 
                                                        <?= $lp['id']==$lo['product_id']?'selected':'' ?>
                                                        <?= in_array($lp['id'],$requestedLabIds)&&$lp['id']!=$lo['product_id']?'disabled':'' ?>>
                                                        <?= htmlspecialchars($lp['name']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-8">
                                            <?php if($hasSub): ?>
                                            <button type="button" class="btn btn-info btn-sm openModal"
                                                data-id="<?= $lo['lab_order_id'] ?>"
                                                data-sub='<?= htmlspecialchars(json_encode($subTestsArray), ENT_QUOTES) ?>'
                                                data-old='<?= htmlspecialchars(is_array($lo['result_value']) ? json_encode($lo['result_value']) : $lo['result_value'], ENT_QUOTES) ?>'>
                                                <i class="icon-eye"></i> View Sub Tests
                                            </button>
                                            <?php else: ?>
                                            <input type="text" name="lab_value[]" class="form-control lab-value" 
                                                   value="<?= htmlspecialchars($lo['result_value'] ?? '') ?>" 
                                                   placeholder="Value / Note (readonly)" disabled>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-md-1 d-flex gap-1">
                                            <?php if (!$isVisitClosed): ?>
                                            <button type="button" class="btn btn-danger btn-sm remove-lab btn-block"><i class="icon-trash"></i></button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="lab-order-row row mb-1 align-items-center">
                                    <div class="col-md-4">
                                        <select name="lab_test_id[]" class="form-control lab-select" <?= $disabled ?>>
                                            <option value="">Select Lab Test</option>
                                            <?php foreach($labProducts as $lp): ?>
                                                <option value="<?= $lp['id'] ?>"><?= htmlspecialchars($lp['name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <input type="text" name="lab_value[]" class="form-control lab-value" placeholder="Value / Note (readonly)" disabled>
                                    </div>
                                    <div class="col-md-4">
                                        <?php if (!$isVisitClosed): ?>
                                        <button type="button" class="btn btn-danger remove-lab btn-block"><i class="icon-trash"></i></button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    
                        <!-- Template -->
                        <template id="lab-row-template">
                            <div class="lab-order-row row mb-1 align-items-center">
                                <div class="col-md-3">
                                    <select name="lab_test_id[]" class="form-control lab-select">
                                        <option value="">Select Lab Test</option>
                                        <?php foreach($labProducts as $lp): ?>
                                            <option value="<?= $lp['id'] ?>"><?= htmlspecialchars($lp['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-8">
                                    <input type="text" name="lab_value[]" class="form-control lab-value" placeholder="Value / Note (readonly)" disabled>
                                </div>
                                <div class="col-md-1">
                                    <button type="button" class="btn btn-danger remove-lab btn-block"><i class="icon-trash text-center"></i></button>
                                </div>
                            </div>
                        </template>
                        
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <button type="button" class="btn btn-primary btn-sm" id="addLabBtn">
                                <i class="icon-plus"></i> Add Lab Order
                            </button>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('lab_orders') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Lab Orders
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>
                    
                <!-- Sub-tests Modal -->
                <div class="modal fade" id="labModal" tabindex="-1" role="dialog">
                  <div class="modal-dialog modal-md" role="document">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title">Sub Lab Tests</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                      </div>
                      <div class="modal-body">
                        <input type="hidden" id="currentLab">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Test</th>
                                    <th>Min</th>
                                    <th>Max</th>
                                    <th>Unit</th>
                                    <th>Result</th>
                                </tr>
                            </thead>
                            <tbody id="modalBody"></tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- ================= IMAGING REPORTS ================= -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="imaging_reports">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Imaging Reports (U/S, X-Ray, etc.)</h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="imaging_reports">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body" id="imaging-container">
                            <?php
                            $imagingReports = json_decode($ticket['imaging_reports'] ?? '[]', true) ?: [];
                            $types = ['Obstetrical','Abdominal','Pelvic','Abdo pelvic','Pelvic U/S','U/S Control','Other (Specify)'];
                            foreach($imagingReports as $ir):
                            ?>
                            <div class="imaging-row row mb-1 align-items-center">
                                <div class="col-md-3">
                                    <select name="imaging_type[]" class="form-control" <?= $disabled ?>>
                                        <option value="">Select Type</option>
                                        <?php foreach($types as $type): ?>
                                        <option value="<?= $type ?>" <?= ($ir['type'] ?? '') == $type ? 'selected' : '' ?>><?= $type ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <textarea name="imaging_report[]" class="form-control" placeholder="Imaging Report" <?= $disabled ?>><?= htmlspecialchars($ir['report'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-4">
                                    <textarea name="imaging_recommendation[]" class="form-control" placeholder="Recommendation" <?= $disabled ?>><?= htmlspecialchars($ir['recommendation'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-1 text-center">
                                    <?php if (!$isVisitClosed): ?>
                                    <button type="button" class="btn btn-danger btn-sm remove-imaging"><i class="icon-trash"></i></button>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    
                        <template id="imaging-row-template">
                            <div class="imaging-row row mb-1 align-items-center">
                                <div class="col-md-3">
                                    <select name="imaging_type[]" class="form-control">
                                        <option value="">Select Type</option>
                                        <?php foreach($types as $type): ?>
                                        <option value="<?= $type ?>"><?= $type ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <textarea name="imaging_report[]" class="form-control" placeholder="Imaging Report"></textarea>
                                </div>
                                <div class="col-md-4">
                                    <textarea name="imaging_recommendation[]" class="form-control" placeholder="Recommendation"></textarea>
                                </div>
                                <div class="col-md-1 text-center">
                                    <button type="button" class="btn btn-danger btn-sm remove-imaging"><i class="icon-trash"></i></button>
                                </div>
                            </div>
                        </template>
                        
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <button type="button" class="btn btn-primary btn-sm" id="addImagingBtn">
                                <i class="icon-plus"></i> Add Imaging Report
                            </button>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('imaging_reports') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Imaging Reports
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>
                
                <!-- ================= FINAL DIAGNOSES ================= -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="final_diagnoses">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Final Diagnoses (Referral, RDV, Health Education) <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="final_diagnoses">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body" id="diagnosis-container">
                            <?php
                                $diagnoses = json_decode($ticket['final_diagnosis_title'] ?? '[]', true) ?: [''];
                                $codes = json_decode($ticket['final_diagnosis_code'] ?? '[]', true) ?: [''];
                                $comments = json_decode($ticket['final_diagnosis_comment'] ?? '[]', true) ?: [''];
                                for ($i = 0; $i < count($diagnoses); $i++):
                            ?>
                                <div class="diagnosis-row row mb-1 align-items-center">
                                    <div class="col-md-4">
                                        <input type="text" name="final_diagnosis_title[]" class="form-control required-field" 
                                               value="<?= htmlspecialchars($diagnoses[$i] ?? '') ?>" placeholder="Diagnosis Title (Required)" <?= $disabled ?> required>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" name="final_diagnosis_code[]" class="form-control" 
                                               value="<?= htmlspecialchars($codes[$i] ?? '') ?>" placeholder="ICD-11 Code" <?= $disabled ?>>
                                    </div>
                                    <div class="col-md-4">
                                        <textarea name="final_diagnosis_comment[]" class="form-control" placeholder="Comments (Referral, RDV, Health Education)" <?= $disabled ?>><?= htmlspecialchars($comments[$i] ?? '') ?></textarea>
                                    </div>
                                    <div class="col-md-1 text-center">
                                        <?php if (!$isVisitClosed): ?>
                                        <button type="button" class="btn btn-danger btn-sm remove-diagnosis">
                                            <i class="icon-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endfor; ?>
                        </div>

                        <template id="diagnosis-row-template">
                            <div class="diagnosis-row row mb-1 align-items-center">
                                <div class="col-md-4">
                                    <input type="text" name="final_diagnosis_title[]" class="form-control required-field" placeholder="Diagnosis Title (Required)" required>
                                </div>
                                <div class="col-md-3">
                                    <input type="text" name="final_diagnosis_code[]" class="form-control" placeholder="ICD-11 Code">
                                </div>
                                <div class="col-md-4">
                                    <textarea name="final_diagnosis_comment[]" class="form-control" placeholder="Comments (Referral, RDV, Health Education)"></textarea>
                                </div>
                                <div class="col-md-1 text-center">
                                    <button type="button" class="btn btn-danger btn-sm remove-diagnosis">
                                        <i class="icon-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </template>
                        
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <button type="button" class="btn btn-primary btn-sm" id="addDiagnosisBtn">
                                <i class="icon-plus"></i> Add Diagnosis
                            </button>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('final_diagnoses') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Final Diagnoses
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Other Management -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="other_management">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Other Management <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="other_management">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body">
                            <textarea rows="5" class="form-control required-field" name="other_management" <?= $disabled ?> required><?= htmlspecialchars((string)($ticket['other_management'] ?? '')) ?></textarea>
                        </div>
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <div>
                                <!-- No add button for this section -->
                            </div>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('other_management') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save Other Management
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- HMIS Report -->
                <form action="" method="POST" class="section-form">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                    <input type="hidden" name="section" value="hmis_report">
                    
                    <div class="card mt-2">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h4 class="card-title">HMIS Report <span class="text-danger">*</span></h4>
                            <button type="button" class="btn btn-info btn-sm history-btn" data-section="hmis_report">
                                <i class="icon-history"></i> History
                            </button>
                        </div>
                        <div class="card-body" id="hmis-container">
                            <?php if (!empty($hmis_report)): ?>
                                <?php foreach ($hmis_report as $indicator_id): ?>
                                    <div class="hmis-row row mb-1 align-items-center">
                                        <div class="col-md-10">
                                            <select name="hmis_report[]" class="form-control hmis-select required-field" <?= $disabled ?> required>
                                                <option value="">Select HMIS Indicators</option>
                                                <?php foreach ($grouped_hmis as $catName => $indicators): ?>
                                                    <optgroup label="<?= htmlspecialchars($catName) ?>">
                                                        <?php foreach ($indicators as $h): ?>
                                                            <option value="<?= $h['id'] ?>"
                                                                <?= ($indicator_id == $h['id']) ? 'selected' : '' ?>>
                                                                <?= htmlspecialchars($h['indicator_name']) ?>
                                                                <?= !empty($h['description']) ? ' - ' . htmlspecialchars($h['description']) : '' ?>
                                                                (Gender: <?= $h['gender'] ?? 'Any' ?>, 
                                                                 Min: <?= $h['min_years'] ?>y, 
                                                                 Max: <?= $h['max_years'] ?>y)
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </optgroup>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2 text-center">
                                            <?php if (!$isVisitClosed): ?>
                                            <button type="button" class="btn btn-danger btn-sm remove-hmis">
                                                <i class="icon-trash"></i>
                                            </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="hmis-row row mb-1 align-items-center">
                                    <div class="col-md-10">
                                        <select name="hmis_report[]" class="form-control hmis-select required-field" <?= $disabled ?> required>
                                            <option value="">Select HMIS Indicators</option>
                                            <?php foreach ($grouped_hmis as $catName => $indicators): ?>
                                                <optgroup label="<?= htmlspecialchars($catName) ?>">
                                                    <?php foreach ($indicators as $h): ?>
                                                        <option value="<?= $h['id'] ?>">
                                                            <?= htmlspecialchars($h['indicator_name']) ?>
                                                            <?= !empty($h['description']) ? ' - ' . htmlspecialchars($h['description']) : '' ?>
                                                            (Gender: <?= $h['gender'] ?? 'Any' ?>, 
                                                             Min: <?= $h['min_years'] ?>y, 
                                                             Max: <?= $h['max_years'] ?>y)
                                                        </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2 text-center">
                                        <?php if (!$isVisitClosed): ?>
                                        <button type="button" class="btn btn-danger btn-sm remove-hmis">
                                            <i class="icon-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Template for adding new rows dynamically -->
                        <template id="hmis-row-template">
                            <div class="hmis-row row mb-1 align-items-center">
                                <div class="col-md-10">
                                    <select name="hmis_report[]" class="form-control hmis-select required-field" required>
                                        <option value="">Select HMIS Indicators</option>
                                        <?php foreach ($grouped_hmis as $catName => $indicators): ?>
                                            <optgroup label="<?= htmlspecialchars($catName) ?>">
                                                <?php foreach ($indicators as $h): ?>
                                                    <option value="<?= $h['id'] ?>">
                                                        <?= htmlspecialchars($h['indicator_name']) ?>
                                                        <?= !empty($h['description']) ? ' - ' . htmlspecialchars($h['description']) : '' ?>
                                                        (Gender: <?= $h['gender'] ?? 'Any' ?>, 
                                                         Min: <?= $h['min_years'] ?>y, 
                                                         Max: <?= $h['max_years'] ?>y)
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 text-center">
                                    <button type="button" class="btn btn-danger btn-sm remove-hmis">
                                        <i class="icon-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </template>
                        
                        <?php if (!$isVisitClosed): ?>
                        <div class="card-footer d-flex justify-content-between align-items-center">
                            <button type="button" class="btn btn-primary btn-sm" id="addHMISBtn">
                                <i class="icon-plus"></i> Add HMIS Indicators
                            </button>
                            <div class="text-right">
                                <div class="mb-1 recent-updates-container">
                                    <?= getRecentUpdates('hmis_report') ?>
                                </div>
                                <button type="submit" name="save_section" class="btn btn-success btn-sm">
                                    <i class="icon-save"></i> Save HMIS Report
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </form>

                <!-- Print & Discharge Buttons -->
                <?php if (!$isVisitClosed): ?>
                <div class="card mt-2">
                    <div class="card-footer text-center">
                        <button type="button" class="btn btn-success btn-md" id="printTicketBtn">
                            <i class="icon-printer"></i> Print Ticket
                        </button>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
                            <input type="hidden" name="visit_id" value="<?= $visit_id ?>">
                            <button type="submit" name="discharge_patient" class="btn btn-primary btn-md" id="dischargeBtn" disabled onclick="return confirm('Are you sure you want to discharge this patient? This will mark treatment as completed but keep the visit open.')">
                                <i class="icon-log-out"></i> Discharge Patient
                            </button>
                        </form>
                    </div>
                </div>
                <?php else: ?>
                <div class="card mt-2">
                    <div class="card-body text-center">
                        <div class="alert alert-warning">
                            <strong>Visit Closed</strong> - Editing Disabled
                        </div>
                        <button type="button" class="btn btn-success btn-md" id="printTicketBtn">
                            <i class="icon-printer"></i> Print Ticket
                        </button>
                    </div>
                </div>
                <?php endif; ?>

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

<?php include('includes/footer.php'); ?>

<style>
.card-body p { margin-bottom: 6px; font-size: 14px; }
.card { border-radius: 6px; }
.card-header { padding: 10px 15px; }
.toast-message { position: fixed; top: 20px; right: 20px; padding: 12px 20px; color: #fff; border-radius: 5px; z-index: 9999; box-shadow: 0 2px 8px rgba(0,0,0,0.2); font-size: 14px; }
.table thead th { vertical-align: middle; }
.section-form { margin-bottom: 15px; }
.card-footer { background-color: #f8f9fa; border-top: 1px solid #e9ecef; padding: 10px 15px; }
.history-btn { margin-left: auto; }
.recent-updates-container {
    max-height: 80px;
    overflow-y: auto;
    font-size: 11px;
    background: #f8f9fa;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #e9ecef;
    margin-bottom: 5px;
}
.recent-updates .update-item {
    padding: 2px 0;
    border-bottom: 1px dashed #eee;
}
.recent-updates .update-item:last-child {
    border-bottom: none;
}
.recent-updates .badge {
    font-size: 9px;
    padding: 1px 4px;
    margin-right: 3px;
}
.admit-btn-container {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #eee;
}
#admitToHospitalBtn {
    background: linear-gradient(to right, #ff8a00, #da1b60);
    border: none;
    color: white;
    font-weight: bold;
}
#admitToHospitalBtn:hover {
    background: linear-gradient(to right, #da1b60, #ff8a00);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.icon-loader.spinner {
    animation: spin 1s linear infinite;
    display: inline-block;
}
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
#dischargeBtn:disabled {
    cursor: not-allowed;
    opacity: 0.6;
}
#dischargeBtn.btn-primary {
    background: linear-gradient(to right, #007bff, #0056b3);
    border-color: #0056b3;
}
#dischargeBtn.btn-secondary {
    background: linear-gradient(to right, #6c757d, #545b62);
    border-color: #545b62;
}
.required-field:invalid {
    border-color: #dc3545;
}
.required-field:valid {
    border-color: #28a745;
}
.text-danger {
    color: #dc3545 !important;
    font-weight: bold;
}
</style>

<script>
$(document).ready(function(){
    // Print functionality
    $('#printTicketBtn').click(function(){
        // Clone the main content
        const formContent = document.querySelector('.app-content.content').cloneNode(true);

        // Replace all inputs, textareas, and selects with plain text
        formContent.querySelectorAll('input, textarea, select').forEach(el => {
            let value = '';
            if(el.tagName.toLowerCase() === 'select'){
                value = el.options[el.selectedIndex]?.text || '';
            } else {
                value = el.value || '';
            }

            const span = document.createElement('span');
            span.textContent = value;

            // Replace the input/textarea/select with the span
            el.parentNode.replaceChild(span, el);
        });

        // Remove buttons and form elements
        formContent.querySelectorAll('button, .card-footer, .section-form').forEach(el => el.remove());

        // Open print window
        const printWindow = window.open('', '', 'height=800,width=1200');
        printWindow.document.write('<html><head><title>Patient Ticket</title>');
        printWindow.document.write('<link rel="stylesheet" href="path_to_your_css/bootstrap.min.css">'); // optional
        printWindow.document.write('<style>span { display:block; margin-bottom:5px; }</style>'); // spacing
        printWindow.document.write('</head><body>');
        printWindow.document.write(formContent.innerHTML);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
        printWindow.close();
    });

    // =================== Lab Orders ===================
    $('#addLabBtn').click(function(){
        const clone = $('#lab-row-template')[0].content.cloneNode(true);
        $('#lab-orders-container').append(clone);
        if($.fn.select2) $('#lab-orders-container .lab-select').last().select2({width:'100%'});
        updateLabDisabledOptions();
    });

    $(document).on('click','.remove-lab', function(){
        $(this).closest('.lab-order-row').remove();
        updateLabDisabledOptions();
    });

    // =================== Disable already-added lab orders ===================
    function updateLabDisabledOptions(){
        let selected = [];
        $('.lab-select').each(function(){
            if($(this).val()) selected.push($(this).val());
        });

        $('.lab-select').each(function(){
            let current = $(this).val();
            $(this).find('option').each(function(){
                if(!$(this).val()) return;
                $(this).prop(
                    'disabled',
                    $(this).val() !== current && selected.includes($(this).val())
                );
            });
        });
    }
    $(document).on('change','.lab-select', updateLabDisabledOptions);

    // =================== Sub-test VIEW MODAL ===================
    $(document).on('click','.openModal', function(){
        const labId = $(this).data('id');
        const subs  = $(this).data('sub') || [];
        const old   = $(this).data('old') || {};

        $('#currentLab').val(labId);

        let html = '';
        subs.forEach(s => {
            let val = (old[s.name] !== undefined && old[s.name] !== null)
                        ? String(old[s.name])   // ✅ show ANY value (text, number, symbol)
                        : '';

            html += `<tr>
                <td>${s.name}</td>
                <td>${s.min ?? ''}</td>
                <td>${s.max ?? ''}</td>
                <td>${s.unit || ''}</td>
                <td>
                    <input type="text"
                           class="form-control form-control-sm res"
                           data-name="${s.name}"
                           data-min="${s.min}"
                           data-max="${s.max}"
                           value="${val.replace(/"/g,'&quot;')}"
                           disabled>
                </td>
            </tr>`;
        });

        $('#modalBody').html(html);
        $('#labModal').modal('show');
        colorize();
    });

    // =================== COLORIZE (NUMBERS ONLY) ===================
    function isPureNumber(val){
        return /^-?\d+(\.\d+)?$/.test(val);
    }

    function colorize(){
        document.querySelectorAll('.res').forEach(i => {
            let val = i.value.trim();
            let min = parseFloat(i.dataset.min);
            let max = parseFloat(i.dataset.max);

            // Reset always
            i.style.background = '';

            // Empty → no color
            if(val === '') return;

            // ❗ Only colorize PURE numbers
            if(isPureNumber(val) && !isNaN(min) && !isNaN(max)){
                let v = parseFloat(val);
                i.style.background = (v >= min && v <= max)
                    ? '#d4edda'   // normal
                    : '#f8d7da';  // abnormal
            }
            // Text / symbols → NO color (but still displayed)
        });
    }

    // =================== Imaging Reports ===================
    $('#addImagingBtn').click(function(){
        const clone = $('#imaging-row-template')[0].content.cloneNode(true);
        $('#imaging-container').append(clone);
    });
    $(document).on('click','.remove-imaging', function(){
        $(this).closest('.imaging-row').remove();
    });

    // =================== Diagnoses ===================
    $('#addDiagnosisBtn').click(function(){
        const clone = $('#diagnosis-row-template')[0].content.cloneNode(true);
        $('#diagnosis-container').append(clone);
    });
    $(document).on('click','.remove-diagnosis', function(){ 
        $(this).closest('.diagnosis-row').remove(); 
    });

    // =================== HMIS Reports ===================
    $('#addHMISBtn').click(function(){
        const clone = $('#hmis-row-template')[0].content.cloneNode(true);
        $('#hmis-container').append(clone);
        if($.fn.select2) $('#hmis-container .hmis-select').last().select2({width:'100%'});
    });
    $(document).on('click','.remove-hmis', function(){ 
        $(this).closest('.hmis-row').remove(); 
    });

    // =================== History Modals ===================
    $(document).on('click', '.history-btn', function() {
        const section = $(this).data('section');
        const sectionNames = {
            'catchment': 'Catchment Area / New Case',
            'vital_signs': 'Vital Signs',
            'chief_complaints': 'Chief Complaints',
            'physical_examination': 'Physical Examination',
            'differential_diagnosis': 'Differential Diagnosis',
            'lab_orders': 'Lab Orders',
            'imaging_reports': 'Imaging Reports',
            'final_diagnoses': 'Final Diagnoses',
            'other_management': 'Other Management',
            'hmis_report': 'HMIS Report'
        };
        
        // Create modal HTML
        const modalId = 'historyModal-' + section;
        const modalHtml = `
            <div class="modal fade" id="${modalId}" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${sectionNames[section]} - History</h5>
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                        </div>
                        <div class="modal-body">
                            <div class="text-center">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="sr-only">Loading...</span>
                                </div>
                                <p>Loading history...</p>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing modal if any
        $('#' + modalId).remove();
        
        // Add modal to container
        $('#historyModals').append(modalHtml);
        
        // Show modal
        $('#' + modalId).modal('show');
        
        // Load history data
        loadHistory(section, modalId);
    });
    
    function loadHistory(section, modalId) {
        $.ajax({
            url: 'get_section_history.php',
            type: 'GET',
            data: {
                visit_id: <?= $visit_id ?>,
                section: section
            },
            success: function(response) {
                $('#' + modalId + ' .modal-body').html(response);
            },
            error: function() {
                $('#' + modalId + ' .modal-body').html(
                    '<div class="alert alert-danger">Error loading history. Please try again.</div>'
                );
            }
        });
    }

    // =================== Admit to Hospital ===================
    $('#admitToHospitalBtn').click(function() {
        // Confirm before admitting
        if (!confirm('Are you sure you want to admit this patient to the hospital?')) {
            return;
        }
        
        // Create form data
        const formData = new FormData();
        formData.append('csrf_token', '<?= htmlspecialchars($csrf) ?>');
        formData.append('visit_id', '<?= $visit_id ?>');
        formData.append('action', 'admit_to_hospital');
        
        // Show loading state
        const btn = $(this);
        const originalText = btn.html();
        btn.prop('disabled', true).html('<i class="icon-loader spinner"></i> Processing...');
        
        // Send AJAX request
        $.ajax({
            url: 'visit_ticket_action.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.success) {
                        // Show success message
                        showToast(result.message, '#28a745');
                        
                        // Optional: Redirect or update UI
                        if (result.redirect) {
                            setTimeout(() => {
                                window.location.href = result.redirect;
                            }, 1500);
                        }
                    } else {
                        showToast(result.message || 'Admission failed', '#dc3545');
                        btn.prop('disabled', false).html(originalText);
                    }
                } catch (e) {
                    showToast('Error processing response', '#dc3545');
                    btn.prop('disabled', false).html(originalText);
                }
            },
            error: function() {
                showToast('Network error. Please try again.', '#dc3545');
                btn.prop('disabled', false).html(originalText);
            }
        });
    });

    // REMOVED AJAX discharge functionality - now handled by pure PHP form submission

    // Function to check if all required fields are filled
    function checkRequiredFields() {
        let allFilled = true;
        let missingFields = [];
        
        // Check Catchment Area
        if (!$('select[name="catchment_area"]').val()) {
            allFilled = false;
            missingFields.push('Catchment Area');
        }
        
        // Check New Case
        if (!$('select[name="new_case"]').val()) {
            allFilled = false;
            missingFields.push('New Case');
        }
        
        // Check Temperature (required in Vital Signs)
        if (!$('input[name="temperature"]').val()) {
            allFilled = false;
            missingFields.push('Temperature');
        }
        
        // Check Weight (required in Vital Signs)
        if (!$('input[name="weight"]').val()) {
            allFilled = false;
            missingFields.push('Weight');
        }
        
        // Check Chief Complaints
        if (!$('textarea[name="chief_complaints"]').val().trim()) {
            allFilled = false;
            missingFields.push('Chief Complaints');
        }
        
        // Check Physical Examination
        if (!$('textarea[name="physical_examination"]').val().trim()) {
            allFilled = false;
            missingFields.push('Physical Examination');
        }
        
        // Check Differential Diagnosis
        if (!$('textarea[name="differential_diagnosis"]').val().trim()) {
            allFilled = false;
            missingFields.push('Differential Diagnosis');
        }
        
        // Check Other Management
        if (!$('textarea[name="other_management"]').val().trim()) {
            allFilled = false;
            missingFields.push('Other Management');
        }
        
        // Check Final Diagnoses - at least one diagnosis title
        let hasDiagnosis = false;
        $('input[name="final_diagnosis_title[]"]').each(function() {
            if ($(this).val().trim()) {
                hasDiagnosis = true;
                return false; // Break the loop
            }
        });
        if (!hasDiagnosis) {
            allFilled = false;
            missingFields.push('Final Diagnoses (at least one)');
        }
        
        // Check HMIS Report - at least one HMIS indicator
        let hasHMIS = false;
        $('select[name="hmis_report[]"]').each(function() {
            if ($(this).val()) {
                hasHMIS = true;
                return false; // Break the loop
            }
        });
        if (!hasHMIS) {
            allFilled = false;
            missingFields.push('HMIS Report (at least one)');
        }
        
        // Enable/Disable discharge button
        $('#dischargeBtn').prop('disabled', !allFilled);
        
        // Add visual feedback
        if (allFilled) {
            $('#dischargeBtn').removeClass('btn-secondary').addClass('btn-primary');
            $('#dischargeBtn').attr('title', 'All required fields are filled');
        } else {
            $('#dischargeBtn').removeClass('btn-primary').addClass('btn-secondary');
            $('#dischargeBtn').attr('title', 'Missing: ' + missingFields.join(', '));
        }
        
        return allFilled;
    }

    // Check fields on page load
    checkRequiredFields();
    
    // Check fields on change
    $(document).on('change input', 'select, input, textarea', function() {
        checkRequiredFields();
    });
    
    // Also check when lab orders are added/removed
    $(document).on('click', '.remove-lab, #addLabBtn', function() {
        setTimeout(checkRequiredFields, 100);
    });
    
    // Check when diagnoses are added/removed
    $(document).on('click', '.remove-diagnosis, #addDiagnosisBtn', function() {
        setTimeout(checkRequiredFields, 100);
    });
    
    // Check when HMIS reports are added/removed
    $(document).on('click', '.remove-hmis, #addHMISBtn', function() {
        setTimeout(checkRequiredFields, 100);
    });

    // =================== Initialize Select2 ===================
    if($.fn.select2) $('.doctor-select, .lab-select, .hmis-select').select2({width:'100%'});

    // =================== Toast ===================
    <?php if(isset($_SESSION['flash'])): ?>
    const message = '<?= addslashes($_SESSION['flash']['message']) ?>';
    const color = '<?= $_SESSION['flash']['color'] ?>';
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = color;
    toast.innerText = message;
    document.body.appendChild(toast);
    setTimeout(()=>toast.remove(),4000);
    <?php unset($_SESSION['flash']); endif; ?>
});

// Helper function to show toast messages
function showToast(message, color) {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = color;
    toast.innerHTML = `<i class="icon-info"></i> ${message}`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}
</script>