<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include('includes/db.php');
include('includes/header.php');

/* ================= CSRF ================= */
if(empty($_SESSION['csrf_token'])){
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

/* ================= Auto Logout ================= */
$timeout_duration = 43200;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}

/* ================= HELPER ================= */
function calculate_age($dob) {
    if (!$dob || $dob === '0000-00-00') {
        return '';
    }
    try {
        $dobDate = new DateTime($dob);
        $now     = new DateTime();
        $diff    = $now->diff($dobDate);
        if ($diff->y >= 1) {
            return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
        }
        if ($diff->m >= 1) {
            return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
        }
        return $diff->d . ' Day' . ($diff->d > 1 ? 's' : '');
    } catch (Exception $e) {
        return '';
    }
}

/* ================= Logged in user + facility ================= */
$user_id = $_SESSION['user_id'] ?? 0;
if(!$user_id) die("User not logged in");

$stmtUser = $pdo->prepare("SELECT username, facility_id FROM users WHERE id=?");
$stmtUser->execute([$user_id]);
$user = $stmtUser->fetch(PDO::FETCH_ASSOC);

$facility_id = $user['facility_id'] ?? 0;
$stmtFac = $pdo->prepare("SELECT * FROM facility WHERE id=?");
$stmtFac->execute([$facility_id]);
$facility = $stmtFac->fetch(PDO::FETCH_ASSOC);

/* ================= GET PARAMETERS ================= */
$patient_id = intval($_GET['patient_id'] ?? 0);
$visit_id = intval($_GET['visit_id'] ?? 0);
$ticket_id = intval($_GET['ticket_id'] ?? 0);

if($patient_id <= 0 || $visit_id <= 0 || $ticket_id <= 0) {
    $_SESSION['flash'] = ['message' => 'Required parameters missing!', 'color' => '#dc3545'];
    header("Location: patient_visits.php");
    exit();
}

/* ================= PATIENT DETAILS ================= */
// UPDATED: Using chief_complaints instead of reason
$stmt = $pdo->prepare("
    SELECT p.*, vt.visit_date, vt.chief_complaints, 
           vt.visit_number, vt.final_diagnosis_title,
           u.username as doctor_name,
           vt.systolic, vt.diastolic, vt.heart_rate, vt.temperature,
           vt.resp_rate, vt.spo2, vt.weight, vt.height
    FROM patients p
    JOIN visit_tickets vt ON vt.patient_id = p.id
    LEFT JOIN visits v ON v.id = vt.visit_id
    LEFT JOIN users u ON u.id = v.treated_by
    WHERE p.id = ? AND vt.id = ?
");
$stmt->execute([$patient_id, $ticket_id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$patient) {
    $_SESSION['flash'] = ['message' => 'Patient not found!', 'color' => '#dc3545'];
    header("Location: patient_visits.php");
    exit();
}

/* ================= CHECK IF ALREADY ADMITTED ================= */
// First check if hospitalizations table exists
$tableExists = $pdo->query("SHOW TABLES LIKE 'hospitalizations'")->fetch();
$already_admitted = null;

if($tableExists) {
    $stmt = $pdo->prepare("
        SELECT h.*, w.ward_name, b.bed_number
        FROM hospitalizations h
        LEFT JOIN wards w ON w.id = h.ward_id
        LEFT JOIN beds b ON b.id = h.bed_id
        WHERE h.patient_id = ? AND h.visit_id = ? 
        AND h.discharge_date IS NULL AND h.status != 'discharged'
    ");
    $stmt->execute([$patient_id, $visit_id]);
    $already_admitted = $stmt->fetch(PDO::FETCH_ASSOC);
}

/* ================= FETCH DOCTORS ================= */
$doctors = $pdo->query("
    SELECT id, username, user_role as specialty 
    FROM users 
    WHERE user_role = 'Doctor' AND status = 'active' 
    ORDER BY username
")->fetchAll(PDO::FETCH_ASSOC);

/* ================= FETCH WARDS ================= */
$wards = [];
$wardsExist = $pdo->query("SHOW TABLES LIKE 'wards'")->fetch();

if($wardsExist) {
    $stmt = $pdo->prepare("
        SELECT w.*, 
               (SELECT COUNT(*) FROM beds b WHERE b.ward_id = w.id AND b.status = 'available') as available_beds
        FROM wards w
        WHERE w.facility_id = ? AND w.status = 'active'
        ORDER BY w.ward_name
    ");
    $stmt->execute([$facility_id]);
    $wards = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $_SESSION['flash'] = ['message' => 'Wards system not configured. Please contact administrator.', 'color' => '#dc3545'];
}

/* ================= HANDLE FORM SUBMISSION ================= */
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admit_patient'])){
    if($already_admitted){
        $_SESSION['flash'] = ['message' => 'Patient already admitted!', 'color' => '#dc3545'];
        header("Location: admit_patient.php?patient_id=".$patient_id."&visit_id=".$visit_id."&ticket_id=".$ticket_id);
        exit();
    }

    if(!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])){
        die("Invalid CSRF");
    }

    try {
        $pdo->beginTransaction();
        
        // Check if required tables exist
        $wardsExist = $pdo->query("SHOW TABLES LIKE 'wards'")->fetch();
        $bedsExist = $pdo->query("SHOW TABLES LIKE 'beds'")->fetch();
        
        if(!$wardsExist || !$bedsExist) {
            throw new Exception("Wards/Beds system not configured. Please setup wards and beds first.");
        }
        
        // Generate hospitalization number
        $hosp_number = 'HOSP-' . date('Ymd') . '-' . str_pad($patient_id, 6, '0', STR_PAD_LEFT);
        
        // Create hospitalizations table if it doesn't exist
        $hospTableExists = $pdo->query("SHOW TABLES LIKE 'hospitalizations'")->fetch();
        if(!$hospTableExists) {
            $pdo->exec("
                CREATE TABLE hospitalizations (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    hospitalization_number VARCHAR(50) UNIQUE,
                    patient_id INT NOT NULL,
                    visit_id INT NOT NULL,
                    ticket_id INT NOT NULL,
                    admission_date DATETIME NOT NULL,
                    discharge_date DATETIME NULL,
                    admitting_doctor_id INT NOT NULL,
                    attending_doctor_id INT NULL,
                    ward_id INT NOT NULL,
                    bed_id INT NOT NULL,
                    bed_number VARCHAR(20),
                    diagnosis TEXT,
                    reason TEXT,
                    initial_condition TEXT,
                    discharge_summary TEXT,
                    discharge_instructions TEXT,
                    status ENUM('admitted', 'discharged', 'transferred', 'cancelled') DEFAULT 'admitted',
                    facility_id INT NOT NULL,
                    created_by INT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_patient (patient_id),
                    INDEX idx_visit (visit_id),
                    INDEX idx_status (status)
                )
            ");
        }
        
        // Insert hospitalization record
        $stmt = $pdo->prepare("
            INSERT INTO hospitalizations 
            (hospitalization_number, patient_id, visit_id, ticket_id, admission_date, 
             admitting_doctor_id, ward_id, bed_id, bed_number, diagnosis, reason, 
             initial_condition, facility_id, created_by, status)
            VALUES (?, ?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, 'admitted')
        ");
        
        $stmt->execute([
            $hosp_number,
            $patient_id,
            $visit_id,
            $ticket_id,
            $_POST['admitting_doctor'],
            $_POST['ward_id'],
            $_POST['bed_id'],
            $_POST['bed_number'],
            $_POST['diagnosis'],
            $_POST['reason'],
            $_POST['initial_condition'],
            $facility_id,
            $user_id
        ]);
        
        $hospitalization_id = $pdo->lastInsertId();
        
        // Update visit status if visits table exists
        $visitsExist = $pdo->query("SHOW TABLES LIKE 'visits'")->fetch();
        if($visitsExist) {
            $stmt = $pdo->prepare("UPDATE visits SET status = 'admitted' WHERE id = ?");
            $stmt->execute([$visit_id]);
        }
        
        // Update bed status
        $stmt = $pdo->prepare("UPDATE beds SET status = 'occupied' WHERE id = ?");
        $stmt->execute([$_POST['bed_id']]);
        
        // Insert hospitalization note if clinical_notes table exists
        $notesExist = $pdo->query("SHOW TABLES LIKE 'clinical_notes'")->fetch();
        if($notesExist && !empty($_POST['initial_condition'])){
            $stmt = $pdo->prepare("
                INSERT INTO clinical_notes 
                (patient_id, visit_id, note_type, note_content, created_by, facility_id)
                VALUES (?, ?, 'admission', ?, ?, ?)
            ");
            $stmt->execute([
                $patient_id,
                $visit_id,
                "Patient admitted to hospital. Diagnosis: " . $_POST['diagnosis'] . ". " . $_POST['initial_condition'],
                $user_id,
                $facility_id
            ]);
        }
        
        $pdo->commit();
        
        $_SESSION['flash'] = ['message' => 'Patient admitted successfully! Hospitalization #: ' . $hosp_number, 'color' => '#28a745'];
        header("Location: hospitalization_details.php?id=".$hospitalization_id);
        exit();
        
    } catch (Exception $e) {
        if($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $_SESSION['flash'] = ['message' => 'Admission failed: ' . $e->getMessage(), 'color' => '#dc3545'];
    }
}
?>

<!-- ================= HTML STRUCTURE ================= -->
<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">
        <div class="content-header row">
            <div class="content-header-left col-md-6 col-xs-12 mb-1">
                <h2 class="content-header-title">
                    <i class="ft-user-plus"></i> Admit Patient to Hospital
                </h2>
            </div>
            <div class="content-header-right breadcrumbs-right breadcrumbs-top col-md-6 col-xs-12">
                <div class="breadcrumb-wrapper col-xs-12">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="patient_visits.php">Patient Visits</a></li>
                        <li class="breadcrumb-item active">Admit Patient</li>
                    </ol>
                </div>
            </div>
        </div>

        <div class="content-body">
            <?php if(isset($_SESSION['flash'])): ?>
            <div class="alert alert-icon-left alert-arrow-left alert-info alert-dismissible mb-2" role="alert">
                <span class="alert-icon"><i class="la la-info"></i></span>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <strong><?php echo $_SESSION['flash']['message']; ?></strong>
            </div>
            <?php unset($_SESSION['flash']); endif; ?>

            <?php if($already_admitted): ?>
            <div class="alert alert-warning alert-dismissible mb-2" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <strong><i class="la la-exclamation-triangle"></i> Patient Already Admitted</strong><br>
                Admission Date: <?= date('d/m/Y H:i', strtotime($already_admitted['admission_date'])) ?><br>
                Ward: <?= $already_admitted['ward_name'] ?> | Bed: <?= $already_admitted['bed_number'] ?>
                <a href="hospitalization_details.php?id=<?= $already_admitted['id'] ?>" class="btn btn-sm btn-info float-right">
                    View Admission Details
                </a>
            </div>
            <?php endif; ?>

            <!-- Patient Information Card -->
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"><i class="ft-user"></i> Patient Information</h4>
                    <a class="heading-elements-toggle"><i class="la la-ellipsis-v font-medium-3"></i></a>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <p><strong>File ID:</strong> <?= htmlspecialchars($patient['file_id']) ?></p>
                        </div>
                        <div class="col-md-3">
                            <p><strong>Patient Name:</strong> <?= htmlspecialchars($patient['first_name'].' '.$patient['last_name']) ?></p>
                        </div>
                        <div class="col-md-2">
                            <p><strong>Age:</strong> <?= calculate_age($patient['d_o_b']) ?></p>
                        </div>
                        <div class="col-md-2">
                            <p><strong>Gender:</strong> <?= htmlspecialchars($patient['gender']) ?></p>
                        </div>
                        <div class="col-md-2">
                            <p><strong>Visit #:</strong> <?= htmlspecialchars($patient['visit_number'] ?? $visit_id) ?></p>
                        </div>
                    </div>
                    
                    <!-- Vital Signs -->
                    <?php if($patient['systolic'] || $patient['diastolic'] || $patient['heart_rate']): ?>
                    <div class="row mt-2">
                        <div class="col-md-12">
                            <h6 class="text-primary"><i class="ft-activity"></i> Recent Vital Signs:</h6>
                            <div class="row">
                                <?php if($patient['systolic'] && $patient['diastolic']): ?>
                                <div class="col-md-2">
                                    <strong>BP:</strong> <?= $patient['systolic'] ?>/<?= $patient['diastolic'] ?> mmHg
                                </div>
                                <?php endif; ?>
                                <?php if($patient['heart_rate']): ?>
                                <div class="col-md-2">
                                    <strong>HR:</strong> <?= $patient['heart_rate'] ?> bpm
                                </div>
                                <?php endif; ?>
                                <?php if($patient['temperature']): ?>
                                <div class="col-md-2">
                                    <strong>Temp:</strong> <?= $patient['temperature'] ?> °C
                                </div>
                                <?php endif; ?>
                                <?php if($patient['resp_rate']): ?>
                                <div class="col-md-2">
                                    <strong>RR:</strong> <?= $patient['resp_rate'] ?> /min
                                </div>
                                <?php endif; ?>
                                <?php if($patient['spo2']): ?>
                                <div class="col-md-2">
                                    <strong>SpO2:</strong> <?= $patient['spo2'] ?>%
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Chief Complaints -->
                    <?php if(!empty($patient['chief_complaints'])): ?>
                    <div class="row mt-2">
                        <div class="col-md-12">
                            <p><strong>Chief Complaints:</strong> <?= htmlspecialchars($patient['chief_complaints']) ?></p>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Final Diagnosis -->
                    <?php if(!empty($patient['final_diagnosis_title'])): ?>
                    <div class="row mt-2">
                        <div class="col-md-12">
                            <p><strong>Final Diagnosis:</strong> <?= htmlspecialchars($patient['final_diagnosis_title']) ?></p>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Doctor -->
                    <?php if(!empty($patient['doctor_name'])): ?>
                    <div class="row mt-2">
                        <div class="col-md-12">
                            <p><strong>Attending Doctor:</strong> <?= htmlspecialchars($patient['doctor_name']) ?></p>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Admission Form -->
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"><i class="ft-file-text"></i> Admission Details</h4>
                    <a class="heading-elements-toggle"><i class="la la-ellipsis-v font-medium-3"></i></a>
                </div>
                <div class="card-body">
                    <?php if(empty($wards)): ?>
                    <div class="alert alert-danger">
                        <i class="la la-exclamation-circle"></i> 
                        <strong>Wards System Not Configured</strong><br>
                        Please contact administrator to setup wards and beds before admitting patients.
                    </div>
                    <?php else: ?>
                    <form method="POST" action="" id="admissionForm">
                        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                        <input type="hidden" name="admit_patient" value="1">
                        <input type="hidden" name="patient_id" value="<?= $patient_id ?>">
                        <input type="hidden" name="visit_id" value="<?= $visit_id ?>">
                        <input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="admitting_doctor" class="label-control">Admitting Doctor *</label>
                                    <select class="form-control" id="admitting_doctor" name="admitting_doctor" required>
                                        <option value="">Select Doctor</option>
                                        <?php foreach($doctors as $doctor): ?>
                                        <option value="<?= $doctor['id'] ?>">
                                            Dr. <?= htmlspecialchars($doctor['username']) ?>
                                            <?= !empty($doctor['specialty']) ? ' ('.htmlspecialchars($doctor['specialty']).')' : '' ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="ward_id" class="label-control">Select Ward/Unit *</label>
                                    <select class="form-control" id="ward_id" name="ward_id" required onchange="loadBeds(this.value)">
                                        <option value="">Select Ward</option>
                                        <?php foreach($wards as $ward): ?>
                                        <option value="<?= $ward['id'] ?>" 
                                                data-beds="<?= $ward['available_beds'] ?>">
                                            <?= htmlspecialchars($ward['ward_name']) ?> 
                                            (<?= htmlspecialchars($ward['ward_type']) ?>)
                                            - Available Beds: <?= $ward['available_beds'] ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <small class="text-muted">Available beds will be shown after selecting a ward</small>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="bed_id" class="label-control">Bed Assignment *</label>
                                    <select class="form-control" id="bed_id" name="bed_id" required disabled>
                                        <option value="">Select Ward First</option>
                                    </select>
                                    <input type="hidden" id="bed_number" name="bed_number">
                                    <small class="text-muted" id="bedInfo"></small>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="diagnosis" class="label-control">Primary Diagnosis *</label>
                                    <textarea class="form-control" id="diagnosis" name="diagnosis" rows="2" required 
                                              placeholder="Enter primary diagnosis for admission..."><?= htmlspecialchars($patient['final_diagnosis_title'] ?? '') ?></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reason" class="label-control">Reason for Admission *</label>
                                    <textarea class="form-control" id="reason" name="reason" rows="2" required 
                                              placeholder="Why is hospitalization required?"><?= htmlspecialchars($patient['chief_complaints'] ?? '') ?></textarea>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="initial_condition" class="label-control">Initial Condition & Notes</label>
                                    <textarea class="form-control" id="initial_condition" name="initial_condition" rows="2" 
                                              placeholder="Patient's condition at admission, vital signs, allergies, etc."></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="consentCheck" required>
                                        <label class="custom-control-label" for="consentCheck">
                                            I confirm that admission is medically necessary and appropriate consent has been obtained from the patient/guardian.
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-actions center">
                            <a href="patient_dashboard.php?patient_id=<?= $patient_id ?>" class="btn btn-warning mr-1">
                                <i class="ft-x"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-primary" id="submitBtn" <?= $already_admitted ? 'disabled' : '' ?>>
                                <i class="ft-user-plus"></i> Admit Patient
                            </button>
                        </div>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- JavaScript Section -->
<script>
function loadBeds(wardId) {
    if (!wardId) {
        document.getElementById('bed_id').innerHTML = '<option value="">Select Ward First</option>';
        document.getElementById('bed_id').disabled = true;
        document.getElementById('bedInfo').textContent = '';
        return;
    }

    fetch('ajax/get_beds.php?ward_id=' + wardId)
        .then(response => response.json())
        .then(data => {
            const bedSelect = document.getElementById('bed_id');
            const bedInfo = document.getElementById('bedInfo');
            
            bedSelect.innerHTML = '<option value="">Select Bed</option>';
            
            if (data.error) {
                bedSelect.innerHTML = '<option value="">Error loading beds</option>';
                bedSelect.disabled = true;
                bedInfo.textContent = data.error;
                bedInfo.style.color = 'red';
            } else if (data.length === 0) {
                bedSelect.innerHTML = '<option value="">No available beds in this ward</option>';
                bedSelect.disabled = true;
                bedInfo.textContent = 'No available beds';
                bedInfo.style.color = 'red';
            } else {
                data.forEach(bed => {
                    const option = document.createElement('option');
                    option.value = bed.id;
                    option.textContent = `Bed ${bed.bed_number} - ${bed.bed_type} (${bed.status})`;
                    option.dataset.bedNumber = bed.bed_number;
                    bedSelect.appendChild(option);
                });
                bedSelect.disabled = false;
                bedInfo.textContent = `${data.length} bed(s) available`;
                bedInfo.style.color = 'green';
            }
        })
        .catch(error => {
            console.error('Error loading beds:', error);
            document.getElementById('bedInfo').textContent = 'Error loading beds. Please try again.';
            document.getElementById('bedInfo').style.color = 'red';
        });
}

// Update bed number when bed is selected
document.getElementById('bed_id')?.addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    document.getElementById('bed_number').value = selectedOption.dataset.bedNumber || '';
});

// Form validation
document.getElementById('admissionForm')?.addEventListener('submit', function(e) {
    const consentCheck = document.getElementById('consentCheck');
    if (!consentCheck?.checked) {
        e.preventDefault();
        alert('Please confirm that admission is medically necessary and consent has been obtained.');
        consentCheck.focus();
        return false;
    }
    
    const bedSelect = document.getElementById('bed_id');
    if (bedSelect?.disabled || !bedSelect?.value) {
        e.preventDefault();
        alert('Please select an available bed.');
        bedSelect.focus();
        return false;
    }
});

// Auto-fill form from localStorage
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('admissionForm');
    if(!form) return;
    
    const formData = localStorage.getItem('admission_form_data');
    
    if (formData) {
        const data = JSON.parse(formData);
        Object.keys(data).forEach(key => {
            const element = form.querySelector(`[name="${key}"]`);
            if (element) {
                if (element.type === 'checkbox') {
                    element.checked = data[key];
                } else {
                    element.value = data[key];
                }
            }
        });
        
        // Trigger change event for ward to load beds
        const wardSelect = document.getElementById('ward_id');
        if (wardSelect && wardSelect.value) {
            loadBeds(wardSelect.value);
        }
    }
    
    // Save form data on change
    form.addEventListener('change', function() {
        const formData = new FormData(form);
        const data = {};
        formData.forEach((value, key) => {
            data[key] = value;
        });
        localStorage.setItem('admission_form_data', JSON.stringify(data));
    });
    
    // Clear localStorage on successful submit
    form.addEventListener('submit', function() {
        localStorage.removeItem('admission_form_data');
    });
});
</script>

<style>
.card {
    margin-bottom: 20px;
}
.form-control:disabled {
    background-color: #e9ecef;
    opacity: 1;
}
.input-group-text {
    background-color: transparent;
    border-right: none;
}
.input-group .form-control {
    border-left: none;
}
#bedInfo {
    font-size: 12px;
    display: block;
    margin-top: 5px;
}
.custom-checkbox .custom-control-label::before {
    border-radius: 3px;
}
.custom-checkbox .custom-control-input:checked~.custom-control-label::before {
    background-color: #28a745;
    border-color: #28a745;
}
</style>

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