<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="wrapper">
        <div class="content">
            <h2 class="text-center mt-4 mb-3">Parent Profiles</h2>
            <table id="myTable" class="display table table-striped table-bordered align-middle" style="width:100%">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email Address</th>
                        <th>Phone Number</th>
                        <th>Gender</th>
                        <th>Registration Date</th>
                        <th>Students</th>
                    </tr>
                </thead>
             <tbody>
    <?php if (!empty($parents)): ?>
        <?php foreach ($parents as $parent): ?>
            <?php 
                // 1. Check if the students array is empty or doesn't exist
                // If it is empty, 'continue' skips the entire <tr> for this parent
                if (empty($parent['students'])) {
                    continue; 
                }
            ?>
            <tr>
                <td><?= esc($parent['school_id']) ?></td>
                <td>
                    <a href="#" class="text-decoration-none" data-family-guardian-id="<?= (int)($parent['id'] ?? 0) ?>">
                        <?= esc($parent['firstname']) ?>
                    </a>
                </td>
                <td>
                    <a href="#" class="text-decoration-none" data-family-guardian-id="<?= (int)($parent['id'] ?? 0) ?>">
                        <?= esc($parent['lastname']) ?>
                    </a>
                </td>
                <td><?= esc($parent['email']) ?></td>
                <td><?= esc($parent['cellphone']) ?></td>
                <td><?= esc($parent['gender']) ?></td>
                <td><?= esc(local_date($parent['created_at'], 'm-d-Y')) ?></td>
                <td>
                    <ul class="list-unstyled mb-0">
                        <?php foreach ($parent['students'] as $student): ?>
                            <li><?= esc($student['name']) ?> (<?= esc($student['class_section']) ?>)</li>
                        <?php endforeach; ?>
                    </ul>
                </td>
            </tr>
        <?php endforeach; ?>
    <?php else: ?>
        <tr><td colspan="8" class="text-center">No parent profiles found.</td></tr>
    <?php endif; ?>
</tbody>
                <tfoot>
                    <tr>
                        <th colspan="8" class="text-end"></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
$(document).ready(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 initTable(){
        $('#myTable').DataTable({
            responsive: true,
            pageLength: 100,
            lengthMenu: [5, 10, 25, 50, 100],
            order: [[6, 'desc']], // Registration Date desc
            dom: 'Bfrtip',
            buttons: [
                { extend: 'csv',  title: 'parent_profiles' },
                { extend: 'excel',title: 'parent_profiles' },
                { extend: 'pdf',  title: 'parent_profiles', orientation: 'landscape', pageSize: 'A4' },
                { extend: 'print',title: 'Parent Profiles' }
            ],
            columnDefs: [
                { targets: [7], className: 'text-center' }
            ],
            fixedHeader: {
                header: true,
                headerOffset: getFixedHeaderOffset()
            }
        });
    }

    const hasFH = $.fn.dataTable && $.fn.dataTable.FixedHeader;
    if (hasFH) {
        initTable();
    } else {
        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')
        ]).then(()=>initTable()).catch(()=>initTable());
    }
});
</script>
<?= $this->endSection() ?>
