<?= $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">Admin 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; ?>

    <!-- Filters -->
    <form class="row gy-2 gx-3 align-items-end mb-3" method="get" action="<?= site_url('admin/admins-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 d-flex gap-2">
            <button type="submit" class="btn btn-secondary">Load</button>
            <a class="btn btn-outline-secondary" href="<?= site_url('admin/admins-attendance') ?>">Reset</a>
        </div>
    </form>

    <!-- Admins grid -->
    <form method="post" action="<?= site_url('admin/admins-attendance/save') ?>" id="adminsAttForm">
        <?= csrf_field() ?>
        <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">
                <div>
                    <strong>Admins on <?= esc($dateLabel) ?></strong>
                    <span class="badge bg-secondary ms-2"><?= is_array($adminsGrid) ? count($adminsGrid) : 0 ?></span>
                </div>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-sm btn-outline-success" id="markAllPresentAdmins">Mark All Present</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="clearAllAdmins">Clear All</button>
                </div>
            </div>

            <div class="card-body table-responsive">
                <?php if (empty($adminsGrid)): ?>
                    <div class="alert alert-info mb-0">No Admin users found for this day/term.</div>
                <?php else: ?>
                    <table id="adminsAttTable" 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:180px;">Role</th>
                            <th class="text-center" style="width:220px;">Status</th>
                            <th>Reason</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php $i=1; foreach ($adminsGrid as $row): ?>
                            <?php
                                $uid    = (int)($row['user_id'] ?? 0);
                                $name   = trim(($row['firstname'] ?? '').' '.($row['lastname'] ?? '')) ?: ('User#'.$uid);
                                $role   = (string)($row['role_name'] ?? 'Admin');
                                $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($role) ?></td>
                                <td class="text-center">
                                    <input type="hidden" name="admins[<?= $uid ?>][user_id]" value="<?= $uid ?>">
                                    <input type="hidden" name="admins[<?= $uid ?>][role_name]" value="<?= esc($role) ?>">
                                    <select name="admins[<?= $uid ?>][status]" class="form-select form-select-sm admin-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="admins[<?= $uid ?>][reason]" class="form-control form-control-sm" placeholder="Optional reason" value="<?= esc($reason) ?>">
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>

            <div class="card-footer d-flex justify-content-end">
                <button type="submit" class="btn btn-primary" <?= empty($adminsGrid) ? 'disabled' : '' ?>>Save Admins Attendance</button>
            </div>
        </div>
    </form>
</div>

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

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

  if (markAll) {
    markAll.addEventListener('click', () => {
      document.querySelectorAll('#adminsAttTable .admin-status-select')
        .forEach(sel => { sel.value = 'present'; });
    });
  }
  if (clearAll) {
    clearAll.addEventListener('click', () => {
      document.querySelectorAll('#adminsAttTable .admin-status-select')
        .forEach(sel => { sel.value = ''; });
      document.querySelectorAll('#adminsAttTable input[name^="admins"][name$="[reason]"]')
        .forEach(inp => { inp.value = ''; });
    });
  }
});
</script>

<script>
$(function(){
    if ($('#adminsAttTable').length) {
        $('#adminsAttTable').DataTable({
            paging: false,
            searching: false,
            info: false,
            order: []
        });
    }
});
</script>
<?= $this->endSection() ?>
