<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>

<?php $dateLabel = !empty($date) ? local_date($date, 'm-d-Y') : ''; ?>

<div class="container-xxl py-4">
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h2 class="mb-0">Teacher Attendance</h2>
        <div class="d-flex gap-2">
            <a class="btn btn-outline-secondary"
               href="<?= site_url('admin/teacher-attendance/month?date='.urlencode($date).'&semester='.urlencode($semester).'&school_year='.urlencode($schoolYear)) ?>">
               ← Back to Monthly Attendance
            </a>
        </div>
    </div>
    <?php if (session()->getFlashdata('status')): ?>
        <div class="alert alert-success"><?= session()->getFlashdata('status') ?></div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
    <?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">

        
    </div>
    <form class="row gy-2 gx-3 align-items-end mb-3" method="get" action="<?= site_url('admin/teacher-attendance') ?>">
        <div class="col-sm-3">
            <label class="form-label">School Year</label>
            <input type="text" name="school_year" class="form-control" value="<?= esc($schoolYear) ?>" placeholder="e.g. 2025-2026">
        </div>
        <div class="col-sm-2">
            <label class="form-label">Semester</label>
            <input type="text" name="semester" class="form-control" value="<?= esc($semester) ?>" placeholder="Fall">
        </div>
        <div class="col-sm-3">
            <label class="form-label">Date</label>
            <input type="date" name="date" class="form-control" value="<?= esc($date) ?>">
        </div>
        <div class="col-sm-4">
            <label class="form-label">Class Section</label>
            <select name="class_section_id" class="form-select">
                <option value="0">— Choose Section —</option>
                <?php foreach ($sections as $id => $label): ?>
                    <option value="<?= (int)$id ?>" <?= (int)$id === (int)$class_section_id ? 'selected' : '' ?>>
                        <?= esc($label) ?> (ID: <?= (int)$id ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="col-12 d-flex gap-2">
            <button type="submit" class="btn btn-secondary">Load</button>
          
            <?php if ($class_section_id): ?>
                <a class="btn btn-outline-secondary" href="<?= site_url('admin/teacher-attendance') ?>">Reset</a>
            <?php endif; ?>
        </div>
    </form>

    <?php if ($class_section_id): ?>
        <?php if ($locked): ?>
            <div class="alert alert-warning">
                <strong>Note:</strong> Student/section attendance for this day appears to be <em>finalized</em>.
                Admin edits to teacher attendance here are allowed and will not unlock the section.
            </div>
        <?php endif; ?>

        <form method="post" action="<?= site_url('admin/teacher-attendance/save') ?>" id="adminTeacherAttForm">
            <?= csrf_field() ?>
            <input type="hidden" name="class_section_id" value="<?= (int)$class_section_id ?>">
            <input type="hidden" name="date"             value="<?= esc($date) ?>">
            <input type="hidden" name="semester"         value="<?= esc($semester) ?>">
            <input type="hidden" name="school_year"      value="<?= esc($schoolYear) ?>">

            <div class="card shadow-sm">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <strong>Teachers on <?= esc($dateLabel) ?></strong>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-sm btn-outline-success" id="markAllPresent">Mark All Present</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="clearAll">Clear All</button>
                    </div>
                </div>
                <div class="card-body table-responsive">
                    <table id="teacherAttTable" class="table table-bordered table-striped align-middle">
                        <thead class="table-light">
                            <tr>
                                <th class="text-center" style="width:70px;">#</th>
                                <th>Name</th>
                                <th class="text-center" style="width:160px;">Role</th>
                                <th class="text-center" style="width:200px;">Status</th>
                                <th>Reason</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!empty($grid)): ?>
                            <?php $i = 1; foreach ($grid as $row): ?>
                                <?php
                                  $tid   = (int)$row['teacher_id'];
                                  $name  = trim(($row['firstname'] ?? '') . ' ' . ($row['lastname'] ?? '')) ?: ('User#' . $tid);
                                  $pos   = (string)$row['position'];
                                  $stat  = strtolower((string)($row['status'] ?? ''));
                                  $reason= (string)($row['reason'] ?? '');
                                ?>
                                <tr>
                                    <td class="text-center"><?= $i++ ?></td>
                                    <td><?= esc($name) ?></td>
                                    <td class="text-center"><?= esc($pos === 'main' ? 'Main Teacher' : 'Assistant') ?></td>
                                    <td class="text-center">
                                        <input type="hidden" name="teachers[<?= $tid ?>][teacher_id]" value="<?= $tid ?>">
                                        <select name="teachers[<?= $tid ?>][status]" class="form-select form-select-sm status-select">
                                            <option value="">—</option>
                                            <option value="present" <?= $stat === 'present' ? 'selected' : '' ?>>Present</option>
                                            <option value="absent"  <?= $stat === 'absent'  ? 'selected' : '' ?>>Absent</option>
                                            <option value="late"    <?= $stat === 'late'    ? 'selected' : '' ?>>Late</option>
                                        </select>
                                    </td>
                                    <td>
                                        <input type="text"
                                               name="teachers[<?= $tid ?>][reason]"
                                               class="form-control form-control-sm"
                                               placeholder="Optional reason"
                                               value="<?= esc($reason) ?>">
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" class="text-center">No teachers found for this section/term.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <div class="card-footer d-flex justify-content-end">
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </div>
            </div>
        </form>
    <?php endif; ?>
</div>

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

<?= $this->section('scripts') ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
    const markAllBtn = document.getElementById('markAllPresent');
    const clearBtn   = document.getElementById('clearAll');

    if (markAllBtn) {
        markAllBtn.addEventListener('click', () => {
            document.querySelectorAll('#teacherAttTable .status-select').forEach(sel => {
                sel.value = 'present';
            });
        });
    }
    if (clearBtn) {
        clearBtn.addEventListener('click', () => {
            document.querySelectorAll('#teacherAttTable .status-select').forEach(sel => {
                sel.value = '';
            });
            document.querySelectorAll('#teacherAttTable input[name$="[reason]"]').forEach(inp => {
                inp.value = '';
            });
        });
    }
});
</script>

<!-- DataTables (optional) -->
<script>
$(function(){
    $('#teacherAttTable').DataTable({
        paging: false, // usually small set; disable paging for editing
        searching: false,
        info: false,
        order: []
    });
});
</script>
<?= $this->endSection() ?>
