<?= $this->extend('layout/main_layout') ?>
<?= $this->section('styles') ?>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.10/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.10/css/dataTables.bootstrap5.min.css">
<?= $this->endSection() ?>
<?= $this->section('content') ?>

<style>
    /* Keep header centered and wide */
    .class-header {
        max-width: 800px;
    }

    /* Make the table span the page width and avoid unexpected shrinking */
    .fullwidth-wrap {
        width: 100%;
    }

    /* DataTables: keep width and allow horizontal scroll area to use full width */
    table.dataTable {
        width: 100% !important;
        white-space: nowrap; /* prevent wrapping that makes table look narrow */
    }

    .dataTables_wrapper .dataTables_scrollHeadInner,
    .dataTables_wrapper .dataTables_scrollHeadInner table {
        width: 100% !important;
    }

    th, td {
        vertical-align: middle !important;
        font-family: Arial, sans-serif;
    }

    .table thead th {
        background-color: #f8f9fa;
        font-weight: bold;
    }
</style>

<div class="container-fluid py-5">
    <?php $activeClassId = (int)($active_class_id ?? $class_section_id ?? 0); ?>

    <?php if (!empty($classes) && is_array($classes)): ?>
        <?php foreach ($classes as $index => $class): ?>
            <?php
            $sectionId   = $class['class_section_id'];
            $mains = $assignedNames[$sectionId]['mains'] ?? [];
            $tas   = $assignedNames[$sectionId]['tas']   ?? [];
            ?>

            <!-- Full-width table area (title + table) -->
            <div class="fullwidth-wrap px-3 px-md-4 mb-5 class-block <?= ((int)$sectionId === $activeClassId) ? '' : 'd-none'; ?>"
                 data-class-section-id="<?= (int)$sectionId; ?>">
                <div class="class-header text-center mx-auto mb-4">
                    <h4 class="text-dark" style="font-family: Arial, sans-serif;">Students Class List</h4>
                    <?php if (!empty($mains)): ?>
                        <h5 class="text-dark" style="font-family: Arial, sans-serif; margin-bottom: 5px;">
                            Teachers: <?= esc(implode(', ', $mains)); ?>
                        </h5>
                    <?php endif; ?>
                    <?php if (!empty($tas)): ?>
                        <h5 class="text-dark" style="font-family: Arial, sans-serif; margin-bottom: 5px;">
                            Teacher Assistants: <?= esc(implode(', ', $tas)); ?>
                        </h5>
                    <?php endif; ?>
                    <h5 class="text-dark" style="font-family: Arial, sans-serif; margin-bottom: 5px;">
                        Grade-Section: <?= esc($class['class_section_name']); ?>
                    </h5>
                </div>
                <div class="table-responsive"> <!-- gives horizontal scroll on small screens -->
                    <table id="classTable<?= $index ?>" class="table table-bordered table-striped w-100">
                        <thead class="table-light">
                            <tr>
                                <th class="text-center">#</th>
                                <th>School ID</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th class="text-center">Age</th>
                                <th class="text-center">New Student</th>
                                <th class="text-center">Take Photo</th>
                                <th class="text-center">Allergies</th>
                                <th class="text-center">Medical Conditions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($studentsData[$sectionId])): ?>
                                <?php $order = 1; ?>
                                <?php foreach ($studentsData[$sectionId] as $student): ?>
                                    <tr>
                                        <td class="text-center"><?= esc($order++); ?></td>
                                        <td><?= esc($student['school_id']); ?></td>
                                        <td>
                                            <a href="#"
                                               class="text-decoration-none"
                                               data-family-student-id="<?= (int) ($student['student_id'] ?? 0); ?>">
                                                <?= esc($student['firstname']); ?>
                                            </a>
                                        </td>
                                        <td>
                                            <a href="#"
                                               class="text-decoration-none"
                                               data-family-student-id="<?= (int) ($student['student_id'] ?? 0); ?>">
                                                <?= esc($student['lastname']); ?>
                                            </a>
                                        </td>
                                        <td class="text-center"><?= esc($student['age']); ?></td>
                                        <td class="text-center">
                                            <?php if ((int)($student['is_new'] ?? 0) === 1): ?>
                                                <span class="badge bg-warning text-dark">Yes</span>
                                            <?php else: ?>
                                                <span class="badge bg-success">No</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <?php if ((int)($student['photo_consent'] ?? 0) === 1): ?>
                                                <span class="badge bg-success">Yes</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">No</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge <?= (!empty($student['allergies_text']) && strtolower($student['allergies_text']) !== 'none')
                                                                    ? 'bg-warning text-dark'
                                                                    : 'bg-success'; ?>">
                                                <?= esc($student['allergies_text'] ?: 'None'); ?>
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge <?= (!empty($student['medical_conditions_text']) && strtolower($student['medical_conditions_text']) !== 'none')
                                                                    ? 'bg-warning text-dark'
                                                                    : 'bg-success'; ?>">
                                                <?= esc($student['medical_conditions_text'] ?: 'None'); ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
        <?php endforeach; ?>
    <?php else: ?>
        <div class="container">
            <div class="alert alert-warning" role="alert">
                No classes found for this teacher.
            </div>
        </div>
    <?php endif; ?>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script src="https://cdn.datatables.net/1.13.10/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.10/js/dataTables.bootstrap5.min.js"></script>
<script>
    $(document).ready(function() {
        if (!(window.jQuery && jQuery.fn && jQuery.fn.DataTable)) {
            return;
        }
        <?php if (!empty($classes)): ?>
            <?php foreach ($classes as $index => $class): ?>
                const table<?= $index ?> = $('#classTable<?= $index ?>');
                const expectedColumns<?= $index ?> = table<?= $index ?>.find('thead th').length;
                const hasInvalidRows<?= $index ?> = table<?= $index ?>.find('tbody tr').toArray().some(function(row) {
                    return $(row).children('td, th').length !== expectedColumns<?= $index ?>;
                });
                if (hasInvalidRows<?= $index ?>) {
                    return;
                }
                table<?= $index ?>.DataTable({
                    // Keep columns visible and avoid squeezing
                    responsive: false,      // prevent column hiding that can make table look small
                    autoWidth: true,        // let DT calculate widths, we'll still force 100% via CSS
                    scrollX: true,          // allow horizontal scroll when needed
                    pageLength: 25,
                    lengthChange: false,
                    language: {
                        emptyTable: 'No students found in this class.'
                    },
                    columnDefs: [
                        { targets: '_all', className: 'text-nowrap' } // avoid wrapping labels
                    ]
                })
                .columns.adjust(); // finalize widths after init
            <?php endforeach; ?>
        <?php endif; ?>
    });
</script>
<?= $this->endSection() ?>
