<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<style>
  .admin-progress-table thead th {
    position: static !important;
    top: auto !important;
    z-index: auto !important;
    background: #f8f9fa;
    white-space: nowrap;
    line-height: 1.2;
    padding-top: .75rem;
    padding-bottom: .75rem;
  }
  .admin-progress-table td {
    vertical-align: top;
  }
  .bg-orange {
    background-color: #fd7e14 !important;
  }
</style>
<div class="container py-4">
  <div class="mb-4 pb-3 border-bottom">
    <div class="d-flex align-items-center justify-content-between">
      <div>
        <h3 class="mb-0">Class Progress Reports</h3>
        <div class="text-muted">Filter by week, class, and status</div>
      </div>
      <div>
        <?php
          $lowProgressSectionIds = $lowProgressSectionIds ?? [];
          $lowProgressQuery = implode(',', $lowProgressSectionIds);
          $lowProgressUrl = base_url('administrator/teacher-submissions');
          $lowProgressParams = [];
          if (!empty($filters['school_year'])) {
            $lowProgressParams['school_year'] = $filters['school_year'];
          }
          if ($lowProgressQuery !== '') {
            $lowProgressParams['low_progress_sections'] = $lowProgressQuery;
          }
          if (!empty($lowProgressParams)) {
            $lowProgressUrl .= '?' . http_build_query($lowProgressParams);
          }
        ?>
        <a
          class="btn btn-sm btn-outline-warning <?= empty($lowProgressSectionIds) ? 'disabled' : '' ?>"
          href="<?= esc($lowProgressUrl) ?>"
          <?= empty($lowProgressSectionIds) ? 'tabindex="-1" aria-disabled="true"' : '' ?>
        >
          Teachers &lt; 50%
        </a>
      </div>
    </div>
  </div>

  <form class="card shadow-sm mb-3" method="get" action="<?= base_url('admin/progress') ?>">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-md-3">
          <label class="form-label">School year</label>
          <select name="school_year" class="form-select">
            <?php foreach (($schoolYears ?? []) as $year): ?>
              <option value="<?= esc($year) ?>" <?= (string)($filters['school_year'] ?? $schoolYear ?? '') === (string)$year ? 'selected' : '' ?>>
                <?= esc($year) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">From</label>
          <input type="date" name="from" class="form-control" value="<?= esc($filters['from'] ?? '') ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">To</label>
          <input type="date" name="to" class="form-control" value="<?= esc($filters['to'] ?? '') ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Class/Section</label>
          <select name="class_section_id" class="form-select">
            <option value="">All</option>
            <?php foreach ($classSections as $cs): ?>
              <option value="<?= esc($cs['class_section_id']) ?>" <?= (isset($filters['class_section_id']) && $filters['class_section_id'] === (string) $cs['class_section_id']) ? 'selected' : '' ?>>
                <?= esc($cs['class_section_name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Status</label>
          <select name="status" class="form-select">
            <option value="">All</option>
            <?php foreach ($statusOptions as $value => $label): ?>
              <option value="<?= esc($value) ?>" <?= (isset($filters['status']) && $filters['status'] === $value) ? 'selected' : '' ?>><?= esc($label) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="d-flex gap-2 mt-3">
        <button class="btn btn-primary" type="submit">Apply</button>
        <a class="btn btn-outline-secondary" href="<?= base_url('admin/progress') ?>">Reset</a>
      </div>
    </div>
  </form>

    <div class="card shadow-sm mt-5">
      <div class="card-body pt-4">
        <?php
          $reportGroupsBySection = $reportGroupsBySection ?? [];
          $subjectSections = $subjectSections ?? [];
          $classSections = $classSections ?? [];
          $sectionStats = $sectionStats ?? [];
          $sectionSubjectCounts = $sectionSubjectCounts ?? [];
          $expectedDays = (int) ($expectedDays ?? 0);
        ?>
        <?php if (empty($classSections)): ?>
          <div class="text-center text-muted py-4">No class sections found.</div>
        <?php else: ?>
          <div class="accordion" id="adminProgressAccordion">
            <?php foreach ($classSections as $index => $cs): ?>
              <?php
                $sectionId = (int) ($cs['class_section_id'] ?? 0);
                $sectionName = $cs['class_section_name'] ?? 'Unknown Section';
                $sectionGroups = $reportGroupsBySection[$sectionId] ?? [];
                $hasReports = ! empty($sectionGroups);
                $collapseId = 'progress-section-' . $sectionId;
                $headingId = 'progress-heading-' . $sectionId;
                $stat = $sectionStats[$sectionId] ?? null;
                $subjectCount = (int) ($sectionSubjectCounts[$sectionId] ?? 0);
                if (! $stat) {
                  if ($expectedDays === 0) {
                    $stat = [
                      'submitted' => 0,
                      'expected' => 0,
                      'percent' => 0,
                      'badgeClass' => 'bg-secondary',
                      'labelClass' => 'text-muted',
                    ];
                  } else {
                    $stat = [
                      'submitted' => 0,
                      'expected' => $expectedDays,
                      'percent' => 0,
                      'badgeClass' => 'bg-danger',
                      'labelClass' => 'text-danger',
                    ];
                  }
                }
                $percentLabel = $expectedDays > 0 ? number_format((float) $stat['percent'], 1) . '%' : 'N/A';
                $submissionLabel = $expectedDays > 0
                  ? ('Submitted: ' . (int) $stat['submitted'] . ' / ' . (int) $expectedDays . ' (' . $percentLabel . ')')
                  : 'Submitted: N/A';
                $subjectLabel = 'Units: ' . $subjectCount;
              ?>
              <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($sectionName) ?>
                    <span class="badge <?= esc($stat['badgeClass']) ?> ms-2"><?= esc($submissionLabel) ?></span>
                    <span class="badge bg-info text-dark ms-2"><?= esc($subjectLabel) ?></span>
                    <?php if ($hasReports): ?>
                      <span class="badge bg-secondary ms-2"><?= count($sectionGroups) ?> weeks</span>
                    <?php endif; ?>
                  </button>
                </h2>
                <div id="<?= esc($collapseId) ?>" class="accordion-collapse collapse" aria-labelledby="<?= esc($headingId) ?>" data-bs-parent="#adminProgressAccordion">
                  <div class="accordion-body">
                    <?php if (! $hasReports): ?>
                      <div class="text-muted">No reports found for this section.</div>
                    <?php else: ?>
                      <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0 admin-progress-table no-mgmt-sticky" data-no-mgmt-sticky>
                          <thead class="table-light">
                            <tr>
                              <th>Week</th>
                              <th>Subjects</th>
                              <th>Teacher</th>
                              <th class="text-end">Action</th>
                            </tr>
                          </thead>
                          <tbody>
                            <?php foreach ($sectionGroups as $group): ?>
                              <?php
                                $weekLabel = $group['week_start'] ? date('M d, Y', strtotime($group['week_start'])) : '-';
                                if (! empty($group['week_end'])) {
                                  $weekLabel .= ' – ' . date('M d, Y', strtotime($group['week_end']));
                                }
                                $reports = $group['reports'] ?? [];
                                $teacherCounts = [];
                                $teacherLatest = [];
                                foreach ($reports as $report) {
                                  $name = trim((string) ($report['teacher_name'] ?? ''));
                                  if ($name === '') {
                                    continue;
                                  }
                                  $teacherCounts[$name] = ($teacherCounts[$name] ?? 0) + 1;
                                  $stamp = (string) ($report['updated_at'] ?? $report['created_at'] ?? '');
                                  if ($stamp !== '' && (!isset($teacherLatest[$name]) || $stamp > $teacherLatest[$name])) {
                                    $teacherLatest[$name] = $stamp;
                                  }
                                }
                                $teacherLabel = '-';
                                if (!empty($teacherCounts)) {
                                  $bestName = '';
                                  $bestCount = -1;
                                  $bestStamp = '';
                                  foreach ($teacherCounts as $name => $count) {
                                    $stamp = $teacherLatest[$name] ?? '';
                                    if ($count > $bestCount || ($count === $bestCount && $stamp > $bestStamp)) {
                                      $bestName = $name;
                                      $bestCount = $count;
                                      $bestStamp = $stamp;
                                    }
                                  }
                                  $teacherLabel = $bestName ?: '-';
                                }
                                $exampleId = $reports ? reset($reports)['id'] : null;
                              ?>
                              <tr>
                                <td><div class="fw-semibold"><?= esc($weekLabel) ?></div></td>
                                <td>
                                  <div class="d-flex flex-column gap-2">
                                    <?php foreach ($subjectSections as $slug => $section): ?>
                                      <?php
                                        $subjectName = $section['db_subject'] ?? $section['label'] ?? $slug;
                                        $report = $reports[$subjectName] ?? null;
                                        $statusTag = $report ? ($report['status_label'] ?? 'Unknown') : 'No entry';
                                        $badgeClass = $report ? 'bg-secondary' : 'bg-light text-muted';
                                      ?>
                                      <div class="border rounded-3 p-2">
                                        <div class="d-flex justify-content-between align-items-center">
                                          <strong class="small mb-0"><?= esc($section['label'] ?? $subjectName) ?></strong>
                                          <span class="badge <?= $badgeClass ?>"><?= esc($statusTag) ?></span>
                                        </div>
                                        <div class="small">
                                          <?php if ($report): ?>
                                            <?= view('admin/partials/class_progress_unit_display', [
                                              'unitTitle' => (string) ($report['unit_title'] ?? ''),
                                              'isQuran' => ($subjectName === 'Quran/Arabic'),
                                              'compact' => true,
                                            ]) ?>
                                          <?php else: ?>
                                            <span class="text-muted">No submission</span>
                                          <?php endif; ?>
                                        </div>
                                      </div>
                                    <?php endforeach; ?>
                                  </div>
                                </td>
                                <td><?= esc($teacherLabel) ?></td>
                                <td class="text-end">
                                  <?php if ($exampleId): ?>
                                    <a class="btn btn-sm btn-outline-primary" href="<?= base_url('admin/progress/view/' . $exampleId) ?>">View</a>
                                  <?php endif; ?>
                                </td>
                              </tr>
                            <?php endforeach; ?>
                          </tbody>
                        </table>
                      </div>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
</div>
<?= $this->endSection() ?>
