<?php include __DIR__ . '/../../views/layouts/header.php'; ?>
<div class="wrapper">
<?php include __DIR__ . '/../../views/layouts/sidebar.php'; ?>
<div class="main-content">
<?php include __DIR__ . '/../../views/layouts/topbar.php'; ?>

<div class="page-content">

  <!-- Page Header -->
  <div class="page-header d-flex justify-content-between align-items-start flex-wrap gap-2">
    <div>
      <h1><i class="bi bi-journal-text me-2 text-primary"></i>Daftar Nilai</h1>
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/index.php?page=dashboard">Dashboard</a></li>
          <li class="breadcrumb-item"><a href="#">Nilai Rapor</a></li>
          <li class="breadcrumb-item active">Daftar Nilai</li>
        </ol>
      </nav>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <a href="<?= BASE_URL ?>/index.php?page=nilai_input" class="btn btn-primary btn-sm">
        <i class="bi bi-pencil-square me-1"></i> Input Nilai
      </a>
      <a href="<?= BASE_URL ?>/index.php?page=nilai_import" class="btn btn-success btn-sm">
        <i class="bi bi-upload me-1"></i> Import Excel
      </a>
    </div>
  </div>

  <?php if ($flash): ?>
  <div class="alert alert-<?= $flash['type'] ?> alert-dismissible alert-auto-dismiss fade show">
    <i class="bi bi-check-circle-fill me-2"></i><?= e($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
  <?php endif; ?>

  <!-- ===== FILTER ===== -->
  <div class="card mb-3">
    <div class="card-body">
      <form method="GET" id="formFilter" class="row g-3 align-items-end">
        <input type="hidden" name="page" value="nilai">

        <!-- Kelas -->
        <div class="col-12 col-md-4">
          <label class="form-label mb-1">Kelas <span class="text-danger">*</span></label>
          <select class="form-select" name="kelas_id" id="selectKelas"
                  onchange="loadSiswa(this.value)">
            <option value="">-- Pilih Kelas --</option>
            <?php foreach ($kelasList as $k): ?>
            <option value="<?= $k['id'] ?>"
              <?= $kelasId == $k['id'] ? 'selected' : '' ?>>
              <?= e($k['nama_kelas']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Nama Siswa -->
        <div class="col-12 col-md-5">
          <label class="form-label mb-1">Nama Siswa <span class="text-danger">*</span></label>
          <select class="form-select" name="siswa_id" id="selectSiswa">
            <option value="">-- Pilih Siswa --</option>
            <?php foreach ($siswaList as $s): ?>
            <option value="<?= $s['id'] ?>"
              <?= $siswaId == $s['id'] ? 'selected' : '' ?>>
              <?= e($s['nama']) ?> (<?= e($s['nis'] ?? '-') ?>)
            </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Tombol Cari -->
        <div class="col-12 col-md-3">
          <button type="submit" class="btn btn-primary w-100">
            <i class="bi bi-search me-1"></i> Cari
          </button>
        </div>
      </form>
    </div>
  </div>

  <?php if ($siswa && $kelasId): ?>

  <!-- ===== PROFIL SISWA ===== -->
  <div class="card mb-3">
    <div class="card-body">
      <div class="d-flex align-items-center gap-3 flex-wrap">
        <!-- Avatar -->
        <?php if (!empty($siswa['foto'])): ?>
          <img src="<?= BASE_URL ?>/uploads/<?= e($siswa['foto']) ?>"
               class="rounded-circle"
               style="width:64px;height:64px;object-fit:cover;border:3px solid #e2e8f0;flex-shrink:0;">
        <?php else: ?>
          <div style="width:64px;height:64px;border-radius:50%;
                      background:#dbeafe;color:#2563eb;flex-shrink:0;
                      display:flex;align-items:center;justify-content:center;
                      font-size:1.5rem;font-weight:700;border:3px solid #e2e8f0;">
            <?= strtoupper(substr($siswa['nama'], 0, 1)) ?>
          </div>
        <?php endif; ?>

        <!-- Info -->
        <div>
          <table style="font-size:.9rem;border-collapse:collapse;">
            <tr>
              <td style="color:#64748b;padding:2px 12px 2px 0;white-space:nowrap;">Nama Siswa</td>
              <td style="padding:2px 8px 2px 0;">:</td>
              <td class="fw-600"><?= e($siswa['nama']) ?></td>
            </tr>
            <tr>
              <td style="color:#64748b;padding:2px 12px 2px 0;">NIS</td>
              <td style="padding:2px 8px 2px 0;">:</td>
              <td><?= e($siswa['nis'] ?? '-') ?></td>
            </tr>
            <tr>
              <td style="color:#64748b;padding:2px 12px 2px 0;">Kelas</td>
              <td style="padding:2px 8px 2px 0;">:</td>
              <td><?= e($siswa['nama_kelas'] ?? '-') ?></td>
            </tr>
          </table>
        </div>

        <!-- Aksi -->
        <div class="ms-auto d-flex gap-2 flex-wrap">
          <a href="<?= BASE_URL ?>/index.php?page=siswa_detail&id=<?= $siswa['id'] ?>"
             class="btn btn-outline-primary btn-sm">
            <i class="bi bi-eye me-1"></i> Detail Siswa
          </a>
          <?php if (!empty($rekap)): ?>
          <a href="<?= BASE_URL ?>/index.php?page=nilai_export_rekap&siswa_id=<?= $siswa['id'] ?>&kelas_id=<?= $kelasId ?>"
             class="btn btn-success btn-sm no-print">
            <i class="bi bi-file-earmark-excel me-1"></i> Export Excel
          </a>
          <button class="btn btn-outline-secondary btn-sm no-print" onclick="window.print()">
            <i class="bi bi-printer me-1"></i> Cetak
          </button>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- ===== TABEL REKAP NILAI ===== -->
  <div class="card">
    <div class="card-header" style="background:#2563eb;">
      <h6 class="mb-0 text-white">
        <i class="bi bi-table me-2"></i>
        Rekap Nilai Rapor — <?= e($siswa['nama']) ?>
      </h6>
    </div>
    <div class="card-body p-0">

      <?php
      // Cek apakah ada nilai sama sekali
      $adaNilai = false;
      foreach ($rekap as $r) {
          for ($s = 1; $s <= 6; $s++) {
              if ($r['semester'][$s] !== null) { $adaNilai = true; break 2; }
          }
      }
      ?>

      <?php if (!$adaNilai): ?>
        <div class="empty-state py-5">
          <div class="empty-icon">📝</div>
          <h6>Belum ada data nilai</h6>
          <p class="text-muted">Siswa ini belum memiliki nilai rapor yang diinput</p>
          <a href="<?= BASE_URL ?>/index.php?page=nilai_input&kelas_id=<?= $kelasId ?>"
             class="btn btn-primary btn-sm">
            <i class="bi bi-pencil-square me-1"></i> Input Nilai
          </a>
        </div>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table mb-0" id="tabelRekap" style="font-size:.85rem;">
          <thead>
            <!-- Baris 1: header utama -->
            <tr style="background:#1e40af;color:#fff;">
              <th rowspan="2" class="align-middle text-center"
                  style="width:45px;background:#1e40af;color:#fff;border-color:#3b82f6;">No</th>
              <th rowspan="2" class="align-middle"
                  style="min-width:130px;background:#1e40af;color:#fff;border-color:#3b82f6;">
                Mata Pelajaran
              </th>
              <th colspan="6" class="text-center"
                  style="background:#1e40af;color:#fff;border-color:#3b82f6;letter-spacing:.05em;">
                SEMESTER
              </th>
              <th rowspan="2" class="align-middle text-center"
                  style="min-width:85px;background:#1e40af;color:#fff;border-color:#3b82f6;">
                Rata-rata
              </th>
              <th rowspan="2" class="align-middle text-center"
                  style="min-width:90px;background:#1e40af;color:#fff;border-color:#3b82f6;">
                Predikat Akhir
              </th>
            </tr>
            <!-- Baris 2: nomor semester -->
            <tr style="background:#2563eb;color:#fff;">
              <?php for ($s = 1; $s <= 6; $s++): ?>
              <th class="text-center"
                  style="background:#2563eb;color:#fff;border-color:#3b82f6;min-width:65px;">
                <?= $s ?>
              </th>
              <?php endfor; ?>
            </tr>
          </thead>
          <tbody>
            <?php
            $no = 1;
            foreach ($rekap as $r):
              // Skip mapel yang tidak ada nilai sama sekali
              $hasNilai = false;
              for ($s = 1; $s <= 6; $s++) {
                  if ($r['semester'][$s] !== null) { $hasNilai = true; break; }
              }
              if (!$hasNilai) continue;
            ?>
            <tr class="rekap-row">
              <td class="text-center text-muted"><?= $no++ ?></td>
              <td class="fw-600"><?= e($r['nama']) ?></td>
              <?php for ($s = 1; $s <= 6; $s++):
                $val  = $r['semester'][$s];
                $kkm  = (float)$r['kkm'];
                $lulus = ($val !== null && $val >= $kkm);
              ?>
              <td class="text-center
                <?= $val !== null
                    ? ($lulus ? 'fw-600' : 'fw-600')
                    : 'text-muted' ?>"
                  style="<?= $val !== null ? ($lulus ? 'color:#16a34a' : 'color:#dc2626') : '' ?>">
                <?= $val !== null ? number_format((float)$val, 2) : '-' ?>
              </td>
              <?php endfor; ?>
              <!-- Rata-rata -->
              <td class="text-center fw-700"
                  style="<?= $r['rata'] !== null
                    ? ($r['rata'] >= $r['kkm'] ? 'color:#16a34a' : 'color:#dc2626')
                    : '' ?>">
                <?= $r['rata'] !== null ? number_format((float)$r['rata'], 2) : '-' ?>
              </td>
              <!-- Predikat -->
              <td class="text-center">
                <?php if ($r['predikat'] !== '-'): ?>
                <span class="badge <?= [
                    'A' => 'bg-success',
                    'B' => 'bg-primary',
                    'C' => 'bg-warning text-dark',
                    'D' => 'bg-danger'
                ][$r['predikat']] ?? 'bg-secondary' ?>">
                  <?= $r['predikat'] ?>
                </span>
                <?php else: ?>
                <span class="text-muted">-</span>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>

            <!-- ===== BARIS RATA-RATA KESELURUHAN ===== -->
            <tr style="background:#1e3a5f;color:#fff;font-weight:700;">
              <td colspan="2" class="text-end pe-3" style="color:#fff;">
                Rata-rata Keseluruhan
              </td>
              <?php
              $totalRataAkhir = 0;
              $countRataAkhir = 0;
              for ($s = 1; $s <= 6; $s++):
                $rata = $rataPerSmt[$s] ?? null;
                if ($rata !== null) { $totalRataAkhir += $rata; $countRataAkhir++; }
              ?>
              <td class="text-center" style="color:#fff;">
                <?= $rata !== null ? number_format((float)$rata, 2) : '-' ?>
              </td>
              <?php endfor; ?>
              <?php
              $rataAkhir = $countRataAkhir > 0
                  ? round($totalRataAkhir / $countRataAkhir, 2)
                  : null;
              $predAkhir = '-';
              if ($rataAkhir !== null) {
                  if ($rataAkhir >= 90)     $predAkhir = 'A';
                  elseif ($rataAkhir >= 80) $predAkhir = 'B';
                  elseif ($rataAkhir >= 70) $predAkhir = 'C';
                  else                      $predAkhir = 'D';
              }
              ?>
              <td class="text-center fw-700" style="color:#fff;">
                <?= $rataAkhir !== null ? number_format((float)$rataAkhir, 2) : '-' ?>
              </td>
              <td class="text-center" style="color:#fff;">
                <?= $predAkhir ?>
              </td>
            </tr>

          </tbody>
        </table>
      </div>
      <?php endif; ?>

    </div>
  </div>

  <?php elseif ($kelasId && !$siswaId): ?>
  <div class="empty-state card py-5">
    <div class="empty-icon">👨‍🎓</div>
    <p class="text-muted">Pilih <strong>Nama Siswa</strong> lalu klik <strong>Cari</strong></p>
  </div>

  <?php else: ?>
  <div class="empty-state card py-5">
    <div class="empty-icon">📊</div>
    <p class="text-muted">
      Pilih <strong>Kelas</strong> dan <strong>Nama Siswa</strong>
      untuk melihat rekap nilai lengkap
    </p>
  </div>
  <?php endif; ?>

</div><!-- /page-content -->

<?php
$extraJs = '<script>
// Load siswa berdasarkan kelas via AJAX
function loadSiswa(kelasId) {
    var select = document.getElementById("selectSiswa");
    select.innerHTML = \'<option value="">-- Memuat... --</option>\';
    select.disabled = true;

    if (!kelasId) {
        select.innerHTML = \'<option value="">-- Pilih Siswa --</option>\';
        select.disabled = false;
        return;
    }

    fetch("' . BASE_URL . '/index.php?page=nilai_siswa_ajax&kelas_id=" + kelasId)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            select.innerHTML = \'<option value="">-- Pilih Siswa --</option>\';
            data.forEach(function(s) {
                var opt = document.createElement("option");
                opt.value = s.id;
                opt.textContent = s.nama + " (" + (s.nis || "-") + ")";
                select.appendChild(opt);
            });
            select.disabled = false;
        })
        .catch(function() {
            select.innerHTML = \'<option value="">-- Gagal memuat --</option>\';
            select.disabled = false;
        });
}

// Hover effect tabel
document.querySelectorAll(".rekap-row").forEach(function(row) {
    row.addEventListener("mouseenter", function() {
        this.style.background = "#eff6ff";
    });
    row.addEventListener("mouseleave", function() {
        this.style.background = "";
    });
});
</script>';
?>

<?php include __DIR__ . '/../../views/layouts/footer.php'; ?>
</div><!-- /main-content -->
</div><!-- /wrapper -->
