<?php
// includes/layout/footer.php
?>
    </div>
</div>

<!-- Book Appointment Modal -->
<div class="modal fade" id="bookAppointmentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER["PHP_SELF"]; ?>?section=<?php echo $section; ?>" method="POST">
            <input type="hidden" name="action" value="book_appointment">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __("book_appointment"); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("patient"); ?></label>
                        <select name="patient_id" class="form-select select2-modal" required>
                            <option value=""><?php echo __("select"); ?>...</option>
                            <?php foreach ($all_patients as $p): ?>
                            <option value="<?php echo $p["id"]; ?>"><?php echo sprintf('%06d', $p['id']) . ' - ' . htmlspecialchars($p['name']) . (!empty($p['phone']) ? ' - ' . htmlspecialchars($p['phone']) : ''); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("doctor"); ?></label>
                        <select name="doctor_id" class="form-select select2-modal" required>
                            <option value=""><?php echo __("select"); ?>...</option>
                            <?php foreach ($all_doctors as $d): ?>
                            <option value="<?php echo $d["id"]; ?>"><?php echo htmlspecialchars($d["name"]); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("date"); ?> & <?php echo __("time"); ?></label>
                        <input type="datetime-local" name="date" class="form-control" required value="<?php echo date("Y-m-d\TH:i"); ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("reason"); ?></label>
                        <textarea name="reason" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __("cancel"); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __("book"); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>


<!-- Import Patients Modal -->
<div class="modal fade" id="importPatientsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="includes/actions.php" enctype="multipart/form-data">
            <input type="hidden" name="action" value="import_patients">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title"><i class="bi bi-file-earmark-excel me-2"></i> <?php echo __("import_excel"); ?></h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __("select_file"); ?></label>
                        <input type="file" name="file" class="form-control" accept=".csv,.xls,.xlsx" required>
                        <div class="form-text mt-2 text-muted">
                            <i class="bi bi-info-circle me-1"></i> <?php echo __("excel_format_info"); ?>
                        </div>
                    </div>
                    <div class="mt-3 text-center">
                        <a href="download_patient_template.php" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-download me-1"></i> <?php echo __("download_sample_template") ?? "Download Sample Template"; ?>
                        </a>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __("cancel"); ?></button>
                    <button type="submit" class="btn btn-success px-4"><?php echo __("import"); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add Patient Modal -->
<div class="modal fade" id="addPatientModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="add_patient">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_patient'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('name'); ?></label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('civil_id'); ?></label>
                            <input type="text" name="civil_id" class="form-control">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('nationality'); ?></label>
                            <select name="nationality" class="form-select select2-modal">
                                <option value=""><?php echo __('search'); ?>...</option>
                                <?php foreach ($all_countries as $c): ?>
                                <option value="<?php echo htmlspecialchars($c); ?>" <?php echo $c === 'Oman' ? 'selected' : ''; ?>><?php echo htmlspecialchars($c); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="phone" class="form-control" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label"><?php echo __('dob'); ?></label>
                            <input type="text" name="dob" id="add_patient_dob" class="form-control masked-date" placeholder="YYYY-MM-DD" data-inputmask-alias="datetime" data-inputmask-inputformat="yyyy-mm-dd">
                        </div>
                        <div class="col-md-2 mb-3">
                            <label class="form-label"><?php echo __('age'); ?></label>
                            <input type="number" id="add_patient_age" class="form-control" placeholder="<?php echo __('age'); ?>" min="0" max="150">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('gender'); ?></label>
                            <select name="gender" class="form-select">
                                <option value="Male"><?php echo __('male'); ?></option>
                                <option value="Female"><?php echo __('female'); ?></option>
                                <option value="Other"><?php echo __('other'); ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
    <label class="form-label"><?php echo __('city'); ?></label>
    <div class="d-flex gap-2">
        <div class="flex-grow-1">
            <select name="city" id="add_patient_city" class="form-select select2-modal">
                <option value=""><?php echo __('select'); ?>...</option>
                <?php foreach ($all_cities as $city): ?>
                <option value="<?php echo htmlspecialchars($city['name']); ?>"><?php echo htmlspecialchars($city['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="button" class="btn btn-outline-primary" onclick="openQuickAddCityModal('add_patient_city')" title="<?php echo __('add_city'); ?>">
            <i class="bi bi-plus-lg"></i>
        </button>
    </div>
</div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('blood_group'); ?></label>
                            <input type="text" name="blood_group" class="form-control" placeholder="O+, A-, etc.">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('insurance_company'); ?></label>
                            <select name="insurance_company_id" class="form-select">
                                <option value=""><?php echo __('not_insured'); ?></option>
                                <?php foreach ($all_insurance as $i): ?>
                                <option value="<?php echo $i['id']; ?>"><?php echo htmlspecialchars($i['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('policy_number'); ?></label>
                            <input type="text" name="policy_number" class="form-control">
                        </div>
                        <div class="col-md-8 mb-3">
                            <label class="form-label"><?php echo __('address'); ?></label>
                            <textarea name="address" class="form-control" rows="1"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Edit Patient Modal -->
<div class="modal fade" id="editPatientModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="edit_patient">
            <input type="hidden" name="id" id="edit_patient_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('edit'); ?> <?php echo __('patient'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('name'); ?></label>
                            <input type="text" name="name" id="edit_patient_name" class="form-control" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('civil_id'); ?></label>
                            <input type="text" name="civil_id" id="edit_patient_civil_id" class="form-control">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('nationality'); ?></label>
                            <select name="nationality" id="edit_patient_nationality" class="form-select select2-modal">
                                <option value=""><?php echo __('search'); ?>...</option>
                                <?php foreach ($all_countries as $c): ?>
                                <option value="<?php echo htmlspecialchars($c); ?>"><?php echo htmlspecialchars($c); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="phone" id="edit_patient_phone" class="form-control" required>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label"><?php echo __('dob'); ?></label>
                            <input type="text" name="dob" id="edit_patient_dob" class="form-control masked-date" placeholder="YYYY-MM-DD" data-inputmask-alias="datetime" data-inputmask-inputformat="yyyy-mm-dd">
                        </div>
                        <div class="col-md-2 mb-3">
                            <label class="form-label"><?php echo __('age'); ?></label>
                            <input type="number" id="edit_patient_age" class="form-control" placeholder="<?php echo __('age'); ?>" min="0" max="150">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('gender'); ?></label>
                            <select name="gender" id="edit_patient_gender" class="form-select">
                                <option value="Male"><?php echo __('male'); ?></option>
                                <option value="Female"><?php echo __('female'); ?></option>
                                <option value="Other"><?php echo __('other'); ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
    <label class="form-label"><?php echo __('city'); ?></label>
    <div class="d-flex gap-2">
        <div class="flex-grow-1">
            <select name="city" id="edit_patient_city" class="form-select select2-modal">
                <option value=""><?php echo __('select'); ?>...</option>
                <?php foreach ($all_cities as $city): ?>
                <option value="<?php echo htmlspecialchars($city['name']); ?>"><?php echo htmlspecialchars($city['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="button" class="btn btn-outline-primary" onclick="openQuickAddCityModal('edit_patient_city')" title="<?php echo __('add_city'); ?>">
            <i class="bi bi-plus-lg"></i>
        </button>
    </div>
</div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('blood_group'); ?></label>
                            <input type="text" name="blood_group" id="edit_patient_blood_group" class="form-control" placeholder="O+, A-, etc.">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('insurance_company'); ?></label>
                            <select name="insurance_company_id" id="edit_patient_insurance_company_id" class="form-select">
                                <option value=""><?php echo __('not_insured'); ?></option>
                                <?php foreach ($all_insurance as $i): ?>
                                <option value="<?php echo $i['id']; ?>"><?php echo htmlspecialchars($i['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label"><?php echo __('policy_number'); ?></label>
                            <input type="text" name="policy_number" id="edit_patient_policy_number" class="form-control">
                        </div>
                        <div class="col-md-8 mb-3">
                            <label class="form-label"><?php echo __('address'); ?></label>
                            <textarea name="address" id="edit_patient_address" class="form-control" rows="1"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Delete Patient Modal -->
<div class="modal fade" id="deletePatientModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="delete_patient">
            <input type="hidden" name="id" id="delete_patient_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('delete'); ?> <?php echo __('patient'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><?php echo __('confirm_delete'); ?> <strong id="delete_patient_name"></strong>?</p>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add Doctor Modal -->
<div class="modal fade" id="addDoctorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="add_doctor">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_doctor'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?></label>
                        <input type="text" name="name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?></label>
                        <input type="text" name="name_ar" class="form-control" dir="rtl" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="tel" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('email'); ?></label>
                            <input type="email" name="email" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('specialization_en'); ?></label>
                        <input type="text" name="specialization_en" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('specialization_ar'); ?></label>
                        <input type="text" name="specialization_ar" class="form-control" dir="rtl">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('department'); ?></label>
                        <select name="department_id" class="form-select">
                            <option value=""><?php echo __('search'); ?>...</option>
                            <?php foreach ($all_departments as $dept): ?>
                            <option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('linked_employee'); ?> (HR/Leaves)</label>
                        <select name="employee_id" class="form-select select2-modal">
                            <option value=""><?php echo __('none'); ?></option>
                            <?php foreach ($all_employees as $emp): ?>
                            <option value="<?php echo $emp['id']; ?>"><?php echo htmlspecialchars($emp['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Edit Doctor Modal -->
<div class="modal fade" id="editDoctorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="edit_doctor">
            <input type="hidden" name="id" id="edit_doctor_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('edit'); ?> <?php echo __('doctor'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?></label>
                        <input type="text" name="name_en" id="edit_doctor_name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?></label>
                        <input type="text" name="name_ar" id="edit_doctor_name_ar" class="form-control" dir="rtl" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="tel" id="edit_doctor_tel" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('email'); ?></label>
                            <input type="email" name="email" id="edit_doctor_email" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('specialization_en'); ?></label>
                        <input type="text" name="specialization_en" id="edit_doctor_spec_en" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('specialization_ar'); ?></label>
                        <input type="text" name="specialization_ar" id="edit_doctor_spec_ar" class="form-control" dir="rtl">
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('department'); ?></label>
                        <select name="department_id" id="edit_doctor_dept_id" class="form-select">
                            <option value=""><?php echo __('search'); ?>...</option>
                            <?php foreach ($all_departments as $dept): ?>
                            <option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('linked_employee'); ?> (HR/Leaves)</label>
                        <select name="employee_id" id="edit_doctor_employee_id" class="form-select select2-modal">
                            <option value=""><?php echo __('none'); ?></option>
                            <?php foreach ($all_employees as $emp): ?>
                            <option value="<?php echo $emp['id']; ?>"><?php echo htmlspecialchars($emp['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Delete Doctor Modal -->
<div class="modal fade" id="deleteDoctorModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="delete_doctor">
            <input type="hidden" name="id" id="delete_doctor_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('delete'); ?> <?php echo __('doctor'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><?php echo __('confirm_delete'); ?>?</p>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add Nurse Modal -->
<div class="modal fade" id="addNurseModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="add_nurse">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_nurse'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?></label>
                        <input type="text" name="name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?></label>
                        <input type="text" name="name_ar" class="form-control" dir="rtl" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="tel" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('email'); ?></label>
                            <input type="email" name="email" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('department'); ?></label>
                        <select name="department_id" class="form-select">
                            <option value=""><?php echo __('search'); ?>...</option>
                            <?php foreach ($all_departments as $dept): ?>
                            <option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Edit Nurse Modal -->
<div class="modal fade" id="editNurseModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="edit_nurse">
            <input type="hidden" name="id" id="edit_nurse_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('edit'); ?> <?php echo __('nurses'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?></label>
                        <input type="text" name="name_en" id="edit_nurse_name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?></label>
                        <input type="text" name="name_ar" id="edit_nurse_name_ar" class="form-control" dir="rtl" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="tel" id="edit_nurse_tel" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('email'); ?></label>
                            <input type="email" name="email" id="edit_nurse_email" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('department'); ?></label>
                        <select name="department_id" id="edit_nurse_dept_id" class="form-select">
                            <option value=""><?php echo __('search'); ?>...</option>
                            <?php foreach ($all_departments as $dept): ?>
                            <option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Delete Nurse Modal -->
<div class="modal fade" id="deleteNurseModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="delete_nurse">
            <input type="hidden" name="id" id="delete_nurse_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('delete'); ?> <?php echo __('nurses'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><?php echo __('confirm_delete'); ?>?</p>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add Insurance Modal -->
<div class="modal fade" id="addInsuranceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=insurance" method="POST">
            <input type="hidden" name="action" value="add_insurance">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_insurance'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name'); ?> (EN)</label>
                        <input type="text" name="name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name'); ?> (AR)</label>
                        <input type="text" name="name_ar" class="form-control" dir="rtl" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('email'); ?></label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('phone'); ?></label>
                            <input type="text" name="phone" class="form-control">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('contact_info'); ?></label>
                        <textarea name="contact_info" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add City Modal -->
<div class="modal fade" id="addCityModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=cities" method="POST">
            <input type="hidden" name="action" value="add_city">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_city'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?></label>
                        <input type="text" name="name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?></label>
                        <input type="text" name="name_ar" class="form-control" dir="rtl" required>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Edit City Modal -->
<div class="modal fade" id="editCityModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=cities" method="POST">
            <input type="hidden" name="action" value="edit_city">
            <input type="hidden" name="id" id="edit_city_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('edit_city'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_en'); ?></label>
                        <input type="text" name="name_en" id="edit_city_name_en" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name_ar'); ?></label>
                        <input type="text" name="name_ar" id="edit_city_name_ar" class="form-control" dir="rtl" required>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Delete City Modal -->
<div class="modal fade" id="deleteCityModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=cities" method="POST">
            <input type="hidden" name="action" value="delete_city">
            <input type="hidden" name="id" id="delete_city_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('delete_city'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p><?php echo __('confirm_delete'); ?>?</p>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Quick Add City Modal -->
<div class="modal fade" id="quickAddCityModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form id="quickAddCityForm">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_city'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('name'); ?></label>
                        <input type="text" name="name" id="quick_city_name" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Record/Edit Visit Modal -->
<div class="modal fade" id="recordVisitModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=visits" method="POST" id="visitForm">
            <input type="hidden" name="action" value="record_visit" id="visitAction">
            <input type="hidden" name="id" id="visitId">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white" id="visitModalTitle"><?php echo __('add_visit'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- Tabs -->
                    <ul class="nav nav-tabs mb-3" id="visitTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="details-tab" data-bs-toggle="tab" data-bs-target="#visit-details" type="button" role="tab"><?php echo __('details'); ?></button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="vitals-tab" data-bs-toggle="tab" data-bs-target="#visit-vitals" type="button" role="tab"><?php echo __('vitals'); ?></button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="diagnosis-tab" data-bs-toggle="tab" data-bs-target="#visit-diagnosis" type="button" role="tab"><?php echo __('symptoms_diagnosis'); ?></button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="treatments-tab" data-bs-toggle="tab" data-bs-target="#visit-treatments" type="button" role="tab"><?php echo __('treatment_plan'); ?></button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="prescriptions-tab" data-bs-toggle="tab" data-bs-target="#visit-prescriptions" type="button" role="tab"><?php echo __('prescriptions'); ?></button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="sick-leave-tab" data-bs-toggle="tab" data-bs-target="#visit-sick-leave" type="button" role="tab"><?php echo __('sick_leave'); ?></button>
                        </li>
                    </ul>
                    
                    <div class="tab-content" id="visitTabsContent">
                        <!-- Details Tab -->
                        <div class="tab-pane fade show active" id="visit-details" role="tabpanel">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label"><?php echo __('patient'); ?></label>
                                    <select name="patient_id" id="visit_patient_id" class="form-select select2-modal" required>
                                        <option value=""><?php echo __('select'); ?>...</option>
                                        <?php foreach ($all_patients as $p): ?>
                                        <option value="<?php echo $p['id']; ?>" data-dob="<?php echo $p['dob']; ?>" data-gender="<?php echo $p['gender']; ?>"><?php echo sprintf('%06d', $p['id']) . ' - ' . htmlspecialchars($p['name']) . (!empty($p['phone']) ? ' - ' . htmlspecialchars($p['phone']) : ''); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label"><?php echo __('doctor'); ?></label>
                                    <select name="doctor_id" id="visit_doctor_id" class="form-select select2-modal" required>
                                        <option value=""><?php echo __('select'); ?>...</option>
                                        <?php foreach ($all_doctors as $d): ?>
                                        <option value="<?php echo $d['id']; ?>"><?php echo htmlspecialchars($d['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('gender'); ?></label>
                                    <input type="text" id="visit_patient_gender" class="form-control" readonly>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('dob'); ?></label>
                                    <input type="text" id="visit_patient_dob" class="form-control" readonly>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label"><?php echo __('age'); ?></label>
                                    <input type="text" id="visit_patient_age" class="form-control" readonly>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="generate_token" name="generate_token" value="1">
                                        <label class="form-check-label" for="generate_token"><?php echo __('issue_token'); ?></label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Vitals Tab -->
                        <div class="tab-pane fade" id="visit-vitals" role="tabpanel">
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label class="form-label"><?php echo __('weight'); ?> (kg)</label>
                                    <input type="number" step="0.1" name="weight" id="visit_weight" class="form-control">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label"><?php echo __('blood_pressure'); ?></label>
                                    <input type="text" name="blood_pressure" id="visit_blood_pressure" class="form-control" placeholder="120/80">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label"><?php echo __('heart_rate'); ?> (bpm)</label>
                                    <input type="number" name="heart_rate" id="visit_heart_rate" class="form-control">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label"><?php echo __('temperature'); ?> (°C)</label>
                                    <input type="number" step="0.1" name="temperature" id="visit_temperature" class="form-control">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label"><?php echo __("nursing_notes"); ?></label>
                                    <button type="button" class="btn btn-sm btn-outline-info float-end" onclick="generateAISuggestion(this)" data-target="nursing_notes">
                                        <i class="bi bi-magic"></i> AI Suggestion
                                    </button>
                                    <textarea name="nursing_notes" id="visit_nursing_notes" class="form-control summernote" rows="3"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Symptoms & Diagnosis Tab -->
                        <div class="tab-pane fade" id="visit-diagnosis" role="tabpanel">
                            <div class="mb-3">
                                <label class="form-label"><?php echo __('symptoms'); ?></label>
                                <button type="button" class="btn btn-sm btn-outline-info float-end" onclick="generateAISuggestion(this)" data-target="symptoms">
                                    <i class="bi bi-magic"></i> AI Suggestion
                                </button>
                                <textarea name="symptoms" id="visit_symptoms" class="form-control summernote" rows="3"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label"><?php echo __('diagnosis'); ?></label>
                                <button type="button" class="btn btn-sm btn-outline-info float-end" onclick="generateAISuggestion(this)" data-target="diagnosis">
                                    <i class="bi bi-magic"></i> AI Suggestion
                                </button>
                                <textarea name="diagnosis" id="visit_diagnosis" class="form-control summernote" rows="3"></textarea>
                            </div>
                        </div>

                        <!-- Treatments Tab -->
                        <div class="tab-pane fade" id="visit-treatments" role="tabpanel">
                            <div class="mb-3">
                                <label class="form-label"><?php echo __('treatment_plan'); ?></label>
                                <button type="button" class="btn btn-sm btn-outline-info float-end" onclick="generateAISuggestion(this)" data-target="treatment_plan">
                                    <i class="bi bi-magic"></i> AI Suggestion
                                </button>
                                <textarea name="treatment_plan" id="visit_treatment_plan" class="form-control summernote" rows="3" data-height="300"></textarea>
                            </div>
                        </div>
                        
                        <!-- Sick Leave Tab -->
                        <div class="tab-pane fade" id="visit-sick-leave" role="tabpanel">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label"><?php echo __('start_date'); ?></label>
                                    <input type="date" name="sick_leave_start_date" id="visit_sick_leave_start_date" class="form-control">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label"><?php echo __('duration_days'); ?></label>
                                    <input type="number" name="sick_leave_days" id="visit_sick_leave_days" class="form-control" min="1">
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label"><?php echo __('remarks'); ?></label>
                                    <textarea name="sick_leave_remarks" id="visit_sick_leave_remarks" class="form-control" rows="3"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Prescriptions Tab -->
                        <div class="tab-pane fade" id="visit-prescriptions" role="tabpanel">
                            <label class="form-label fw-bold"><?php echo __('prescriptions'); ?></label>
                            <div class="table-responsive mb-2">
                                <table class="table table-bordered table-sm" id="prescriptionTable">
                                    <thead>
                                        <tr>
                                            <th><?php echo __('drug_name'); ?></th>
                                            <th style="width: 150px;"><?php echo __('dosage'); ?></th>
                                            <th><?php echo __('instructions'); ?></th>
                                            <th style="width: 50px;"></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Rows added dynamically -->
                                    </tbody>
                                </table>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-primary" onclick="addPrescriptionRow()">
                                <i class="bi bi-plus-lg"></i> <?php echo __('add_drug'); ?>
                            </button>
                        </div>
                    </div>
                    
                    <div id="visitEditAlert" class="alert alert-warning mt-3 d-none">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        <?php echo __('disable_visit_edit_24h_desc'); ?>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4" id="visitSaveBtn"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add Inquiry Modal -->
<div class="modal fade" id="addInquiryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=laboratory_inquiries" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="add_inquiry">
            <input type="hidden" name="visit_id" id="inquiry_visit_id">
            <input type="hidden" name="patient_id" id="inquiry_patient_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_inquiry'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('patient_name'); ?></label>
                        <input type="text" name="patient_name" id="inquiry_patient_name" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('inquiry_date'); ?></label>
                            <input type="datetime-local" name="inquiry_date" class="form-control" value="<?php echo date('Y-m-d\TH:i'); ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('status'); ?></label>
                            <select name="status" class="form-select">
                                <option value="Pending"><?php echo __('Pending'); ?></option>
                                <option value="Completed"><?php echo __('Completed'); ?></option>
                                <option value="Cancelled"><?php echo __('Cancelled'); ?></option>
                            </select>
                        </div>
                    </div>
                    
                    <label class="form-label fw-bold"><?php echo __('tests'); ?></label>
                    <div class="table-responsive mb-2">
                        <table class="table table-bordered table-sm" id="inquiryTestsTable">
                            <thead>
                                <tr>
                                    <th><?php echo __('test'); ?></th>
                                    <th><?php echo __('result'); ?></th>
                                    <th><?php echo __('attachment'); ?></th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addInquiryTestRow()">
                        <i class="bi bi-plus-lg"></i> <?php echo __('add_test'); ?>
                    </button>
                    
                    <div class="mt-3">
                        <label class="form-label"><?php echo __('notes'); ?></label>
                        <textarea name="notes" class="form-control summernote" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Add X-Ray Inquiry Modal -->
<div class="modal fade" id="addXrayInquiryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=xray_inquiries" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="add_xray_inquiry">
            <input type="hidden" name="visit_id" id="xray_inquiry_visit_id">
            <input type="hidden" name="patient_id" id="xray_inquiry_patient_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('add_xray_inquiry'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('patient_name'); ?></label>
                        <input type="text" name="patient_name" id="xray_inquiry_patient_name" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('inquiry_date'); ?></label>
                            <input type="datetime-local" name="inquiry_date" class="form-control" value="<?php echo date('Y-m-d\TH:i'); ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><?php echo __('status'); ?></label>
                            <select name="status" class="form-select">
                                <option value="Pending"><?php echo __('Pending'); ?></option>
                                <option value="Completed"><?php echo __('Completed'); ?></option>
                                <option value="Cancelled"><?php echo __('Cancelled'); ?></option>
                            </select>
                        </div>
                    </div>
                    
                    <label class="form-label fw-bold"><?php echo __('xray_tests'); ?></label>
                    <div class="table-responsive mb-2">
                        <table class="table table-bordered table-sm" id="xrayInquiryTestsTable">
                            <thead>
                                <tr>
                                    <th><?php echo __('test'); ?></th>
                                    <th><?php echo __('result'); ?></th>
                                    <th><?php echo __('attachment'); ?></th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addXrayInquiryTestRow()">
                        <i class="bi bi-plus-lg"></i> <?php echo __('add_test'); ?>
                    </button>
                    
                    <div class="mt-3">
                        <label class="form-label"><?php echo __('notes'); ?></label>
                        <textarea name="notes" class="form-control summernote" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Report Modal -->
<div class="modal fade" id="reportModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=visits" method="POST">
            <input type="hidden" name="action" value="create_report">
            <input type="hidden" name="visit_id" id="report_visit_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('new_report'); ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('report_type'); ?></label>
                        <select name="report_type" class="form-select" required>
                            <option value="Medical Report">Medical Report</option>
                            <option value="Referral">Referral</option>
                            <option value="Sick Leave">Sick Leave</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('findings'); ?></label>
                        <textarea name="findings" class="form-control summernote" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('recommendations'); ?></label>
                        <textarea name="recommendations" class="form-control summernote" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Bill Modal -->
<div class="modal fade" id="billModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?section=<?php echo $section; ?>" method="POST">
            <input type="hidden" name="action" value="create_bill">
            <input type="hidden" name="patient_id" id="bill_patient_id">
            <input type="hidden" name="visit_id" id="bill_visit_id">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold text-white"><?php echo __('create_bill'); ?>: <span id="bill_patient_name"></span></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="table-responsive mb-2">
                        <table class="table table-bordered" id="billTable">
                            <thead>
                                <tr>
                                    <th><?php echo __('description'); ?></th>
                                    <th style="width: 150px;"><?php echo __('amount'); ?></th>
                                    <th style="width: 50px;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" name="items[]" class="form-control" placeholder="Consultation Fee" required></td>
                                    <td><input type="number" step="0.01" name="amounts[]" class="form-control" required></td>
                                    <td><button type="button" class="btn btn-sm btn-danger" onclick="removeBillItemRow(this)"><i class="bi bi-x-lg"></i></button></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addBillItemRow()">
                        <i class="bi bi-plus-lg"></i> <?php echo __('add_item'); ?>
                    </button>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-success px-4"><?php echo __('create_bill'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Visit Results Modal (Read-only view) -->
<div class="modal fade" id="visitResultsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-white"><?php echo __('visit_details'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="visitResultsContent">
                <!-- Populated via JS -->
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.7/jquery.inputmask.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
<script src="assets/js/ai_helper.js"></script>
<script src="assets/js/main.js?v=<?php echo time(); ?>"></script>
<script>
const disableVisitEdit24h = <?php echo !empty($settings['disable_visit_edit_24h']) ? 'true' : 'false'; ?>;

// --- Patient Modals ---
function showEditPatientModal(data) {
    document.getElementById('edit_patient_id').value = data.id;
    document.getElementById('edit_patient_name').value = data.name;
    document.getElementById('edit_patient_civil_id').value = data.civil_id || '';
    $('#edit_patient_nationality').val(data.nationality).trigger('change');
    document.getElementById('edit_patient_phone').value = data.phone;
    document.getElementById('edit_patient_dob').value = data.dob || '';
    document.getElementById('edit_patient_age').value = data.age || '';
    document.getElementById('edit_patient_gender').value = data.gender;
    $('#edit_patient_city').val(data.city).trigger('change');
    document.getElementById('edit_patient_blood_group').value = data.blood_group || '';
    document.getElementById('edit_patient_insurance_company_id').value = data.insurance_company_id || '';
    document.getElementById('edit_patient_policy_number').value = data.policy_number || '';
    document.getElementById('edit_patient_address').value = data.address || '';
    
    var modal = new bootstrap.Modal(document.getElementById('editPatientModal'));
    modal.show();
}

function showDeletePatientModal(id, name) {
    document.getElementById('delete_patient_id').value = id;
    document.getElementById('delete_patient_name').innerText = name;
    var modal = new bootstrap.Modal(document.getElementById('deletePatientModal'));
    modal.show();
}

// --- Visit Modals ---
function showRecordVisitModal(patientId = null) {
    document.getElementById('visitForm').reset();
    document.getElementById('visitAction').value = 'record_visit';
    document.getElementById('visitId').value = '';
    document.getElementById('visitModalTitle').innerText = '<?php echo __('add_visit'); ?>';
    
    // Enable patient select
    $('#visit_patient_id').prop('disabled', false);
    
    // Reset UI state
    document.getElementById('visitSaveBtn').disabled = false;
    document.getElementById('visitEditAlert').classList.add('d-none');
    
    // Reset Summernote fields
    $('#visit_symptoms').summernote('code', '');
    $('#visit_diagnosis').summernote('code', '');
    $('#visit_treatment_plan').summernote('code', '');
    $('#visit_nursing_notes').summernote('code', '');

    // Clear dynamic rows
    document.querySelector('#prescriptionTable tbody').innerHTML = '';
    addPrescriptionRow(); // Add one empty row
    
    // Clear patient info
    $('#visit_patient_gender').val('');
    $('#visit_patient_dob').val('');
    $('#visit_patient_age').val('');

    if (patientId) {
        $('#visit_patient_id').val(patientId).trigger('change');
    } else {
        $('#visit_patient_id').val('').trigger('change');
    }
    
    // Reset other selects
    $('#visit_doctor_id').val('').trigger('change');

    var modal = new bootstrap.Modal(document.getElementById('recordVisitModal'));
    modal.show();
}

function showEditVisitModal(data) {
    document.getElementById('visitForm').reset();
    document.getElementById('visitAction').value = 'edit_visit';
    document.getElementById('visitId').value = data.id;
    document.getElementById('visitModalTitle').innerText = '<?php echo __('edit_visit'); ?>';
    
    // Disable patient select
    $('#visit_patient_id').prop('disabled', true);
    
    // Check 24h restriction
    let isEditable = true;
    if (disableVisitEdit24h && data.visit_date) {
        const visitDate = new Date(data.visit_date);
        const now = new Date();
        const diffHours = (now - visitDate) / 1000 / 60 / 60;
        
        if (diffHours > 24) {
            isEditable = false;
        }
    }
    
    const saveBtn = document.getElementById('visitSaveBtn');
    const alertBox = document.getElementById('visitEditAlert');
    
    if (!isEditable) {
        saveBtn.disabled = true;
        alertBox.classList.remove('d-none');
        // Optionally disable inputs
        $('#visitForm input, #visitForm select, #visitForm textarea').prop('disabled', true);
        $('.summernote').summernote('disable');
    } else {
        saveBtn.disabled = false;
        alertBox.classList.add('d-none');
        $('#visitForm input, #visitForm select, #visitForm textarea').prop('disabled', false);
        // Ensure patient ID stays disabled
        $('#visit_patient_id').prop('disabled', true); 
        $('.summernote').summernote('enable');
    }
    
    // Populate fields
    $('#visit_patient_id').val(data.patient_id).trigger('change');
    $('#visit_doctor_id').val(data.doctor_id).trigger('change');
    document.getElementById('visit_weight').value = data.weight || '';
    document.getElementById('visit_blood_pressure').value = data.blood_pressure || '';
    document.getElementById('visit_heart_rate').value = data.heart_rate || '';
    document.getElementById('visit_temperature').value = data.temperature || '';
    
    // Populate new fields
    $('#visit_patient_gender').val(data.patient_gender || '');
    $('#visit_patient_dob').val(data.patient_dob || '');
    if (data.patient_dob) {
        const birthDate = new Date(data.patient_dob);
        const today = new Date();
        let age = today.getFullYear() - birthDate.getFullYear();
        const m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        $('#visit_patient_age').val(age);
    } else {
        $('#visit_patient_age').val('');
    }
    
    // Populate Sick Leave
    document.getElementById('visit_sick_leave_start_date').value = data.sick_leave_start_date || '';
    document.getElementById('visit_sick_leave_days').value = data.sick_leave_days || '';
    document.getElementById('visit_sick_leave_remarks').value = data.sick_leave_remarks || '';

    // Populate Summernote fields
    $('#visit_symptoms').summernote('code', data.symptoms || '');
    $('#visit_diagnosis').summernote('code', data.diagnosis || '');
    $('#visit_treatment_plan').summernote('code', data.treatment_plan || '');
    $('#visit_nursing_notes').summernote('code', data.nursing_notes || '');
    
    // Populate prescriptions
    const tbody = document.querySelector('#prescriptionTable tbody');
    tbody.innerHTML = '';
    
    if (data.prescriptions && data.prescriptions.length > 0) {
        data.prescriptions.forEach(p => {
            addPrescriptionRow(p.drug_name, p.dosage, p.instructions);
        });
    } else {
        addPrescriptionRow();
    }
    
    var modal = new bootstrap.Modal(document.getElementById('recordVisitModal'));
    modal.show();
}

function showVisitResultsModal(data) {
    const content = `
        <dl class="row">
            <dt class="col-sm-3"><?php echo __('date'); ?></dt>
            <dd class="col-sm-9">${data.visit_date}</dd>
            
            <dt class="col-sm-3"><?php echo __('patient'); ?></dt>
            <dd class="col-sm-9">${data.patient_name || '-'}</dd>
            
            <dt class="col-sm-3"><?php echo __('doctor'); ?></dt>
            <dd class="col-sm-9">${data.doctor_name || '-'}</dd>
            
            <dt class="col-sm-3"><?php echo __('diagnosis'); ?></dt>
            <dd class="col-sm-9">${data.diagnosis || '-'}</dd>
            
            <dt class="col-sm-3"><?php echo __('treatment'); ?></dt>
            <dd class="col-sm-9">${data.treatment_plan || '-'}</dd>
            
            <dt class="col-sm-3"><?php echo __('vitals'); ?></dt>
            <dd class="col-sm-9">
                BP: ${data.blood_pressure || '-'}, 
                Weight: ${data.weight || '-'} kg, 
                Temp: ${data.temperature || '-'}°C
                , <br>Nursing Notes: ${data.nursing_notes || '-'}
            </dd>
        </dl>
    `;
    document.getElementById('visitResultsContent').innerHTML = content;
    var modal = new bootstrap.Modal(document.getElementById('visitResultsModal'));
    modal.show();
}

function showLabInquiryModalFromVisit(visitId, patientId, patientName) {
    document.getElementById('inquiry_visit_id').value = visitId;
    document.getElementById('inquiry_patient_id').value = patientId;
    document.getElementById('inquiry_patient_name').value = patientName || '';
    // if patient name is present, make it readonly maybe?
    
    // Clear tests
    document.querySelector('#inquiryTestsTable tbody').innerHTML = '';
    addInquiryTestRow();
    
    var modal = new bootstrap.Modal(document.getElementById('addInquiryModal'));
    modal.show();
}

function showXrayInquiryModalFromVisit(visitId, patientId, patientName) {
    document.getElementById('xray_inquiry_visit_id').value = visitId;
    document.getElementById('xray_inquiry_patient_id').value = patientId;
    document.getElementById('xray_inquiry_patient_name').value = patientName || '';
    
    // Clear tests
    document.querySelector('#xrayInquiryTestsTable tbody').innerHTML = '';
    addXrayInquiryTestRow();
    
    var modal = new bootstrap.Modal(document.getElementById('addXrayInquiryModal'));
    modal.show();
}

function showReportModal(visitId) {
    document.getElementById('report_visit_id').value = visitId;
    var modal = new bootstrap.Modal(document.getElementById('reportModal'));
    modal.show();
}

// --- Bill Modal ---
function showBillModal(visitId, patientId, patientName) {
    document.getElementById('bill_visit_id').value = visitId || '';
    document.getElementById('bill_patient_id').value = patientId;
    document.getElementById('bill_patient_name').innerText = patientName || '';
    
    // Reset table
    const tbody = document.querySelector('#billTable tbody');
    tbody.innerHTML = `
        <tr>
            <td><input type="text" name="items[]" class="form-control" placeholder="Consultation Fee" required></td>
            <td><input type="number" step="0.01" name="amounts[]" class="form-control" required></td>
            <td><button type="button" class="btn btn-sm btn-danger" onclick="removeBillItemRow(this)"><i class="bi bi-x-lg"></i></button></td>
        </tr>
    `;

    var modal = new bootstrap.Modal(document.getElementById('billModal'));
    modal.show();
}

// --- Helper Functions ---
function addPrescriptionRow(drugName = '', dosage = '', instructions = '') {
    const tbody = document.querySelector('#prescriptionTable tbody');
    const tr = document.createElement('tr');
    
    // Build options for drug select
    let drugOptions = '<option value="">Select Drug...</option>';
    <?php foreach ($all_drugs as $drug): ?>
        drugOptions += `<option value="<?php echo htmlspecialchars($drug['name']); ?>" data-dosage="<?php echo htmlspecialchars($drug['default_dosage']); ?>" data-instructions="<?php echo htmlspecialchars($drug['default_instructions']); ?>"><?php echo htmlspecialchars($drug['name']); ?></option>`;
    <?php endforeach; ?>
    
    tr.innerHTML = `
        <td>
            <div class="input-group">
                <select name="prescriptions[drug_name][]" class="form-select drug-select" onchange="updateDrugDetails(this)">
                    ${drugOptions}
                </select>
                <input type="text" name="prescriptions[custom_drug_name][]" class="form-control d-none" placeholder="Or type custom name">
            </div>
        </td>
        <td><input type="text" name="prescriptions[dosage][]" class="form-control" value="${dosage}"></td>
        <td><input type="text" name="prescriptions[instructions][]" class="form-control" value="${instructions}"></td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="removePrescriptionRow(this)"><i class="bi bi-x-lg"></i></button></td>
    `;
    tbody.appendChild(tr);
    
    // Set value if provided
    if (drugName) {
        // Try to set select value
        const select = tr.querySelector('select');
        select.value = drugName;
    }
}

function updateDrugDetails(select) {
    const option = select.options[select.selectedIndex];
    const row = select.closest('tr');
    if (option.value) {
        row.querySelector('input[name="prescriptions[dosage][]"]').value = option.getAttribute('data-dosage') || '';
        row.querySelector('input[name="prescriptions[instructions][]"]').value = option.getAttribute('data-instructions') || '';
    }
}

function removePrescriptionRow(btn) {
    btn.closest('tr').remove();
}

function addBillItemRow() {
    const tbody = document.querySelector('#billTable tbody');
    const tr = document.createElement('tr');
    tr.innerHTML = `
        <td><input type="text" name="items[]" class="form-control" required></td>
        <td><input type="number" step="0.01" name="amounts[]" class="form-control" required></td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="removeBillItemRow(this)"><i class="bi bi-x-lg"></i></button></td>
    `;
    tbody.appendChild(tr);
}

function removeBillItemRow(btn) {
    const tbody = document.querySelector('#billTable tbody');
    if (tbody.children.length > 1) {
        btn.closest('tr').remove();
    }
}

function addInquiryTestRow() {
    const tbody = document.querySelector('#inquiryTestsTable tbody');
    const tr = document.createElement('tr');
    
    let options = '<option value="">Select Test...</option>';
    <?php foreach ($all_tests as $t): ?>
        options += `<option value="<?php echo $t['id']; ?>"><?php echo htmlspecialchars($t['name']); ?> ($<?php echo $t['price']; ?>)</option>`;
    <?php endforeach; ?>
    
    tr.innerHTML = `
        <td><select name="test_ids[]" class="form-select select2-modal">${options}</select></td>
        <td><input type="text" name="results[]" class="form-control"></td>
        <td><input type="file" name="attachments[]" class="form-control"></td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()"><i class="bi bi-x-lg"></i></button></td>
    `;
    tbody.appendChild(tr);
    $(tr).find('.select2-modal').select2({ dropdownParent: $(tr).closest('.modal'), width: '100%' });
}

function addXrayInquiryTestRow() {
    const tbody = document.querySelector('#xrayInquiryTestsTable tbody');
    const tr = document.createElement('tr');
    const rowIndex = tbody.children.length;
    
    let options = '<option value="">Select X-Ray...</option>';
    <?php foreach ($all_xrays as $x): ?>
        options += `<option value="<?php echo $x['id']; ?>"><?php echo htmlspecialchars($x['name']); ?> ($<?php echo $x['price']; ?>)</option>`;
    <?php endforeach; ?>
    
    tr.innerHTML = `
        <td><select name="xray_ids[]" class="form-select select2-modal">${options}</select></td>
        <td><input type="text" name="results[]" class="form-control"></td>
        <td>
            <input type="file" name="new_attachments_${rowIndex}[]" class="form-control" multiple>
            <input type="hidden" name="row_indices[]" value="${rowIndex}">
        </td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="this.closest('tr').remove()"><i class="bi bi-x-lg"></i></button></td>
    `;
    tbody.appendChild(tr);
    $(tr).find('.select2-modal').select2({ dropdownParent: $(tr).closest('.modal'), width: '100%' });
}

// --- Other Modals (Doctor, Nurse, etc.) ---
function showEditDoctorModal(data) {
    document.getElementById('edit_doctor_id').value = data.id;
    document.getElementById('edit_doctor_name_en').value = data.name_en;
    document.getElementById('edit_doctor_name_ar').value = data.name_ar;
    document.getElementById('edit_doctor_tel').value = data.tel || '';
    document.getElementById('edit_doctor_email').value = data.email || '';
    document.getElementById('edit_doctor_spec_en').value = data.specialization_en || '';
    document.getElementById('edit_doctor_spec_ar').value = data.specialization_ar || '';
    document.getElementById('edit_doctor_dept_id').value = data.department_id || '';
    $('#edit_doctor_employee_id').val(data.employee_id).trigger('change');
    
    var modal = new bootstrap.Modal(document.getElementById('editDoctorModal'));
    modal.show();
}

function showDeleteDoctorModal(id) {
    document.getElementById('delete_doctor_id').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteDoctorModal'));
    modal.show();
}

function showEditNurseModal(data) {
    document.getElementById('edit_nurse_id').value = data.id;
    document.getElementById('edit_nurse_name_en').value = data.name_en;
    document.getElementById('edit_nurse_name_ar').value = data.name_ar;
    document.getElementById('edit_nurse_tel').value = data.tel || '';
    document.getElementById('edit_nurse_email').value = data.email || '';
    document.getElementById('edit_nurse_dept_id').value = data.department_id || '';
    
    var modal = new bootstrap.Modal(document.getElementById('editNurseModal'));
    modal.show();
}

function showDeleteNurseModal(id) {
    document.getElementById('delete_nurse_id').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteNurseModal'));
    modal.show();
}

function showEditCityModal(data) {
    document.getElementById('edit_city_id').value = data.id;
    document.getElementById('edit_city_name_en').value = data.name_en;
    document.getElementById('edit_city_name_ar').value = data.name_ar;
    var modal = new bootstrap.Modal(document.getElementById('editCityModal'));
    modal.show();
}

function showDeleteCityModal(id) {
    document.getElementById('delete_city_id').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteCityModal'));
    modal.show();
}

let targetCitySelectId = null;

function openQuickAddCityModal(targetSelectId) {
    targetCitySelectId = targetSelectId;
    var modal = new bootstrap.Modal(document.getElementById('quickAddCityModal'));
    modal.show();
}

// Handle Quick Add City Form Submission
document.getElementById('quickAddCityForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const name = document.getElementById('quick_city_name').value;
    
    fetch('api/cities.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=add&name=' + encodeURIComponent(name)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Add new option to the target select and select it
            const newOption = new Option(data.city.name, data.city.name, true, true);
            $('#' + targetCitySelectId).append(newOption).trigger('change');
            
            // Also add to other city selects if they exist
            $('.select2-modal[name="city"]').each(function() {
                if (this.id !== targetCitySelectId) {
                    $(this).append(new Option(data.city.name, data.city.name, false, false));
                }
            });

            // Close modal and reset form
            bootstrap.Modal.getInstance(document.getElementById('quickAddCityModal')).hide();
            document.getElementById('quickAddCityForm').reset();
        } else {
            alert('Error adding city: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while adding the city.');
    });
});

$(document).ready(function() {
    // Initialize Select2 for modals
    $('.select2-modal').each(function() {
        $(this).select2({
            dropdownParent: $(this).closest('.modal'),
            width: '100%'
        });
    });
    
    // Initialize Inputmask
    if (typeof Inputmask !== 'undefined') {
        Inputmask().mask(document.querySelectorAll("[data-inputmask], [data-inputmask-alias], [data-inputmask-mask]"));
    }
    
    // Initialize Summernote
    $('.summernote').each(function() {
        $(this).summernote({
            placeholder: 'Type here...',
            tabsize: 2,
            height: $(this).data('height') || 100,
            toolbar: [
              ['style', ['style']],
              ['font', ['bold', 'underline', 'clear']],
              ['color', ['color']],
              ['para', ['ul', 'ol', 'paragraph']],
              ['table', ['table']],
              ['insert', ['link', 'picture', 'video']],
              ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });
    });

    // Update patient details in Visit Modal
    $('#visit_patient_id').on('change', function() {
        const selected = $(this).find('option:selected');
        const dob = selected.data('dob');
        const gender = selected.data('gender');
        
        $('#visit_patient_gender').val(gender || '');
        $('#visit_patient_dob').val(dob || '');
        
        if (dob) {
            const birthDate = new Date(dob);
            const today = new Date();
            let age = today.getFullYear() - birthDate.getFullYear();
            const m = today.getMonth() - birthDate.getMonth();
            if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            $('#visit_patient_age').val(age);
        } else {
            $('#visit_patient_age').val('');
        }
    });
});
</script>
<script>
<?php if (isset($_SESSION['print_token_id'])): ?>
    window.open('print_token.php?id=<?php echo $_SESSION['print_token_id']; ?>', '_blank', 'width=400,height=600');
    <?php unset($_SESSION['print_token_id']); ?>
<?php endif; ?>
</script>
</body>