<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
  $classes = $classes ?? [];
  $entries = $entries ?? [];
  $subjectLabels = $subjectLabels ?? [];
  $editEntry = $editEntry ?? null;
?>

<div class="container-fluid">
  <div class="d-flex flex-wrap align-items-center justify-content-between mb-3 gap-2">
    <div>
      <h2 class="mb-1">Subject Curriculum</h2>
      <p class="text-muted mb-0">Add, update, or remove the unit/surah targets that teachers use when reporting class progress.</p>
    </div>
    <a href="<?= site_url('administrator/class_assignment') ?>" class="btn btn-outline-secondary btn-sm">Back to class list</a>
  </div>

  <?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
  <?php endif; ?>
  <?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
  <?php endif; ?>
  <?php if (session()->getFlashdata('errors')): ?>
    <div class="alert alert-danger">
      <ul class="mb-0">
        <?php foreach (session()->getFlashdata('errors') as $error): ?>
          <li><?= esc($error) ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <div class="row g-4">
    <div class="col-lg-5">
      <div class="card shadow-sm">
        <div class="card-header bg-white">
          <h5 class="mb-0">Add new curriculum entry</h5>
        </div>
        <div class="card-body">
          <form action="<?= site_url('administrator/subject-curriculum/save') ?>" method="post">
            <?= csrf_field() ?>
            <div class="mb-3">
              <label class="form-label">Class</label>
              <select name="class_id" class="form-select" required>
                <option value="">Select a class</option>
                <?php foreach ($classes as $class): ?>
                  <option value="<?= esc($class['id']) ?>"
                    <?= set_select('class_id', $class['id'], false) ?>>
                    <?= esc($class['class_name'] ?? 'Unnamed') ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">Subject</label>
              <select name="subject" class="form-select" required>
                <?php foreach ($subjectLabels as $key => $label): ?>
                  <option value="<?= esc($key) ?>" <?= set_select('subject', $key, $key === 'islamic') ?>>
                    <?= esc($label) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">Unit / Term number</label>
              <input type="number" name="unit_number" class="form-control" placeholder="Optional" value="<?= set_value('unit_number') ?>">
              <div class="form-text text-muted small">Leave blank for Quran/Arabic entries that only need a chapter/surah.</div>
            </div>
            <div class="mb-3">
              <label class="form-label">Unit title</label>
              <input type="text" name="unit_title" class="form-control" placeholder="Optional summary" value="<?= set_value('unit_title') ?>">
            </div>
            <div class="mb-3">
              <label class="form-label">Chapter / Surah</label>
              <input type="text" name="chapter_name" class="form-control" required value="<?= set_value('chapter_name') ?>">
            </div>
            <button type="submit" class="btn btn-primary w-100">Save curriculum entry</button>
          </form>
        </div>
      </div>

      <?php if ($editEntry): ?>
        <div class="card shadow-sm mt-4">
          <div class="card-header bg-white">
            <h5 class="mb-0">Edit entry</h5>
          </div>
          <div class="card-body">
            <form action="<?= site_url('administrator/subject-curriculum/update/' . $editEntry['id']) ?>" method="post">
              <?= csrf_field() ?>
              <div class="mb-3">
                <label class="form-label">Class</label>
                <select name="class_id" class="form-select" required>
                  <?php foreach ($classes as $class): ?>
                    <?php
                      $selected = set_select('class_id', $class['id'], ((int)($editEntry['class_id'] ?? 0)) === (int)$class['id']);
                    ?>
                    <option value="<?= esc($class['id']) ?>" <?= $selected ?>>
                      <?= esc($class['class_name'] ?? 'Unnamed') ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="mb-3">
                <label class="form-label">Subject</label>
                <select name="subject" class="form-select" required>
                  <?php foreach ($subjectLabels as $key => $label): ?>
                    <?php
                      $isSelected = set_select('subject', $key, ($editEntry['subject'] ?? '') === $key);
                    ?>
                    <option value="<?= esc($key) ?>" <?= $isSelected ?>>
                      <?= esc($label) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="mb-3">
                <label class="form-label">Unit / Term number</label>
                <input type="number" name="unit_number" class="form-control" placeholder="Optional" value="<?= set_value('unit_number', $editEntry['unit_number'] ?? '') ?>">
              </div>
              <div class="mb-3">
                <label class="form-label">Unit title</label>
                <input type="text" name="unit_title" class="form-control" placeholder="Optional summary" value="<?= set_value('unit_title', $editEntry['unit_title'] ?? '') ?>">
              </div>
              <div class="mb-3">
                <label class="form-label">Chapter / Surah</label>
                <input type="text" name="chapter_name" class="form-control" required value="<?= set_value('chapter_name', $editEntry['chapter_name'] ?? '') ?>">
              </div>
              <div class="d-flex gap-2">
                <button type="submit" class="btn btn-success w-100">Apply changes</button>
                <a href="<?= site_url('administrator/subject-curriculum') ?>" class="btn btn-outline-secondary w-100">Cancel</a>
              </div>
            </form>
          </div>
        </div>
      <?php endif; ?>
    </div>

    <div class="col-lg-7">
      <div class="card shadow-sm">
        <div class="card-header bg-white d-flex align-items-center justify-content-between">
          <h5 class="mb-0">Current curriculum entries</h5>
          <span class="text-muted small"><?= count($entries) ?> record<?= count($entries) === 1 ? '' : 's' ?></span>
        </div>
        <div class="card-body">
          <?php if (empty($entries)): ?>
            <div class="text-center text-muted">No curriculum records yet.</div>
          <?php else: ?>
            <?php
              $entriesByClass = [];
              foreach ($entries as $entry) {
                $className = ($entry['class_name'] ?? '') ?: '—';
                if (!isset($entriesByClass[$className])) {
                  $entriesByClass[$className] = [];
                }
                $entriesByClass[$className][] = $entry;
              }
            ?>
            <div class="accordion" id="curriculumAccordion">
              <?php $accIndex = 0; ?>
              <?php foreach ($entriesByClass as $className => $classEntries): ?>
                <?php
                  $accIndex++;
                  $collapseId = 'curriculum-class-' . $accIndex;
                  $headingId = 'curriculum-heading-' . $accIndex;
                ?>
                <div class="accordion-item mb-2">
                  <h2 class="accordion-header" id="<?= esc($headingId) ?>">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#<?= esc($collapseId) ?>" aria-expanded="false" aria-controls="<?= esc($collapseId) ?>">
                      <?= esc($className) ?>
                      <span class="badge bg-secondary ms-2"><?= count($classEntries) ?> entries</span>
                    </button>
                  </h2>
                  <div id="<?= esc($collapseId) ?>" class="accordion-collapse collapse" aria-labelledby="<?= esc($headingId) ?>" data-bs-parent="#curriculumAccordion">
                    <div class="accordion-body">
                      <div class="table-responsive">
                        <table class="table table-bordered table-hover align-middle mb-0" data-no-mgmt-sticky>
                          <thead class="table-light">
                            <tr>
                              <th>Subject</th>
                              <th>Unit</th>
                              <th>Unit title</th>
                              <th>Chapter / Surah</th>
                              <th>Updated</th>
                              <th style="min-width: 170px;">Actions</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php foreach ($classEntries as $entry): ?>
                              <?php
                                $subjectLabel = $subjectLabels[$entry['subject']] ?? ucfirst($entry['subject'] ?? '');
                                $updatedAt = $entry['updated_at'] ?? $entry['created_at'] ?? '';
                                $updatedDisplay = '';
                                if ($updatedAt) {
                                  try {
                                    $updatedDisplay = (new \DateTime($updatedAt))->format('M d, Y H:i');
                                  } catch (\Exception $e) {
                                    $updatedDisplay = $updatedAt;
                                  }
                                }
                              ?>
                              <tr>
                                <td><?= esc($subjectLabel) ?></td>
                                <td><?= $entry['unit_number'] ? esc((string)$entry['unit_number']) : '—' ?></td>
                                <td><?= esc(($entry['unit_title'] ?? '') ?: '—') ?></td>
                                <td><?= esc(($entry['chapter_name'] ?? '') ?: '—') ?></td>
                                <td><?= esc($updatedDisplay ?: '—') ?></td>
                                <td class="d-flex gap-2 flex-wrap">
                                  <a href="<?= site_url('administrator/subject-curriculum/edit/' . $entry['id']) ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                                  <form action="<?= site_url('administrator/subject-curriculum/delete/' . $entry['id']) ?>" method="post" onsubmit="return confirm('Remove this curriculum entry?');">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
                                  </form>
                                </td>
                              </tr>
                            <?php endforeach; ?>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

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