<?php
/**
 * SISPENRA - Laporan Nilai Per Mapel (Kurikulum Merdeka)
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle  = 'Laporan Nilai';
$activeMenu = 'nilai-report';
$pengaturan = getPengaturan();
$ta         = $pengaturan['tahun_ajaran_aktif'];
$sem        = $pengaturan['semester_aktif'];

$kelasId = intval($_GET['kelas_id'] ?? 0);
$mapelId = intval($_GET['mapel_id'] ?? 0);

$kelasList = db_fetchAll(
    "SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas",
    [$ta, $sem]
);

$mapelList = array();
if ($kelasId) {
    $mapelList = db_fetchAll(
        "SELECT * FROM mata_pelajaran WHERE status='aktif' ORDER BY urutan, nama_mapel"
    );
}

$nilaiList     = array();
$selectedKelas = null;
$selectedMapel = null;

if ($kelasId && $mapelId) {
    $selectedKelas = db_fetch("SELECT * FROM kelas WHERE id=?", [$kelasId]);
    $selectedMapel = db_fetch("SELECT * FROM mata_pelajaran WHERE id=?", [$mapelId]);

    $nilaiList = db_fetchAll("
        SELECT s.nis, s.nama, s.jenis_kelamin,
               n.sumatif_1, n.sumatif_2, n.sumatif_3, n.sumatif_4, n.sumatif_5,
               n.rata_sumatif, n.sts, n.sas, n.nilai_akhir, n.catatan
        FROM siswa s
        LEFT JOIN nilai n ON n.siswa_id = s.id
            AND n.mapel_id  = ?
            AND n.kelas_id  = ?
            AND n.tahun_ajaran = ?
            AND n.semester  = ?
        WHERE s.kelas_id = ? AND s.status = 'aktif'
        ORDER BY s.nama
    ", [$mapelId, $kelasId, $ta, $sem, $kelasId]);
}

include '../../templates/header.php';
?>

<!-- Filter -->
<div class="card mb-16">
  <div class="card-body" style="padding:16px 20px;">
    <form method="GET" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;">
      <div style="min-width:180px;flex:1;">
        <label class="form-label">Kelas</label>
        <select name="kelas_id" class="form-control" onchange="this.form.submit()">
          <option value="">-- Pilih Kelas --</option>
          <?php foreach ($kelasList as $k): ?>
          <option value="<?= $k['id'] ?>" <?= $kelasId==$k['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($k['nama_kelas']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($kelasId && !empty($mapelList)): ?>
      <div style="min-width:240px;flex:2;">
        <label class="form-label">Mata Pelajaran</label>
        <select name="mapel_id" class="form-control" onchange="this.form.submit()">
          <option value="">-- Pilih Mata Pelajaran --</option>
          <?php foreach ($mapelList as $m): ?>
          <option value="<?= $m['id'] ?>" <?= $mapelId==$m['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($m['nama_mapel']) ?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">
      <?php endif; ?>
    </form>
  </div>
</div>

<?php if ($kelasId && $mapelId && $selectedKelas && $selectedMapel): ?>

<!-- Info bar -->
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px;">
  <?php foreach ([
      ['fas fa-door-open','Kelas',$selectedKelas['nama_kelas']],
      ['fas fa-book','Mapel',$selectedMapel['nama_mapel']],
      ['fas fa-calendar','TA',$ta.' · Sem '.$sem],
      ['fas fa-users','Siswa',count($nilaiList).' orang'],
  ] as $info): ?>
  <div style="background:#fff;border:1px solid var(--border);border-radius:8px;padding:9px 16px;font-size:13px;">
    <i class="<?= $info[0] ?>" style="color:var(--primary);margin-right:5px;"></i>
    <strong><?= $info[1] ?>:</strong> <?= htmlspecialchars($info[2]) ?>
  </div>
  <?php endforeach; ?>
</div>

<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-table" style="color:var(--primary);margin-right:8px;"></i>
      Daftar Nilai &mdash; <?= htmlspecialchars($selectedMapel['nama_mapel']) ?>
    </span>
    <div style="display:flex;gap:8px;">
      <button onclick="exportTable('nilaiTable','nilai_<?= $kelasId ?>_<?= $mapelId ?>')"
              class="btn btn-outline btn-sm">
        <i class="fas fa-file-csv"></i> Export CSV
      </button>
      <button onclick="window.print()" class="btn btn-accent btn-sm">
        <i class="fas fa-print"></i> Cetak
      </button>
      <a href="<?= BASE_URL ?>/modules/nilai/input.php?kelas_id=<?= $kelasId ?>&mapel_id=<?= $mapelId ?>"
         class="btn btn-primary btn-sm">
        <i class="fas fa-edit"></i> Edit Nilai
      </a>
    </div>
  </div>

  <div style="overflow-x:auto;">
    <table style="width:100%;border-collapse:collapse;font-size:13px;min-width:960px;" id="nilaiTable">
      <thead>
        <tr style="background:var(--primary-dark);color:#fff;">
          <th rowspan="2" style="padding:10px 12px;text-align:left;width:36px;">No</th>
          <th rowspan="2" style="padding:10px 12px;text-align:left;width:80px;">NIS</th>
          <th rowspan="2" style="padding:10px 12px;text-align:left;min-width:160px;">Nama Siswa</th>
          <th rowspan="2" style="padding:10px 8px;text-align:center;width:40px;">L/P</th>
          <th colspan="5" style="padding:8px 12px;text-align:center;background:rgba(255,255,255,.08);border-left:1px solid rgba(255,255,255,.2);">
            Sumatif Lingkup Materi
          </th>
          <th rowspan="2" style="padding:10px 8px;text-align:center;width:78px;background:rgba(255,220,80,.2);border-left:1px solid rgba(255,255,255,.2);">Rata2<br>Sumatif</th>
          <th rowspan="2" style="padding:10px 8px;text-align:center;width:68px;border-left:1px solid rgba(255,255,255,.2);">STS</th>
          <th rowspan="2" style="padding:10px 8px;text-align:center;width:68px;border-left:1px solid rgba(255,255,255,.2);">SAS</th>
          <th rowspan="2" style="padding:10px 8px;text-align:center;width:82px;background:rgba(232,160,32,.25);border-left:2px solid rgba(255,255,255,.3);">Nilai<br>Rapor</th>
          <th rowspan="2" style="padding:10px 8px;text-align:left;min-width:120px;border-left:1px solid rgba(255,255,255,.2);">Catatan</th>
        </tr>
        <tr style="background:var(--primary);color:#fff;">
          <?php for ($i=1;$i<=5;$i++): ?>
          <th style="padding:7px 8px;text-align:center;width:68px;border-left:1px solid rgba(255,255,255,.15);font-size:12px;">S<?= $i ?></th>
          <?php endfor; ?>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($nilaiList)): ?>
        <tr>
          <td colspan="14" style="text-align:center;padding:40px;color:var(--text-muted);">
            <i class="fas fa-inbox" style="font-size:32px;display:block;margin-bottom:10px;opacity:.3;"></i>
            Belum ada data nilai
          </td>
        </tr>
        <?php else: ?>
        <?php
        $totals = array_fill_keys(['s1','s2','s3','s4','s5','rata','sts','sas','akhir'], 0);
        $counts = array_fill_keys(['s1','s2','s3','s4','s5','rata','sts','sas','akhir'], 0);
        $arrAkhir = array();

        foreach ($nilaiList as $idx => $n):
            $adaNilai = $n['nilai_akhir'] !== null;
            for ($i=1;$i<=5;$i++) {
                $k = 'sumatif_'.$i; $tk = 's'.$i;
                if ($n[$k] !== null) { $totals[$tk] += $n[$k]; $counts[$tk]++; }
            }
            if ($n['rata_sumatif'] !== null) { $totals['rata'] += $n['rata_sumatif']; $counts['rata']++; }
            if ($n['sts']         !== null) { $totals['sts']  += $n['sts'];          $counts['sts']++;  }
            if ($n['sas']         !== null) { $totals['sas']  += $n['sas'];          $counts['sas']++;  }
            if ($adaNilai)                  { $totals['akhir']+= $n['nilai_akhir'];  $counts['akhir']++; $arrAkhir[] = $n['nilai_akhir']; }
        ?>
        <tr style="<?= $idx%2===0?'':'background:var(--surface-2);' ?>">
          <td style="padding:8px 12px;color:var(--text-muted);"><?= $idx+1 ?></td>
          <td style="padding:8px 12px;"><code style="font-size:11px;"><?= htmlspecialchars($n['nis']) ?></code></td>
          <td style="padding:8px 12px;font-weight:600;"><?= htmlspecialchars($n['nama']) ?></td>
          <td style="padding:8px 6px;text-align:center;">
            <span class="badge <?= $n['jenis_kelamin']==='L'?'badge-info':'badge-warning' ?>" style="font-size:10px;"><?= $n['jenis_kelamin'] ?></span>
          </td>
          <?php for ($i=1;$i<=5;$i++): $val = $n['sumatif_'.$i]; ?>
          <td style="padding:8px 6px;text-align:center;border-left:1px solid var(--border);">
            <?= $val!==null ? '<span style="font-weight:500;">'.number_format($val,0).'</span>' : '<span style="color:var(--text-light);">-</span>' ?>
          </td>
          <?php endfor; ?>
          <td style="padding:8px 6px;text-align:center;background:#fffbf0;border-left:1px solid var(--border);">
            <?= $n['rata_sumatif']!==null ? '<strong style="color:var(--accent);">'.number_format($n['rata_sumatif'],1).'</strong>' : '<span style="color:var(--text-light);">-</span>' ?>
          </td>
          <td style="padding:8px 6px;text-align:center;border-left:1px solid var(--border);">
            <?= $n['sts']!==null ? number_format($n['sts'],0) : '<span style="color:var(--text-light);">-</span>' ?>
          </td>
          <td style="padding:8px 6px;text-align:center;border-left:1px solid var(--border);">
            <?= $n['sas']!==null ? number_format($n['sas'],0) : '<span style="color:var(--text-light);">-</span>' ?>
          </td>
          <td style="padding:8px 6px;text-align:center;background:#fff8e8;border-left:2px solid var(--accent);">
            <?php if ($adaNilai): ?>
            <span style="font-weight:800;font-size:15px;color:var(--primary);"><?= number_format($n['nilai_akhir'],0) ?></span>
            <?php else: ?><span style="color:var(--text-light);">-</span><?php endif; ?>
          </td>
          <td style="padding:8px 8px;font-size:12px;color:var(--text-muted);border-left:1px solid var(--border);">
            <?= htmlspecialchars($n['catatan'] ?? '') ?>
          </td>
        </tr>
        <?php endforeach; ?>

        <?php if ($counts['akhir'] > 0): ?>
        <tr style="background:var(--bg);border-top:2px solid var(--border);font-weight:600;">
          <td colspan="4" style="padding:9px 12px;text-align:right;font-size:12px;color:var(--text-muted);">
            Rata-rata kelas (<?= $counts['akhir'] ?> siswa):
          </td>
          <?php for ($i=1;$i<=5;$i++): $tk='s'.$i; ?>
          <td style="padding:9px 6px;text-align:center;border-left:1px solid var(--border);">
            <?= $counts[$tk]>0 ? number_format($totals[$tk]/$counts[$tk],1) : '-' ?>
          </td>
          <?php endfor; ?>
          <td style="padding:9px 6px;text-align:center;background:#fffbf0;border-left:1px solid var(--border);color:var(--accent);">
            <?= $counts['rata']>0 ? number_format($totals['rata']/$counts['rata'],1) : '-' ?>
          </td>
          <td style="padding:9px 6px;text-align:center;border-left:1px solid var(--border);">
            <?= $counts['sts']>0 ? number_format($totals['sts']/$counts['sts'],1) : '-' ?>
          </td>
          <td style="padding:9px 6px;text-align:center;border-left:1px solid var(--border);">
            <?= $counts['sas']>0 ? number_format($totals['sas']/$counts['sas'],1) : '-' ?>
          </td>
          <td style="padding:9px 6px;text-align:center;background:#fff8e8;border-left:2px solid var(--accent);">
            <span style="font-size:16px;font-weight:800;color:var(--primary);">
              <?= $counts['akhir']>0 ? number_format($totals['akhir']/$counts['akhir'],1) : '-' ?>
            </span>
          </td>
          <td style="border-left:1px solid var(--border);"></td>
        </tr>
        <?php endif; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <?php if (!empty($arrAkhir)): ?>
  <div style="padding:12px 20px;border-top:1px solid var(--border);background:var(--surface-2);display:flex;gap:24px;flex-wrap:wrap;font-size:13px;align-items:center;">
    <span><i class="fas fa-check-circle" style="color:var(--success);"></i> Terisi: <strong><?= $counts['akhir'] ?>/<?= count($nilaiList) ?></strong></span>
    <span><i class="fas fa-arrow-up" style="color:var(--success);"></i> Tertinggi: <strong><?= number_format(max($arrAkhir),0) ?></strong></span>
    <span><i class="fas fa-arrow-down" style="color:var(--danger);"></i> Terendah: <strong><?= number_format(min($arrAkhir),0) ?></strong></span>
  </div>
  <?php endif; ?>
</div>

<?php elseif ($kelasId && !$mapelId): ?>
<div class="card">
  <div class="card-body" style="text-align:center;padding:48px;color:var(--text-muted);">
    <i class="fas fa-book-open" style="font-size:42px;display:block;margin-bottom:14px;opacity:.3;"></i>
    <p>Pilih mata pelajaran untuk menampilkan daftar nilai.</p>
  </div>
</div>

<?php else: ?>
<div class="card">
  <div class="card-body" style="text-align:center;padding:48px;color:var(--text-muted);">
    <i class="fas fa-chart-bar" style="font-size:42px;display:block;margin-bottom:14px;opacity:.3;"></i>
    <p>Pilih kelas, kemudian pilih mata pelajaran.</p>
  </div>
</div>
<?php endif; ?>

<?php include '../../templates/footer.php'; ?>
