<?php
$isEditable = isset($isEditable) ? (bool) $isEditable : true;
$selectedYear = trim((string) ($selectedYear ?? ''));
$disableStudentBtn = count($existingKids) >= $maxChilds;
$disableEmergencyBtn = count($emergencies) >= $maxEmergency;
?>

<?= $this->extend('layout/main_layout') ?>
<?= $this->section('content') ?>
<div class="container my-5">
    <h3 class="text-center text-success mb-3" style="font-family: Arial, sans-serif;">Student Registration</h3>
    <?php if ($selectedYear !== ''): ?>
        <div class="text-center text-muted mb-3">School year: <?= esc($selectedYear) ?></div>
    <?php endif; ?>
    <?php if (!$isEditable): ?>
        <div class="alert alert-warning">
            This school year is read-only. Switch to the active school year to register or edit students.
        </div>
    <?php endif; ?>
    <?php if ($disableStudentBtn): ?>
        <div class="alert alert-info mt-2">You've reached the maximum number of students (<?= $maxChilds ?>).</div>
    <?php endif; ?>
    <?php if ($disableEmergencyBtn): ?>
        <!-- <div class="alert alert-info mt-2">You've reached the maximum number of emergency contacts (<?= esc((string) $maxEmergency) ?>).</div> -->
    <?php endif; ?>
    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger">
            <?= esc(session()->getFlashdata('error')) ?>
        </div>
    <?php endif; ?>
    <?php if (session('errors')): ?>
        <div class="alert alert-danger">
            <ul>
                <?php foreach (session('errors') as $error): ?>
                    <li><?= esc($error) ?></li>
                <?php endforeach ?>
            </ul>
        </div>
    <?php endif; ?>
    <?php
    // Check if at least one student is not enrolled
    $hasUnenrolled = false;
    foreach ($existingKids as $kid) {
        if ($kid['enrollment'] == 0) {
            $hasUnenrolled = true;
            break;
        }
    }
    ?>

    <?php if ($hasUnenrolled): ?>
        <div class="p-3 mb-4 border border-danger rounded bg-light text-center">
            <h5 class="text-danger mb-2">
                ⚠ Please ensure that all of your students are enrolled.
            </h5>
            <p class="mb-3">
                Please complete their enrollment using the button below to ensure they are able to attend classes.
            </p>
            <a href="<?= base_url('/parent/enroll_classes') ?>"
                class="btn btn-lg btn-success bi bi-pencil-square"
                data-bs-toggle="tooltip"
                data-bs-placement="bottom"
                title="Enroll registered students in their appropriate grade level or course.">
                Enroll in Classes
            </a>
        </div>
    <?php endif; ?>
    <?php if (!empty($existingKids)): ?>
        <h5>Student Information</h5>
        <table class="table table-bordered">
            <thead class="table-light">
                <tr>
                    <th>School ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>DOB</th>
                    <th>Grade</th>
                    <th>Medical Conditions</th>
                    <th>Allergies</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($existingKids as $kid): ?>
                    <tr>
                        <td><?= esc($kid['school_id']) ?></td>
                        <td><?= esc($kid['firstname']) ?></td>
                        <td><?= esc($kid['lastname']) ?></td>
                        <td><?= esc((new DateTime($kid['dob']))->format('m-d-Y')) ?></td>
                        <td><?= esc($kid['registration_grade']) ?></td>
                        <td>
                            <?php
                            $mc = is_array($kid['medical_conditions'] ?? null)
                                ? $kid['medical_conditions']
                                : (strlen($kid['medical_conditions'] ?? '') > 0
                                    ? array_map('trim', explode(',', $kid['medical_conditions']))
                                    : ['N/A']);
                            // Escape each item, then join with real <br> (not escaped)
                            echo implode('<br>', array_map('esc', $mc));
                            ?>
                        </td>
                        <td>
                            <?php
                            $al = is_array($kid['allergies'] ?? null)
                                ? $kid['allergies']
                                : (strlen($kid['alalergies'] ?? '') > 0
                                    ? array_map('trim', explode(',', $kid['allergies']))
                                    : ['N/A']);
                            echo implode('<br>', array_map('esc', $al));
                            ?>
                        </td>
                        <td class="text-center">
                            <?php if ($isEditable && $kid['enrollment'] == 0): ?>
                                <form action="<?= base_url('/parent/delete_student/' . $kid['id']) ?>"
                                    method="post"
                                    style="display:inline">
                                    <?= csrf_field() ?>
                                    <button
                                        type="button"
                                        class="btn btn-sm btn-outline-danger"
                                        aria-label="Delete this student"
                                        title="Delete this student"
                                        onclick="if (confirm('Are you sure you want to delete this student?')) { this.closest('form').submit(); }">
                                        <i class="fas fa-trash" aria-hidden="true"></i>
                                        <span class="ms-1">Delete</span>
                                    </button>
                                </form>
                            <?php else: ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary" disabled title="<?= $isEditable ? 'Student is already enrolled' : 'This school year is read-only' ?>">
                                    <i class="fas fa-ban"></i> Delete
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php $student = $kid; ?>
                    <?php include(APPPATH . 'Views/parent/edit_student_modal.php'); ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <?php if (!empty($emergencies)): ?>
        <h5 class="mt-4">Emergency Contacts</h5>
        <table class="table table-bordered">
            <thead class="table-light">
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone</th>
                    <th>Relation</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($emergencies as $contact): ?>
                    <?php
                    $fullName = $contact['emergency_contact_name'] ?? '';
                    $nameParts = explode(' ', trim($fullName), 2);
                    $firstName = $nameParts[0] ?? '';
                    $lastName = $nameParts[1] ?? '';
                    ?>
                    <tr>
                        <td><?= esc($firstName) ?></td>
                        <td><?= esc($lastName) ?></td>
                        <td><?= esc($contact['cellphone']) ?></td>
                        <td><?= esc($contact['relation']) ?></td>
                    </tr>
                    <?php include(APPPATH . 'Views/parent/edit_emergency_contact.php'); ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
    <?php
    $today = local_date(utc_now(), 'Y-m-d');
    $disableDueToDate = ($today >= $lastDayOfRegistration);
    $disableAll = $disableStudentBtn || $disableDueToDate || ! $isEditable;
    ?>
    <form action="<?= base_url('/parent/register_student/save') ?>"
        method="post"
        id="studentRegistrationForm"
        data-max-students="<?= $maxChilds ?>"
        data-existing-students="<?= count($existingKids) ?>"
        data-max-emergency="<?= $maxEmergency ?>"
        data-existing-emergencies="<?= count($emergencies) ?>">
        <?= csrf_field() ?>

        <div id="studentFormsContainer"></div>
        <div id="emergencyFormsContainer"></div>

        <div class="text-center mb-3" id="initialButtons">
            <button type="button"
                class="btn btn-outline-primary me-2 <?= $disableAll ? 'disabled' : '' ?>"
                id="addStudentBtn"
                title="<?php
                        if ($disableStudentBtn) {
                            echo "Maximum of $maxChilds students reached.";
                        } elseif (!$isEditable) {
                            echo "This school year is read-only.";
                        } elseif ($disableDueToDate) {
                            echo "Registration is closed after $lastDayOfRegistration.";
                        }
                        ?>"
                <?= $disableAll ? 'disabled' : '' ?>>
                <i class="fas fa-user-plus"></i> Add Student
            </button>
        </div>

        <div class="text-center mb-3 d-none" id="formActionButtons">
            <button type="button"
                class="btn btn-outline-primary me-2 <?= $disableAll ? 'disabled' : '' ?>"
                id="addAnotherStudentBtn"
                title="<?php
                        if ($disableStudentBtn) {
                            echo "Maximum of $maxChilds students reached.";
                        } elseif (!$isEditable) {
                            echo "This school year is read-only.";
                        } elseif ($disableDueToDate) {
                            echo "Registration is closed after $lastDayOfRegistration.";
                        }
                        ?>"
                <?= $disableAll ? 'disabled' : '' ?>>
                <i class="fas fa-user-plus"></i> Add Another Student
            </button>

            <button type="button"
                class="btn btn-outline-primary me-2"
                id="doneWithStudentBtn">
                <i class="fas fa-check"></i> Done With Student(s)
            </button>

            <button type="submit" class="btn btn-success d-none" id="saveFormBtn">
                <i class="fas fa-save"></i> Save
            </button>
        </div>
    </form>

    <!-- Picture Policy Modal -->
    <div class="modal fade" id="picturePolicyModal" tabindex="-1" aria-labelledby="picturePolicyModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-success" id="picturePolicyModalLabel">Picture & Media Agreement</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" style="white-space: pre-wrap;">
                    <?php
                    $picturePolicy = include(APPPATH . 'Views/policy/picture_policy_partial.php');
                    $sections = $picturePolicy['sections'] ?? [];
                    $title = $picturePolicy['title'] ?? '';
                    ?>
                    <h3 class="text-success"><?= esc($title) ?></h3>
                    <?php if (!empty($sections)): ?>
                        <?php foreach ($sections as $section): ?>
                            <h4 class="mt-4"><?= esc($section['heading']) ?></h4>

                            <?php if (isset($section['subsections'][0])): ?>
                                <?php foreach ($section['subsections'] as $sub): ?>
                                    <?php if (!empty($sub['title'])): ?>
                                        <h5><?= esc($sub['title']) ?></h5>
                                    <?php endif; ?>
                                    <p><?= nl2br(esc($sub['body'] ?? '')) ?></p>
                                <?php endforeach; ?>
                            <?php elseif (isset($section['subsections']['body'])): ?>
                                <p><?= nl2br(esc($section['subsections']['body'])) ?></p>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-outline-primary" onclick="window.print()">Print</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Hidden Templates -->
<div id="studentFormTemplate" class="d-none">
    <?= view('partials/student_form') ?>
</div>

<div id="emergencyFormTemplate" class="d-none">
    <?= view('partials/emergencycontact_form') ?>
</div>

<?php
$tz = new DateTimeZone((string) (config('School')->attendance['timezone'] ?? user_timezone()));

$now     = new DateTime('now', $tz);
$closeAt = new DateTime($lastDayOfRegistration . ' 00:00:00', $tz);

// Closed at the start of the close date
$disableDueToDate = ($now >= $closeAt);

// Last usable calendar day (date - 1)
$lastDayFmt = (clone $closeAt)->modify('-1 day')->format('m-d-Y');

// Also prepare a precise closing moment string
$closeAtFmt24 = $closeAt->format('m-d-Y H:i T');   // e.g., 10-01-2025 00:00 EDT
$closeAtFmt12 = $closeAt->format('m-d-Y g:i A T'); // e.g., 10-01-2025 12:00 AM EDT
?>



<?php if ($disableDueToDate): ?>
    <!-- Registration Closed Modal -->
    <div class="modal fade" id="regClosedModal" tabindex="-1" aria-labelledby="regClosedModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-danger">
                <div class="modal-header">
                    <h5 class="modal-title text-danger" id="regClosedModalLabel">Registration & Enrollment Closed</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    Registration/enrollment is over for this school year.<br>
                    <strong>Last day:</strong> <?= esc($lastDayFmt) ?> (until 11:59 PM)<br>
                    <strong>Closed at:</strong> <?= esc($closeAtFmt24) ?> <!-- or <?= esc($closeAtFmt12) ?> -->
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Optional inline banner as well -->
    <div class="alert alert-danger d-flex align-items-center my-3" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-2"></i>
        <div>
            Registration/enrollment is closed.<br>
            Last day to register was <strong><?= esc($lastDayFmt) ?></strong> (until <strong>11:59 PM</strong>).<br>
            It closed at <strong><?= esc($closeAtFmt24) ?></strong> <!-- or <?= esc($closeAtFmt12) ?> -->
        </div>
    </div>
<?php endif; ?>

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

<?= $this->section('scripts') ?>
<?php if ($disableDueToDate): ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var modalEl = document.getElementById('regClosedModal');
            if (modalEl && window.bootstrap) {
                var m = new bootstrap.Modal(modalEl);
                m.show();
            }
        });
    </script>
<?php endif; ?>

<script>
    window.appConfig = {
        registrationAgeDeadline: "<?= esc($registrationAgeDeadline) ?>"
    };
</script>
<!-- Only keep the script imports -->
<script type="module" src="/assets/js/name_validation.js"></script>
<script type="module" src="/assets/js/age_validation.js"></script>
<script type="module" src="/assets/js/phone_validation.js"></script>
<script type="module" src="/assets/js/validate_student.js"></script>

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