<div class="student-form border rounded p-3 mb-4 bg-light position-relative">
    <button type="button" class="btn-close position-absolute end-0 top-0 m-2 js-remove-student" aria-label="Close"></button>
    <h5 class="mb-3 text-primary">Student Information</h5>
    <div class="col-md-12 mb-3">
        <label class="form-label fw-bold mb-2 d-block">
            Was your child enrolled in Al Rahma Sunday School last year? <span class="text-danger">*</span>
        </label>

        <div class="d-flex align-items-center flex-wrap gap-3">
            <div class="form-check ps-3">
                <input class="form-check-input" type="radio" name="last_year_0" value="yes" data-base-name="last_year" required autocomplete="off">
                <label class="form-check-label">Yes</label>
            </div>
            <div class="form-check ps-3">
                <input class="form-check-input" type="radio" name="last_year_0" value="no" data-base-name="last_year" required autocomplete="off">
                <label class="form-check-label">No</label>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label">First Name <span class="text-danger">*</span></label>
            <input
                type="text"
                class="form-control"
                name="studentFirstName[]"
                placeholder="First Name"
                maxlength="30"
                required
                data-base-name="studentFirstName"
                title="Only letters, spaces, or dashes (2–30 chars)">
        </div>
        <div class="col-md-6 mb-3">
            <label class="form-label">Last Name <span class="text-danger">*</span></label>
            <input
                type="text"
                class="form-control"
                name="studentLastName[]"
                placeholder="Last Name"
                maxlength="30"
                required
                data-base-name="studentLastName"
                title="Only letters, spaces, or dashes (2–30 chars)">
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label">Date of Birth <span class="text-danger">*</span></label>
            <input type="date" class="form-control dob-input" name="dob[]" required data-base-name="dob">
            <small class="text-danger age-error d-none">Student must be between 5 and 18 years old.</small>
        </div>
        <div class="col-6 mb-3">
            <label class="form-label grade-label">Last Year Grade <span class="text-danger">*</span></label>
            <select class="form-select dynamic-grade grade-select"
                name="registration_grade[]"
                required data-base-name="registration_grade"
                disabled>
                <option value="">Select Grade</option>
            </select>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6 mb-3">
            <label class="form-label">Gender <span class="text-danger">*</span></label>
            <select class="form-select" name="gender[]" required data-base-name="gender">
                <option value="">Select Gender</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
            </select>
        </div>
        <div class="col-md-6 mb-3">
            <label class="form-label">Photo Consent <span class="text-danger">*</span></label>
            <select class="form-select" name="photo_consent[]" required data-base-name="photo_consent">
                <option value="">Select Answer</option>
                <option value="Yes">Yes</option>
                <option value="No">No</option>
            </select>
            <small>
                <a href="#" class="text-nowrap" data-bs-toggle="modal" data-bs-target="#picturePolicyModal">
                    Read Photo Consent Agreement
                </a>
            </small>
        </div>
    </div>

    <!-- NEW SECTION -->
    <div class="row">
        <!-- Medical Conditions -->
        <div class="col-md-6 mb-3">
            <label class="form-label">Medical Conditions (Select all that apply from the 33 items below) <span class="text-danger">*</span></label>
            <div class="border rounded p-2 bg-white ps-3" style="max-height: 200px; overflow-y: auto;">
                <?php
                $medicalOptions = [
                    "None",
                    "ADHD (Attention-Deficit/Hyperactivity Disorder)",
                    "Anxiety or Emotional Disorders",
                    "Asthma",
                    "Autism Spectrum Disorder (ASD)",
                    "Behavioral or Conduct Disorders",
                    "Blindness / Vision Impairment",
                    "Celiac Disease (Gluten Intolerance)",
                    "Cerebral Palsy",
                    "Cystic Fibrosis",
                    "Depression",
                    "Diabetes (Type 1 or Type 2)",
                    "Down Syndrome",
                    "Dyslexia or Learning Disabilities",
                    "Eating Disorders",
                    "Eczema / Severe Skin Conditions",
                    "Epilepsy / Seizure Disorders",
                    "Hearing Impairments / Deafness",
                    "Heart Conditions (congenital or acquired)",
                    "Hemophilia / Bleeding Disorders",
                    "Kidney Disease",
                    "Migraines / Chronic Headaches",
                    "Obsessive-Compulsive Disorder (OCD)",
                    "Physical Disabilities / Mobility Impairments",
                    "PTSD (Post-Traumatic Stress Disorder)",
                    "Sickle Cell Anemia",
                    "Speech and Language Disorders",
                    "Thyroid Disorders",
                    "Tourette Syndrome",
                    "Traumatic Brain Injury (TBI)",
                    "Rheumatic diseases",
                    "Ulcerative Colitis / Crohn’s Disease",
                    "Other"
                ];
                foreach ($medicalOptions as $opt): ?>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="medical_conditions[][]" value="<?= esc($opt) ?>" data-base-name="medical_conditions">
                        <label class="form-check-label ms-1"><?= esc($opt) ?></label>
                    </div>
                <?php endforeach; ?>
            </div>
            <input type="text" class="form-control mt-2 d-none medical-condition-other" name="medical_condition_other[]" placeholder="Please specify if 'Other' selected">
        </div>

        <!-- Allergies -->
        <div class="col-md-6 mb-3">
            <label class="form-label">Allergies (Select all that apply from the 24 items below) <span class="text-danger">*</span></label>
            <div class="border rounded p-2 bg-white ps-3" style="max-height: 200px; overflow-y: auto; overflow-x: hidden;">
                <?php
                $allergyOptions = [
                    "None",
                    "Animal Dander (cats, dogs, etc.)",
                    "Antibiotics",
                    "Bee stings",
                    "Cockroach",
                    "Corn",
                    "Dust Mites",
                    "Egg",
                    "Fire ant stings",
                    "Fish",
                    "Fragrances / Perfumes",
                    "Latex",
                    "Milk / Dairy",
                    "Mold",
                    "Mosquito bites",
                    "Peanut",
                    "Pollen (grass, tree, weed)",
                    "Sesame",
                    "Shellfish (shrimp, crab, lobster, etc.)",
                    "Soy",
                    "Tree Nuts (almond, cashew, walnut, etc.)",
                    "Wasp stings",
                    "Wheat / Gluten",
                    "Other"
                ];
                foreach ($allergyOptions as $opt): ?>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="allergies[][]" value="<?= esc($opt) ?>" data-base-name="allergies">
                        <label class="form-check-label ms-1"><?= esc($opt) ?></label>
                    </div>
                <?php endforeach; ?>
            </div>
            <input type="text" class="form-control mt-2 d-none allergy-other" name="allergy_other[]" placeholder="Please specify if 'Other' selected">
        </div>
    </div>
</div>

<script>
    const gradeOptions = {
        public: [{
                value: "NA",
                text: "Not enrolled in public school"
            },
            {
                value: "KG",
                text: "Pre-K / Kindergarten"
            },
            {
                value: "1",
                text: "Grade 1"
            }, {
                value: "2",
                text: "Grade 2"
            },
            {
                value: "3",
                text: "Grade 3"
            }, {
                value: "4",
                text: "Grade 4"
            },
            {
                value: "5",
                text: "Grade 5"
            }, {
                value: "6",
                text: "Grade 6"
            },
            {
                value: "7",
                text: "Grade 7"
            }, {
                value: "8",
                text: "Grade 8"
            },
            {
                value: "9",
                text: "Grade 9"
            }, {
                value: "10",
                text: "Grade 10"
            },
            {
                value: "11",
                text: "Grade 11"
            }, {
                value: "12",
                text: "Grade 12"
            }
        ],
        alrahma: [{
                value: "KG",
                text: "Pre-K / Kindergarten"
            },
            {
                value: "1",
                text: "Grade 1"
            }, {
                value: "2",
                text: "Grade 2"
            },
            {
                value: "3",
                text: "Grade 3"
            }, {
                value: "4",
                text: "Grade 4"
            },
            {
                value: "5",
                text: "Grade 5"
            }, {
                value: "6",
                text: "Grade 6"
            },
            {
                value: "7",
                text: "Grade 7"
            }, {
                value: "8",
                text: "Grade 8"
            },
            {
                value: "9",
                text: "Grade 9"
            }, {
                value: "10",
                text: "Youth"
            }
        ]
    };

    function resetGradeSelect(gradeSelect, gradeLabel) {
        if (!gradeSelect || !gradeLabel) return;
        gradeSelect.innerHTML = '<option value="">Select Grade</option>';
        gradeSelect.value = '';
        gradeSelect.disabled = true; // keep disabled until a radio is chosen
        gradeLabel.innerHTML = 'Last Year Grade <span class="text-danger">*</span>';
    }

    function populateSelect(gradeSelect, options) {
        gradeSelect.innerHTML = '<option value="">Select Grade</option>';
        options.forEach(o => {
            const opt = document.createElement('option');
            opt.value = o.value;
            opt.textContent = o.text;
            gradeSelect.appendChild(opt);
        });
    }

    function updateGradeOptions(studentForm, type) {
        const gradeSelect = studentForm.querySelector('.grade-select');
        const gradeLabel = studentForm.querySelector('.grade-label');
        if (!gradeSelect || !gradeLabel) return;

        gradeSelect.disabled = false; // enable now that a choice was made
        gradeSelect.value = ''; // clear any stale selection

        if (type === 'yes') {
            gradeLabel.innerHTML = 'Al Rahma School Last Year Grade <span class="text-danger">*</span>';
            populateSelect(gradeSelect, gradeOptions.alrahma);
        } else if (type === 'no') {
            gradeLabel.innerHTML = 'Public School Last Year Grade <span class="text-danger">*</span>';
            populateSelect(gradeSelect, gradeOptions.public);
        } else {
            resetGradeSelect(gradeSelect, gradeLabel);
        }
    }

    // Event: when a radio is chosen, update this form's select
    document.addEventListener('change', function(e) {
        if (e.target.matches('input[type="radio"][data-base-name="last_year"]')) {
            const form = e.target.closest('.student-form');
            if (form && e.target.checked) {
                updateGradeOptions(form, e.target.value);
            }
        }
    });

    // On load: enforce disabled unless a radio is already checked (server repopulation)
    (function initStudentForms() {
        const forms = document.querySelectorAll('.student-form');
        forms.forEach(form => {
            const gradeSelect = form.querySelector('.grade-select');
            const gradeLabel = form.querySelector('.grade-label');

            // Start disabled (HTML already has disabled, but enforce from JS too)
            resetGradeSelect(gradeSelect, gradeLabel);

            // If a radio is already checked (e.g., after validation error), enable/populate accordingly
            const checked = form.querySelector('input[type="radio"][data-base-name="last_year"]:checked');
            if (checked) {
                updateGradeOptions(form, checked.value);
            }
        });
    })();
</script>