<?php echo csrf_field(); ?>
<div class="row g-4">
    
    <div class="col-12">
        <h6 class="text-uppercase text-muted small fw-bold mb-2"><i class="bi bi-mortarboard me-1"></i>Admission & Academic</h6>
    </div>
    <div class="col-md-4">
        <label class="form-label">Family <span class="text-danger">*</span></label>
        <select name="family_id" class="form-select js-select2 <?php $__errorArgs = ['family_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
            <option value="">— Select family —</option>
            <?php $__currentLoopData = $families; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $family): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($family->id); ?>" <?php if(old('family_id', $student->family_id) == $family->id): echo 'selected'; endif; ?>>
                    <?php echo e($family->family_code); ?> — <?php echo e($family->primary_contact_name); ?>

                </option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
        <?php $__errorArgs = ['family_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback d-block"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
        <div class="form-text">
            <a href="#" data-bs-toggle="modal" data-bs-target="#quickFamilyModal"><i class="bi bi-plus-circle me-1"></i>Add new family</a>
        </div>
    </div>
    <div class="col-md-4">
        <label class="form-label">Academic Session</label>
        <select name="academic_session_id" class="form-select">
            <?php $__currentLoopData = $sessions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($s->id); ?>" <?php if(old('academic_session_id', $student->academic_session_id ?? optional($sessions->firstWhere('is_current',true))->id) == $s->id): echo 'selected'; endif; ?>><?php echo e($s->name); ?></option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
    </div>
    <div class="col-md-4">
        <label class="form-label">Admission Date</label>
        <input type="date" name="admission_date" value="<?php echo e(old('admission_date', optional($student->admission_date)->format('Y-m-d') ?? now()->format('Y-m-d'))); ?>" class="form-control">
    </div>
    <div class="col-md-4">
        <label class="form-label">Class</label>
        <select name="class_id" id="class_id" class="form-select">
            <option value="">— Select class —</option>
            <?php $__currentLoopData = $classes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $class): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($class->id); ?>" <?php if(old('class_id', $student->class_id) == $class->id): echo 'selected'; endif; ?>><?php echo e($class->name); ?></option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
    </div>
    <div class="col-md-4">
        <label class="form-label">Section</label>
        <select name="section_id" id="section_id" class="form-select">
            <option value="">— Select section —</option>
        </select>
    </div>
    <div class="col-md-4">
        <label class="form-label">Group</label>
        <input type="text" name="group" value="<?php echo e(old('group', $student->group)); ?>" class="form-control" placeholder="Science / Arts">
    </div>

    
    <div class="col-12"><hr class="my-1"><h6 class="text-uppercase text-muted small fw-bold mb-2"><i class="bi bi-person-vcard me-1"></i>Basic Information</h6></div>
    <div class="col-md-4">
        <label class="form-label">Student Name <span class="text-danger">*</span></label>
        <input type="text" name="name" value="<?php echo e(old('name', $student->name)); ?>" class="form-control <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
        <?php $__errorArgs = ['name'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
    </div>
    <div class="col-md-4">
        <label class="form-label">Name (Urdu)</label>
        <input type="text" name="name_urdu" value="<?php echo e(old('name_urdu', $student->name_urdu)); ?>" class="form-control" dir="rtl">
    </div>
    <div class="col-md-4">
        <label class="form-label">Photo</label>
        <input type="file" name="photo" accept="image/*" class="form-control <?php $__errorArgs = ['photo'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
        <?php $__errorArgs = ['photo'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
    </div>
    <div class="col-md-3">
        <label class="form-label">Gender <span class="text-danger">*</span></label>
        <select name="gender" class="form-select">
            <?php $__currentLoopData = ['male','female','other']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $g): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($g); ?>" <?php if(old('gender', $student->gender) === $g): echo 'selected'; endif; ?> class="text-capitalize"><?php echo e(ucfirst($g)); ?></option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
    </div>
    <div class="col-md-3"><label class="form-label">Date of Birth</label>
        <input type="date" name="date_of_birth" value="<?php echo e(old('date_of_birth', optional($student->date_of_birth)->format('Y-m-d'))); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">Place of Birth</label>
        <input type="text" name="place_of_birth" value="<?php echo e(old('place_of_birth', $student->place_of_birth)); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">Blood Group</label>
        <input type="text" name="blood_group" value="<?php echo e(old('blood_group', $student->blood_group)); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">Religion</label>
        <input type="text" name="religion" value="<?php echo e(old('religion', $student->religion ?? 'Islam')); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">Nationality</label>
        <input type="text" name="nationality" value="<?php echo e(old('nationality', $student->nationality ?? 'Pakistani')); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">B-Form #</label>
        <input type="text" name="b_form_number" value="<?php echo e(old('b_form_number', $student->b_form_number)); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">GR Number</label>
        <input type="text" name="gr_number" value="<?php echo e(old('gr_number', $student->gr_number)); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">Roll Number</label>
        <input type="text" name="roll_number" value="<?php echo e(old('roll_number', $student->roll_number)); ?>" class="form-control"></div>
    <div class="col-md-3"><label class="form-label">Registration #</label>
        <input type="text" name="registration_number" value="<?php echo e(old('registration_number', $student->registration_number)); ?>" class="form-control"></div>
    <?php if($student->exists): ?>
        <div class="col-md-3"><label class="form-label">Status</label>
            <select name="status" class="form-select text-capitalize">
                <?php $__currentLoopData = App\Models\Student::STATUSES; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($s); ?>" <?php if(old('status', $student->status) === $s): echo 'selected'; endif; ?>><?php echo e(ucfirst(str_replace('_',' ',$s))); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>
    <?php endif; ?>

    
    <div class="col-12"><hr class="my-1"><h6 class="text-uppercase text-muted small fw-bold mb-2"><i class="bi bi-heart-pulse me-1"></i>Medical</h6></div>
    <div class="col-md-6"><label class="form-label">Allergies</label>
        <input type="text" name="allergies" value="<?php echo e(old('allergies', $student->allergies)); ?>" class="form-control"></div>
    <div class="col-md-6"><label class="form-label">Medical Conditions</label>
        <input type="text" name="medical_conditions" value="<?php echo e(old('medical_conditions', $student->medical_conditions)); ?>" class="form-control"></div>
    <div class="col-md-6"><label class="form-label">Disability Information</label>
        <input type="text" name="disability_info" value="<?php echo e(old('disability_info', $student->disability_info)); ?>" class="form-control"></div>
    <div class="col-md-6"><label class="form-label">Medical Notes</label>
        <input type="text" name="medical_notes" value="<?php echo e(old('medical_notes', $student->medical_notes)); ?>" class="form-control"></div>

    
    <div class="col-12"><hr class="my-1"><h6 class="text-uppercase text-muted small fw-bold mb-2"><i class="bi bi-bus-front me-1"></i>Transport</h6></div>
    <div class="col-md-4"><label class="form-label">Route</label>
        <select name="transport_route_id" id="transport_route_id" class="form-select">
            <option value="">— Not using transport —</option>
            <?php $__currentLoopData = $transportRoutes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $route): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($route->id); ?>" <?php if(old('transport_route_id', $student->transport_route_id) == $route->id): echo 'selected'; endif; ?>><?php echo e($route->name); ?> (<?php echo e($route->code); ?>)</option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
    </div>
    <div class="col-md-4"><label class="form-label">Stop</label>
        <select name="transport_stop_id" id="transport_stop_id" class="form-select">
            <option value="">— Select stop —</option>
        </select>
        <div class="form-text" id="stop_fare_hint"></div>
    </div>
    <div class="col-md-4"><label class="form-label">Pickup Point</label>
        <input type="text" name="pickup_point" value="<?php echo e(old('pickup_point', $student->pickup_point)); ?>" class="form-control"></div>

    
    <div class="col-12"><hr class="my-1">
        <h6 class="text-uppercase text-muted small fw-bold mb-1"><i class="bi bi-cash-coin me-1"></i>Fees (per student)</h6>
        <p class="text-muted small mb-2">Each box shows the <b>class default</b> as a placeholder. Leave blank to use the default, or type an amount to set a custom fee for this student. Transport uses the chosen stop’s fare.</p>
    </div>
    <div class="col-12">
        <div class="row g-2">
            <?php $__currentLoopData = $feeTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ft): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div class="col-md-3 col-sm-4">
                    <label class="form-label small mb-1">
                        <?php echo e($ft->name); ?>

                        <span class="badge bg-soft-secondary text-capitalize"><?php echo e(str_replace('_',' ',$ft->frequency)); ?></span>
                    </label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text">Rs</span>
                        <input type="number" step="0.01" min="0"
                               name="fees[<?php echo e($ft->id); ?>]"
                               data-fee-input="<?php echo e($ft->id); ?>"
                               <?php if(strtoupper($ft->code) === 'TRANS' || str_contains(strtolower($ft->name), 'transport')): ?> data-transport-fee="1" <?php endif; ?>
                               value="<?php echo e(old('fees.'.$ft->id, $feeOverrides[$ft->id] ?? '')); ?>"
                               class="form-control" placeholder="0">
                    </div>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
    </div>
</div>

<?php if (! ($student->exists)): ?>
    <div class="mt-3 p-2 rounded" style="background:#f6f8fc">
        <div class="form-check">
            <input type="hidden" name="generate_challan" value="0">
            <input type="checkbox" class="form-check-input" id="generate_challan" name="generate_challan" value="1" <?php if(old('generate_challan')): echo 'checked'; endif; ?>>
            <label class="form-check-label" for="generate_challan">
                <b>Generate the first fee challan now</b> — bills this month’s fees for the family right after admission (due in 10 days).
            </label>
        </div>
    </div>
<?php endif; ?>

<div class="mt-4 d-flex gap-2">
    <button class="btn btn-primary"><i class="bi bi-check-lg me-1"></i><?php echo e($submitLabel ?? 'Save'); ?></button>
    <a href="<?php echo e(route('students.index')); ?>" class="btn btn-light border">Cancel</a>
</div>


<div class="modal fade" id="quickFamilyModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-people me-1"></i>Add New Family</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger py-2 px-3 small d-none" data-qf-error></div>
                <div class="row g-2">
                    <?php if(auth()->user()->isSuperAdmin()): ?>
                        <div class="col-12">
                            <label class="form-label small mb-1">Branch <span class="text-danger">*</span></label>
                            <select class="form-select form-select-sm" data-qf="branch_id">
                                <?php $__currentLoopData = \App\Models\Branch::active()->orderBy('name')->get(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $b): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($b->id); ?>" <?php if(app(\App\Support\BranchContext::class)->currentId() == $b->id): echo 'selected'; endif; ?>><?php echo e($b->name); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                    <?php endif; ?>
                    <div class="col-md-6">
                        <label class="form-label small mb-1">Father Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-sm" data-qf="father_name">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small mb-1">Father Mobile</label>
                        <input type="text" class="form-control form-control-sm" data-qf="father_mobile">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small mb-1">Father CNIC</label>
                        <input type="text" class="form-control form-control-sm js-cnic" data-qf="father_cnic" maxlength="15" placeholder="00000-0000000-0">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small mb-1">Mother Name</label>
                        <input type="text" class="form-control form-control-sm" data-qf="mother_name">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small mb-1">Email</label>
                        <input type="email" class="form-control form-control-sm" data-qf="email">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small mb-1">Address</label>
                        <input type="text" class="form-control form-control-sm" data-qf="address">
                    </div>
                </div>
                <div class="form-text mt-2">You can add full details later from the Families section.</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light border btn-sm" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary btn-sm" data-qf-save>
                    <span data-qf-label><i class="bi bi-check-lg me-1"></i>Save & Select</span>
                </button>
            </div>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script>
    const SECTIONS = <?php echo json_encode($sections, 15, 512) ?>;
    const selectedSection = <?php echo json_encode(old('section_id', $student->section_id), 512) ?>;
    function loadSections() {
        const classId = document.getElementById('class_id').value;
        const sel = document.getElementById('section_id');
        sel.innerHTML = '<option value="">— Select section —</option>';
        SECTIONS.filter(s => String(s.class_id) === String(classId)).forEach(s => {
            const o = document.createElement('option');
            o.value = s.id; o.textContent = s.name;
            if (String(s.id) === String(selectedSection)) o.selected = true;
            sel.appendChild(o);
        });
    }
    document.getElementById('class_id').addEventListener('change', loadSections);
    loadSections();

    /* ---- Transport stops (filtered by route) ---- */
    const STOPS = <?php echo json_encode($transportStops, 15, 512) ?>;
    const selectedStop = <?php echo json_encode(old('transport_stop_id', $student->transport_stop_id), 512) ?>;
    const routeSel = document.getElementById('transport_route_id');
    const stopSel = document.getElementById('transport_stop_id');
    const stopHint = document.getElementById('stop_fare_hint');

    function fmt(n) { return 'Rs ' + Number(n).toLocaleString(); }

    function loadStops() {
        const routeId = routeSel.value;
        stopSel.innerHTML = '<option value="">— Select stop —</option>';
        STOPS.filter(s => String(s.transport_route_id) === String(routeId)).forEach(s => {
            const o = document.createElement('option');
            o.value = s.id; o.textContent = s.name + ' — ' + fmt(s.fare);
            o.dataset.fare = s.fare;
            if (String(s.id) === String(selectedStop)) o.selected = true;
            stopSel.appendChild(o);
        });
        updateTransportFee();
    }
    function currentStopFare() {
        const opt = stopSel.options[stopSel.selectedIndex];
        return opt && opt.dataset.fare ? Number(opt.dataset.fare) : 0;
    }
    function updateTransportFee() {
        const fare = currentStopFare();
        stopHint.textContent = fare ? ('Stop fare: ' + fmt(fare)) : '';
        document.querySelectorAll('[data-transport-fee]').forEach(inp => {
            inp.placeholder = fare ? String(fare) : '0';
        });
    }
    if (routeSel) {
        routeSel.addEventListener('change', loadStops);
        stopSel.addEventListener('change', updateTransportFee);
        loadStops();
    }

    /* ---- Fee placeholders from class structure ---- */
    const FEE_STRUCTURE = <?php echo json_encode($feeStructure, 15, 512) ?>; // { class_id: { fee_type_id: amount } }
    function updateFeePlaceholders() {
        const classId = document.getElementById('class_id').value;
        const map = FEE_STRUCTURE[classId] || {};
        document.querySelectorAll('[data-fee-input]').forEach(inp => {
            if (inp.hasAttribute('data-transport-fee')) return; // handled by transport
            const ftId = inp.getAttribute('data-fee-input');
            inp.placeholder = map[ftId] != null ? String(map[ftId]) : '0';
        });
    }
    document.getElementById('class_id').addEventListener('change', updateFeePlaceholders);
    updateFeePlaceholders();

    /* ---- Quick "Add Family" modal ---- */
    (function () {
        const modalEl = document.getElementById('quickFamilyModal');
        if (!modalEl) return;
        const saveBtn = modalEl.querySelector('[data-qf-save]');
        const label = modalEl.querySelector('[data-qf-label]');
        const errBox = modalEl.querySelector('[data-qf-error]');
        const familySelect = document.querySelector('select[name="family_id"]');
        const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

        function val(name) { const el = modalEl.querySelector('[data-qf="' + name + '"]'); return el ? el.value.trim() : ''; }

        saveBtn.addEventListener('click', function () {
            errBox.classList.add('d-none'); errBox.textContent = '';
            if (!val('father_name')) { errBox.textContent = 'Father name is required.'; errBox.classList.remove('d-none'); return; }

            const payload = {
                father_name: val('father_name'), father_mobile: val('father_mobile'), father_cnic: val('father_cnic'),
                mother_name: val('mother_name'), email: val('email'), address: val('address'), branch_id: val('branch_id'),
            };
            label.innerHTML = 'Saving…'; saveBtn.disabled = true;

            fetch(<?php echo json_encode(route('families.quick-store'), 15, 512) ?>, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': token, 'Accept': 'application/json' },
                body: JSON.stringify(payload),
            }).then(async (r) => {
                if (!r.ok) {
                    const d = await r.json().catch(() => ({}));
                    const msg = d.message || (d.errors ? Object.values(d.errors)[0][0] : 'Could not save family.');
                    throw new Error(msg);
                }
                return r.json();
            }).then((fam) => {
                // Add and select the new family in the dropdown (works with select2).
                const opt = new Option(fam.label, fam.id, true, true);
                familySelect.appendChild(opt);
                if (window.jQuery && jQuery(familySelect).data('select2')) {
                    jQuery(familySelect).val(String(fam.id)).trigger('change');
                } else {
                    familySelect.value = String(fam.id);
                    familySelect.dispatchEvent(new Event('change', { bubbles: true }));
                }
                // reset + close
                modalEl.querySelectorAll('[data-qf]').forEach((el) => { if (el.tagName === 'INPUT') el.value = ''; });
                bootstrap.Modal.getOrCreateInstance(modalEl).hide();
            }).catch((e) => {
                errBox.textContent = e.message; errBox.classList.remove('d-none');
            }).finally(() => {
                label.innerHTML = '<i class="bi bi-check-lg me-1"></i>Save & Select'; saveBtn.disabled = false;
            });
        });
    })();
</script>
<?php $__env->stopPush(); ?>
<?php /**PATH /home/u385418287/domains/itartificer.com/public_html/sms-erp/resources/views/students/_form.blade.php ENDPATH**/ ?>