<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="wrapper">
        <div class="content"></div>
        <h2 class="text-center mt-4 mb-3">
            Registered Students
            <?php if (isset($total_new)): ?>
                <span class="badge bg-secondary ms-2"><?= (int)$total_new ?></span>
            <?php endif; ?>
        </h2>

        <!-- Flash messages -->
        <?php if (session()->getFlashdata('success')): ?>
            <div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
        <?php endif; ?>
        <?php if (session()->getFlashdata('error')): ?>
            <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
        <?php endif; ?>

        <div class="table-responsive">
            <table id="enrollmentTable" class="table table-bordered table-striped mt-4 align-middle w-100">

                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>New Student</th>
                        <th>Current Class</th>
                        <th>Actual Status</th>
                        <th>Age</th> <!-- NEW -->
                        <th>Registration Date</th> <!-- NEW -->
                        <th>Action</th>
                    </tr>

                </thead>
                <tbody>
                    <?php if (!empty($new_students)): ?>
                        <?php foreach ($new_students as $student): ?>
                            <?php
                            $sid            = (int)($student['id'] ?? 0);
                            $modalIdContact = $student['modalIdContact'] ?? ('contact_' . $sid);
                            ?>
                            <tr>
                                <td>
                                    <a href="<?= site_url('family') ?>?student_id=<?= (int)($student['id'] ?? 0) ?>" class="text-decoration-none" data-family-student-id="<?= (int)($student['id'] ?? 0) ?>">
                                        <?= esc($student['firstname'] ?? '') ?>
                                    </a>
                                </td>
                                <td>
                                    <a href="<?= site_url('family') ?>?student_id=<?= (int)($student['id'] ?? 0) ?>" class="text-decoration-none" data-family-student-id="<?= (int)($student['id'] ?? 0) ?>">
                                        <?= esc($student['lastname'] ?? '') ?>
                                    </a>
                                </td>

                                <td>
                                    <?php if (($student['new_student'] ?? '') === 'Yes'): ?>
                                        <span class="badge bg-warning text-dark">Yes</span>
                                    <?php elseif (($student['new_student'] ?? '') === 'No'): ?>
                                        <span class="badge bg-success">No</span>
                                    <?php else: ?>
                                        <span class="badge bg-light text-dark">Unknown</span>
                                    <?php endif; ?>
                                </td>

                                <td><?= esc($student['class_section'] ?? 'Class not Assigned') ?></td>

                                <td>
                                    <?php
                                    $status = $student['enrollment_status'] ?? 'not enrolled';
                                    switch ($status) {
                                        case 'admission under review':
                                            echo '<span class="badge bg-primary">admission under review</span>';
                                            break;
                                        case 'payment pending':
                                            echo '<span class="badge bg-warning text-dark">payment pending</span>';
                                            break;
                                        case 'enrolled':
                                            echo '<span class="badge bg-success">enrolled</span>';
                                            break;
                                        case 'withdraw under review':
                                            echo '<span class="badge bg-warning text-dark">withdraw under review</span>';
                                            break;
                                        case 'refund pending':
                                            echo '<span class="badge bg-info text-dark">refund pending</span>';
                                            break;
                                        case 'withdrawn':
                                            echo '<span class="badge bg-danger">withdrawn</span>';
                                            break;
                                        case 'waitlist':
                                            echo '<span class="badge bg-secondary">waitlist</span>';
                                            break;
                                        case 'denied':
                                            echo '<span class="badge bg-light">denied</span>';
                                            break;
                                        case 'not enrolled':
                                            echo '<span class="badge bg-danger text-dark">not enrolled</span>';
                                            break;
                                        default:
                                            echo '<span class="badge bg-light text-dark">unknown</span>';
                                    }
                                    ?>
                                </td>
                                <td><?= esc($student['age'] ?? '-') ?></td>
                                <td><?= esc(!empty($student['registration_date']) ? local_date($student['registration_date'], 'm-d-Y') : '-') ?></td>

                                <td class="d-flex gap-2">
                                    <!-- Contact info modal trigger ONLY -->
                                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#<?= esc($modalIdContact) ?>">
                                        Contact Information
                                    </button>

                                    <!-- Contact Modal -->
                                    <div class="modal fade" id="<?= esc($modalIdContact) ?>" tabindex="-1" aria-labelledby="<?= esc($modalIdContact) ?>Label" aria-hidden="true">
                                        <div class="modal-dialog modal-lg">
                                            <div class="modal-content shadow">
                                                <div class="modal-header bg-primary text-white">
                                                    <h5 class="modal-title" id="<?= esc($modalIdContact) ?>Label">
                                                        Contact Info - <?= esc($student['firstname'] ?? '') ?> <?= esc($student['lastname'] ?? '') ?>
                                                    </h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <h5 class="mb-3 border-bottom pb-1">👨‍👩‍👧 Parent Information</h5>
                                                    <div class="row mb-3">
                                                        <div class="col-md-6">
                                                            <p><strong>Name:</strong> <?= esc(($student['parent_firstname'] ?? '') . ' ' . ($student['parent_lastname'] ?? '')) ?></p>
                                                            <p><strong>Phone:</strong> <?= esc($student['parent_phone'] ?? 'N/A') ?></p>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <p><strong>Email:</strong> <?= esc($student['parent_email'] ?? 'N/A') ?></p>
                                                        </div>
                                                    </div>

                                                    <h5 class="mb-3 border-bottom pb-1">🚨 Emergency Contact</h5>
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <p><strong>Name:</strong> <?= esc($student['emergency_name'] ?? 'N/A') ?></p>
                                                            <p><strong>Relationship:</strong> <?= esc($student['emergency_relationship'] ?? 'N/A') ?></p>
                                                            <p><strong>Phone:</strong> <?= esc($student['emergency_phone'] ?? 'N/A') ?></p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- /Contact Modal -->
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center">No students found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
    $(function() {
        function getFixedHeaderOffset() {
            let total = 0;
            const stack = [];
            const header = document.querySelector('header.navbar.sticky-top, header.navbar.fixed-top');
            if (header) stack.push(header);
            const mgmt = document.getElementById('navbarManagement');
            if (mgmt && (mgmt.classList.contains('sticky-top') || mgmt.classList.contains('fixed-top'))) stack.push(mgmt);
            document.querySelectorAll('.navbar.sticky-top, .navbar.fixed-top').forEach(el => { if (!stack.includes(el)) stack.push(el); });
            stack.forEach(el => { const h = el.offsetHeight || el.getBoundingClientRect().height || 0; total += Math.max(0, Math.round(h)); });
            return total;
        }

        function loadScript(src, id) {
            return new Promise((resolve, reject) => {
                if (id && document.getElementById(id)) return resolve();
                const s = document.createElement('script');
                if (id) s.id = id;
                s.src = src;
                s.onload = resolve;
                s.onerror = reject;
                document.head.appendChild(s);
            });
        }
        function loadCss(href, id) {
            return new Promise((resolve) => {
                if (id && document.getElementById(id)) return resolve();
                const l = document.createElement('link');
                if (id) l.id = id;
                l.rel = 'stylesheet';
                l.href = href;
                l.onload = resolve;
                document.head.appendChild(l);
            });
        }

        function ensureFixedHeaderAssets() {
            const hasFH = !!($.fn.dataTable && $.fn.dataTable.FixedHeader);
            if (hasFH) return Promise.resolve();
            return Promise.all([
                loadScript('https://cdn.jsdelivr.net/npm/datatables.net-fixedheader@3.4.0/js/dataTables.fixedHeader.min.js', 'dt-fixedheader'),
                loadCss('https://cdn.jsdelivr.net/npm/datatables.net-fixedheader-bs5@3.4.0/css/fixedHeader.bootstrap5.min.css', 'dt-fixedheader-css')
            ]).catch(() => {});
        }

        function initTable() {
            $('#enrollmentTable').DataTable({
                pageLength: 100,
                lengthMenu: [10, 25, 50, 100],
                stateSave: true,
                order: [[0, 'asc']],
                columnDefs: [
                    { targets: [1, 2, 3], searchable: false }
                ],
                fixedHeader: {
                    header: true,
                    headerOffset: getFixedHeaderOffset()
                }
            });
        }

        if ($.fn.dataTable && $.fn.dataTable.FixedHeader) {
            initTable();
        } else {
            ensureFixedHeaderAssets().then(() => initTable()).catch(() => initTable());
        }
    });
</script>
<?= $this->endSection() ?>
