<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?= csrf_meta() ?>
<?php
  use App\Libraries\AttendancePolicy;

  $roleRaw = session()->get('role');
  $roleList = is_array($roleRaw) ? $roleRaw : [$roleRaw];
  $canManage = AttendancePolicy::canManageEarlyDismissals($roleList);
  $signatureByDate = $signatureByDate ?? [];
  $query = $_SERVER['QUERY_STRING'] ?? '';
  $returnUrl = current_url();
  if ($query && strpos($returnUrl, '?') === false) {
    $returnUrl .= '?' . $query;
  }
?>

<div class="container-xxl py-4">
  <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
    <div>
      <h2 class="mb-0">Early Dismissals</h2>
      <small class="text-muted">Parent-submitted early dismissal requests</small>
    </div>
    <?php if ($canManage): ?>
      <a href="<?= site_url('attendance/early-dismissals/new') ?>" class="btn btn-primary">
        <i class="bi bi-plus-circle"></i> Add Early Dismissal
      </a>
    <?php endif; ?>
  </div>

  <form method="get" class="row gy-2 gx-3 align-items-end mb-4">
    <div class="col-md-4">
      <label class="form-label">School Year</label>
      <input type="text" class="form-control"
             name="school_year"
             value="<?= esc($schoolYear ?? ($_GET['school_year'] ?? '')) ?>"
             placeholder="e.g. 2025-2026">
    </div>

    <div class="col-md-3">
      <label class="form-label">Semester</label>
      <?php $semVal = (string)($semester ?? ($_GET['semester'] ?? '')); ?>
      <select name="semester" class="form-select">
        <option value="">All Semesters</option>
        <option value="Fall"   <?= (strcasecmp($semVal, 'Fall') === 0 ? 'selected' : '') ?>>Fall</option>
        <option value="Spring" <?= (strcasecmp($semVal, 'Spring') === 0 ? 'selected' : '') ?>>Spring</option>
      </select>
    </div>

    <div class="col-md-3 d-flex gap-2">
      <button type="submit" class="btn btn-secondary mt-4">Apply</button>
      <a class="btn btn-outline-secondary mt-4" href="<?= site_url('attendance/early-dismissals') ?>">Reset</a>
    </div>
  </form>

  <?php if ($msg = session()->getFlashdata('message')): ?>
    <div class="alert alert-success"><?= $msg ?></div>
  <?php endif; ?>
  <?php if ($err = session()->getFlashdata('error')): ?>
    <div class="alert alert-danger"><?= $err ?></div>
  <?php endif; ?>

  <?php if (empty($groups)): ?>
    <div class="alert alert-info">No early dismissals found for the selected school year<?= $semester ? ' and semester' : '' ?>.</div>
  <?php else: ?>
    <?php foreach ($groups as $date => $rows): ?>
      <?php
        $dateLabel = $date;
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $date)) {
          $dateLabel = date('m-d-Y', strtotime($date));
        }
      ?>
      <div class="card shadow-sm mb-3">
        <div class="card-body">
          <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
            <strong><?= esc($dateLabel) ?></strong>
            <?php if ($date !== 'Unknown'): ?>
              <?php $sig = $signatureByDate[$date] ?? null; ?>
              <div class="d-flex flex-wrap align-items-center gap-2">
                <?php if (!empty($sig['filename'])): ?>
                  <a class="btn btn-sm btn-outline-primary" href="<?= site_url('early-dismissal-signatures/' . $sig['filename']) ?>" target="_blank" rel="noopener">
                    View Signature
                  </a>
                  <?php if (!empty($sig['original_name'])): ?>
                    <span class="small text-muted"><?= esc($sig['original_name']) ?></span>
                  <?php endif; ?>
                <?php else: ?>
                  <span class="small text-muted">No signature uploaded</span>
                <?php endif; ?>

                <?php if ($canManage): ?>
                  <form method="post"
                        action="<?= site_url('attendance/early-dismissals/signature') ?>"
                        enctype="multipart/form-data"
                        class="d-flex flex-wrap align-items-center gap-2">
                    <?= csrf_field() ?>
                    <input type="hidden" name="report_date" value="<?= esc($date) ?>">
                    <input type="hidden" name="school_year" value="<?= esc($schoolYear ?? '') ?>">
                    <input type="hidden" name="semester" value="<?= esc($semester ?? '') ?>">
                    <input type="hidden" name="return_url" value="<?= esc($returnUrl) ?>">
                    <input type="file"
                           name="signature_file"
                           class="form-control form-control-sm"
                           accept=".jpg,.jpeg,.png,.webp,.gif,.pdf"
                           required>
                    <button type="submit" class="btn btn-sm btn-primary">
                      <?= !empty($sig['filename']) ? 'Replace' : 'Upload' ?>
                    </button>
                  </form>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          </div>
        <div class="table-responsive">
          <table class="table table-striped align-middle mb-0 no-mgmt-sticky" data-no-mgmt-sticky="1">
            <thead>
              <tr>
                <th>Student</th>
                <th>Class/Section</th>
                <th>Dismissal Time</th>
                <th>Reason</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($rows as $r): ?>
                <tr>
                  <td><?= esc(($r['firstname'] ?? '') . ' ' . ($r['lastname'] ?? '')) ?></td>
                  <td><?= esc($r['class_section_name'] ?? '—') ?></td>
                  <td><?= !empty($r['dismiss_time']) ? esc(substr($r['dismiss_time'], 0, 5)) : '—' ?></td>
                  <td style="max-width: 420px; white-space: normal;"><?= esc($r['reason'] ?? '') ?></td>
                  <td>
                    <span class="badge bg-<?= ($r['status'] === 'processed'
                        ? 'success'
                        : ($r['status'] === 'seen' ? 'info' : 'secondary')) ?>">
                      <?= esc(ucfirst($r['status'] ?? 'new')) ?>
                    </span>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

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