<?php $__env->startSection('title', 'Generate Challans'); ?>
<?php $__env->startSection('page_title', 'Generate Fee Challans'); ?>
<?php $__env->startSection('breadcrumbs'); ?>
    <li class="breadcrumb-item"><a href="<?php echo e(route('challans.index')); ?>">Challans</a></li><li class="breadcrumb-item active">Generate</li>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="card"><div class="card-body">
        <form method="POST" action="<?php echo e(route('challans.store')); ?>">
            <?php echo csrf_field(); ?>
            <div class="row g-3">
                <div class="col-md-3"><label class="form-label">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($s->is_current): echo 'selected'; endif; ?>><?php echo e($s->name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select></div>
                <div class="col-md-3"><label class="form-label">Billing Month</label>
                    <?php
                        // Build the month options from the current session range (fallback: current year ±).
                        $cur = $sessions->firstWhere('is_current', true) ?? $sessions->first();
                        $start = $cur && $cur->start_date ? \Illuminate\Support\Carbon::parse($cur->start_date)->startOfMonth() : now()->subMonths(3)->startOfMonth();
                        $end = $cur && $cur->end_date ? \Illuminate\Support\Carbon::parse($cur->end_date)->startOfMonth() : now()->addMonths(9)->startOfMonth();
                        $months = [];
                        for ($m = $start->copy(); $m <= $end; $m->addMonth()) { $months[] = $m->copy(); }
                        $defaultMonth = now()->startOfMonth()->format('Y-m-d');
                    ?>
                    <select name="month" class="form-select">
                        <?php $__currentLoopData = $months; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $m): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($m->format('Y-m-d')); ?>" <?php if($m->format('Y-m-d') === old('month', $defaultMonth)): echo 'selected'; endif; ?>><?php echo e($m->format('F Y')); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="col-md-3"><label class="form-label">Bill Date</label>
                    <input type="date" name="bill_date" value="<?php echo e(now()->format('Y-m-d')); ?>" class="form-control"></div>
                <div class="col-md-3"><label class="form-label">Due Date</label>
                    <input type="date" name="due_date" value="<?php echo e(now()->addDays(10)->format('Y-m-d')); ?>" class="form-control"></div>

                <div class="col-12"><label class="form-label">Fee Heads to include <span class="text-danger">*</span></label>
                    <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"><div class="form-check">
                                <input type="checkbox" name="fee_type_ids[]" value="<?php echo e($ft->id); ?>" id="ft<?php echo e($ft->id); ?>" class="form-check-input" <?php if($ft->frequency==='monthly'): echo 'checked'; endif; ?>>
                                <label for="ft<?php echo e($ft->id); ?>" class="form-check-label"><?php echo e($ft->name); ?> <span class="text-muted small">(<?php echo e($ft->frequency); ?>)</span></label>
                            </div></div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                </div>

                <div class="col-md-4"><label class="form-label">Scope</label>
                    <select name="scope" id="scope" class="form-select">
                        <option value="students">Selected students (by class/section)</option>
                        <option value="branch">All families in branch</option>
                        <option value="family">A single family</option>
                    </select></div>
                <div class="col-md-5" id="familyPicker" style="display:none">
                    <label class="form-label">Family</label>
                    <select name="family_id" class="form-select js-select2">
                        <option value="">— Select family —</option>
                        <?php $__currentLoopData = $families; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $f): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($f->id); ?>"><?php echo e($f->family_code); ?> — <?php echo e($f->primary_contact_name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                
                <div class="col-12" id="studentPicker">
                    <div class="card border">
                        <div class="card-body">
                            <div class="row g-2 align-items-end mb-2">
                                <div class="col-md-3">
                                    <label class="form-label small mb-1">Class</label>
                                    <select id="sp_class" class="form-select form-select-sm">
                                        <option value="">All Classes</option>
                                        <?php $__currentLoopData = $classes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $c): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><option value="<?php echo e($c->id); ?>"><?php echo e($c->name); ?></option><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label small mb-1">Section</label>
                                    <select id="sp_section" class="form-select form-select-sm"><option value="">All Sections</option></select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label small mb-1">Search student</label>
                                    <input type="text" id="sp_search" class="form-control form-control-sm" placeholder="Name or admission #…">
                                </div>
                                <div class="col-md-2">
                                    <button type="button" id="sp_all" class="btn btn-sm btn-light border w-100">Select all shown</button>
                                </div>
                            </div>
                            <div class="border rounded" style="max-height:280px;overflow:auto">
                                <table class="table table-sm table-hover mb-0 align-middle">
                                    <thead class="table-light" style="position:sticky;top:0"><tr>
                                        <th style="width:40px"></th><th>Student</th><th>Father Name</th><th>NIC / B-Form</th><th>Adm #</th><th>Class / Section</th>
                                    </tr></thead>
                                    <tbody id="sp_rows"></tbody>
                                </table>
                            </div>
                            <div class="small text-muted mt-2"><b id="sp_count">0</b> student(s) selected. <span class="text-muted">One combined challan is created per family for the students you pick.</span></div>
                            <div id="sp_inputs"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="alert alert-info small mt-3 mb-0"><i class="bi bi-info-circle me-1"></i>Sibling discounts and student concessions/scholarships are applied automatically. Families already billed for the selected month are skipped.</div>
            <div class="mt-3 d-flex gap-2">
                <button class="btn btn-primary"><i class="bi bi-lightning-charge me-1"></i>Generate</button>
                <a href="<?php echo e(route('challans.index')); ?>" class="btn btn-light border">Cancel</a>
            </div>
        </form>
    </div></div>

    <?php $__env->startPush('scripts'); ?>
    <script>
        const SP_STUDENTS = <?php echo json_encode($studentsList, 15, 512) ?>;
        const SP_SECTIONS = <?php echo json_encode($sections, 15, 512) ?>;
        const selected = new Set();

        const scope = document.getElementById('scope');
        function applyScope() {
            document.getElementById('familyPicker').style.display = scope.value === 'family' ? 'block' : 'none';
            document.getElementById('studentPicker').style.display = scope.value === 'students' ? 'block' : 'none';
        }
        scope.addEventListener('change', applyScope);

        const spClass = document.getElementById('sp_class');
        const spSection = document.getElementById('sp_section');
        const spSearch = document.getElementById('sp_search');
        const spRows = document.getElementById('sp_rows');
        const spInputs = document.getElementById('sp_inputs');
        const spCount = document.getElementById('sp_count');
        const classNames = {}; <?php $__currentLoopData = $classes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $c): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> classNames[<?php echo e($c->id); ?>] = <?php echo json_encode($c->name, 15, 512) ?>; <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        const sectionNames = {}; <?php $__currentLoopData = $sections; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> sectionNames[<?php echo e($s->id); ?>] = <?php echo json_encode($s->name, 15, 512) ?>; <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

        function loadSpSections() {
            const c = spClass.value;
            spSection.innerHTML = '<option value="">All Sections</option>';
            SP_SECTIONS.filter(s => !c || String(s.class_id) === String(c)).forEach(s => {
                spSection.appendChild(new Option(s.name, s.id));
            });
        }
        function syncInputs() {
            spInputs.innerHTML = '';
            selected.forEach(id => {
                const i = document.createElement('input');
                i.type = 'hidden'; i.name = 'student_ids[]'; i.value = id;
                spInputs.appendChild(i);
            });
            spCount.textContent = selected.size;
        }
        function render() {
            const c = spClass.value, sec = spSection.value, q = spSearch.value.trim().toLowerCase();
            const list = SP_STUDENTS.filter(s =>
                (!c || String(s.class_id) === String(c)) &&
                (!sec || String(s.section_id) === String(sec)) &&
                (!q || (s.name||'').toLowerCase().includes(q) || (s.admission_number||'').toLowerCase().includes(q)
                    || (s.father||'').toLowerCase().includes(q) || (s.nic||'').toLowerCase().includes(q))
            ).slice(0, 400);
            const esc = v => (v==null?'':String(v)).replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m]));
            spRows.innerHTML = list.map(s => `
                <tr>
                    <td><input type="checkbox" class="form-check-input sp-chk" value="${s.id}" ${selected.has(String(s.id))?'checked':''}></td>
                    <td>${esc(s.name)}</td>
                    <td class="small">${esc(s.father)||'-'}</td>
                    <td class="small">${esc(s.nic)||'-'}</td>
                    <td class="small">${esc(s.admission_number)}</td>
                    <td class="small">${classNames[s.class_id]||'-'}${s.section_id?(' / '+(sectionNames[s.section_id]||'')):''}</td>
                </tr>`).join('') || '<tr><td colspan="6" class="text-center text-muted py-3">No students match.</td></tr>';
        }
        spRows.addEventListener('change', e => {
            if (e.target.classList.contains('sp-chk')) {
                const v = e.target.value;
                e.target.checked ? selected.add(v) : selected.delete(v);
                syncInputs();
            }
        });
        document.getElementById('sp_all').addEventListener('click', () => {
            spRows.querySelectorAll('.sp-chk').forEach(chk => { chk.checked = true; selected.add(chk.value); });
            syncInputs();
        });
        spClass.addEventListener('change', () => { loadSpSections(); render(); });
        spSection.addEventListener('change', render);
        spSearch.addEventListener('input', render);

        applyScope(); loadSpSections(); render();
    </script>
    <?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/u385418287/domains/itartificer.com/public_html/sms-erp/resources/views/fees/challans/create.blade.php ENDPATH**/ ?>