<?php
/**
 * SisPen Snesaka - Input Nilai (Kurikulum Merdeka)
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle   = 'Input Nilai';
$activeMenu  = 'nilai-input';
$pengaturan  = getPengaturan();
$isAdmin     = $_SESSION['role'] === 'admin';
$currentUser = getCurrentUser();
$guruId      = $currentUser['guru_id'] ?? null;
$ta          = $pengaturan['tahun_ajaran_aktif'] ?? '2024/2025';
$semester    = $pengaturan['semester_aktif'] ?? '1';

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

// ---- Formula: ambil dari session override atau global ----
$formulaGlobal = getFormula();

// Reset override jika diminta
if (isset($_GET['reset_formula'])) {
    unset($_SESSION['formula_override']);
    header("Location: input.php?kelas_id=$kelasId&mapel_id=$mapelId"); exit;
}

// Simpan override formula ke session
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_formula_override'])) {
    $rs  = floatval($_POST['fo_rata_sumatif'] ?? 50);
    $sts = floatval($_POST['fo_sts'] ?? 25);
    $sas = floatval($_POST['fo_sas'] ?? 25);
    $js  = intval($_POST['fo_jumlah_sumatif'] ?? 5);
    $total = $rs + $sts + $sas;
    if (abs($total - 100) < 0.01 && $js >= 1 && $js <= 10) {
        $_SESSION['formula_override'] = array(
            'rata_sumatif'   => $rs,
            'sts'            => $sts,
            'sas'            => $sas,
            'jumlah_sumatif' => $js,
        );
        setFlash('success', 'Formula sesi diubah: Rata Sumatif '.$rs.'% + STS '.$sts.'% + SAS '.$sas.'%');
    } else {
        setFlash('danger', 'Total bobot harus 100% dan jumlah sumatif 1-10. Total saat ini: '.$total.'%');
    }
    header("Location: input.php?kelas_id=$kelasId&mapel_id=$mapelId"); exit;
}

// Formula yang digunakan: override sesi atau global
$formulaAktif = isset($_SESSION['formula_override']) ? $_SESSION['formula_override'] : $formulaGlobal;
$isOverride   = isset($_SESSION['formula_override']);
$jsSumatif    = $formulaAktif['jumlah_sumatif'];

// ---- Daftar kelas & mapel sesuai role ----
if ($isAdmin) {
    $kelasList = db_fetchAll("SELECT * FROM kelas WHERE tahun_ajaran=? AND semester=? ORDER BY tingkat, nama_kelas", [$ta, $semester]);
    $mapelList = $kelasId ? db_fetchAll("SELECT * FROM mata_pelajaran WHERE status='aktif' ORDER BY kelompok, urutan") : array();
} else {
    $kelasList = db_fetchAll("SELECT DISTINCT k.* FROM pengampu p JOIN kelas k ON k.id=p.kelas_id WHERE p.guru_id=? AND p.tahun_ajaran=? AND p.semester=? ORDER BY k.nama_kelas", [$guruId, $ta, $semester]);
    $mapelList = $kelasId ? db_fetchAll("SELECT m.* FROM pengampu p JOIN mata_pelajaran m ON m.id=p.mapel_id WHERE p.guru_id=? AND p.kelas_id=? AND p.tahun_ajaran=? AND p.semester=?", [$guruId, $kelasId, $ta, $semester]) : array();
}

// ---- SIMPAN NILAI ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_nilai'])) {
    $nilaiData = isset($_POST['nilai']) ? $_POST['nilai'] : array();
    $savedCount = 0;

    foreach ($nilaiData as $siswaId => $n) {
        // Ambil sumatif sesuai jumlah kolom aktif
        $sumatifs = array();
        for ($i = 1; $i <= $jsSumatif; $i++) {
            $key = 'sumatif_'.$i;
            if (isset($n[$key]) && $n[$key] !== '') {
                $val = floatval($n[$key]);
                $sumatifs[$i] = ($val >= 0 && $val <= 100) ? $val : null;
            } else {
                $sumatifs[$i] = null;
            }
        }
        // Kolom sumatif di atas jumlah = null
        for ($i = $jsSumatif + 1; $i <= 5; $i++) $sumatifs[$i] = null;

        $stsRaw = (isset($n['sts']) && $n['sts'] !== '') ? floatval($n['sts']) : null;
        $sasRaw = (isset($n['sas']) && $n['sas'] !== '') ? floatval($n['sas']) : null;
        $sts = ($stsRaw !== null && $stsRaw >= 0 && $stsRaw <= 100) ? $stsRaw : null;
        $sas = ($sasRaw !== null && $sasRaw >= 0 && $sasRaw <= 100) ? $sasRaw : null;

        // Hitung rata sumatif — hanya jika minimal S1 dan S2 terisi
        $isiSumatif  = array_filter($sumatifs, function($v){ return $v !== null; });
        $adaS1       = isset($sumatifs[1]) && $sumatifs[1] !== null;
        $adaS2       = isset($sumatifs[2]) && $sumatifs[2] !== null;
        $rataSumatif = ($adaS1 && $adaS2 && count($isiSumatif) >= 2)
                       ? round(array_sum($isiSumatif) / count($isiSumatif), 2)
                       : null;

        // Validasi syarat nilai rapor:
        // 1. Minimal 2 sumatif terisi (S1 dan S2)
        // 2. Jika STS/SAS dipakai (>0%), harus terisi
        $jumlahSumatifTerisi = count($isiSumatif);
        $syaratTerpenuhi = true;

        if ($jumlahSumatifTerisi < 2) {
            $syaratTerpenuhi = false;
        }
        if ($formulaAktif['sts'] > 0 && $sts === null) {
            $syaratTerpenuhi = false;
        }
        if ($formulaAktif['sas'] > 0 && $sas === null) {
            $syaratTerpenuhi = false;
        }

        // Hitung nilai rapor pakai formula aktif (hanya jika syarat terpenuhi)
        $nilaiAkhir = $syaratTerpenuhi ? hitungNilaiRapor($sumatifs, $sts, $sas, $formulaAktif) : null;

        // Validasi hasil kalkulasi rata & nilai_akhir — harus dalam range 0-100
        if ($rataSumatif !== null && ($rataSumatif < 0 || $rataSumatif > 100)) {
            $rataSumatif = null;
            $nilaiAkhir  = null;
        }
        if ($nilaiAkhir !== null && ($nilaiAkhir < 0 || $nilaiAkhir > 100)) {
            $nilaiAkhir = null;
        }

        $row = array(
            'sumatif_1'    => $sumatifs[1],
            'sumatif_2'    => $sumatifs[2],
            'sumatif_3'    => $sumatifs[3],
            'sumatif_4'    => isset($sumatifs[4]) ? $sumatifs[4] : null,
            'sumatif_5'    => isset($sumatifs[5]) ? $sumatifs[5] : null,
            'rata_sumatif' => $rataSumatif,
            'sts'          => $sts,
            'sas'          => $sas,
            'nilai_akhir'  => $nilaiAkhir,
            'catatan'      => sanitize(isset($n['catatan']) ? $n['catatan'] : ''),
            'guru_id'      => $guruId ? $guruId : null,
        );

        $existing = db_fetch("SELECT id FROM nilai WHERE siswa_id=? AND mapel_id=? AND kelas_id=? AND tahun_ajaran=? AND semester=?",
            [intval($siswaId), $mapelId, $kelasId, $ta, $semester]);
        if ($existing) {
            db_update('nilai', $row, 'id = :id', array('id' => $existing['id']));
        } else {
            db_insert('nilai', array_merge($row, array(
                'siswa_id' => intval($siswaId), 'mapel_id' => $mapelId,
                'kelas_id' => $kelasId, 'tahun_ajaran' => $ta, 'semester' => $semester,
            )));
        }
        $savedCount++;
    }
    setFlash('success', "Nilai berhasil disimpan untuk $savedCount siswa!");
    header("Location: input.php?kelas_id=$kelasId&mapel_id=$mapelId"); exit;
}

// Ambil siswa & nilai existing
$siswas = $nilaiExisting = array();
if ($kelasId && $mapelId) {
    $siswas = db_fetchAll("SELECT * FROM siswa WHERE kelas_id=? AND status='aktif' ORDER BY nama", [$kelasId]);
    $rows   = db_fetchAll("SELECT * FROM nilai WHERE kelas_id=? AND mapel_id=? AND tahun_ajaran=? AND semester=?", [$kelasId, $mapelId, $ta, $semester]);
    foreach ($rows as $r) $nilaiExisting[$r['siswa_id']] = $r;
}

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

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="flex:1;min-width:180px;">
        <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): ?>
      <div style="flex:2;min-width:220px;">
        <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 && !empty($siswas)): ?>

<!-- Info bar -->
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px;">
  <div style="background:#fff;border:1px solid var(--border);border-radius:8px;padding:9px 16px;font-size:13px;">
    <strong>Kelas:</strong> <?= htmlspecialchars($selectedKelas['nama_kelas']) ?>
  </div>
  <div style="background:#fff;border:1px solid var(--border);border-radius:8px;padding:9px 16px;font-size:13px;">
    <strong>Mapel:</strong> <?= htmlspecialchars($selectedMapel['nama_mapel']) ?>
  </div>
  <div style="background:#fff;border:1px solid var(--border);border-radius:8px;padding:9px 16px;font-size:13px;">
    <strong>TA:</strong> <?= $ta ?> · Sem <?= $semester ?>
  </div>
</div>

<!-- PANEL FORMULA -->
<div style="background:<?= $isOverride ? '#fff8f0' : '#f0faf4' ?>;border:1px solid <?= $isOverride ? '#ffc107' : '#a7d7b8' ?>;border-radius:10px;padding:14px 18px;margin-bottom:16px;">
  <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;">

    <!-- Info formula aktif -->
    <div>
      <div style="font-size:12px;font-weight:700;color:<?= $isOverride ? '#856404' : '#2d7a4f' ?>;margin-bottom:5px;">
        <i class="fas fa-<?= $isOverride ? 'user-edit' : 'cog' ?>"></i>
        Formula <?= $isOverride ? '<span style="background:#ffc107;color:#212529;padding:1px 7px;border-radius:10px;font-size:11px;">OVERRIDE SESI INI</span>' : 'Global (dari Pengaturan Sekolah)' ?>
      </div>
      <div style="font-size:13px;font-family:monospace;color:var(--text);line-height:2.1;">
        Nilai Rapor =
        <span style="background:#e8f5e9;padding:2px 7px;border-radius:4px;">Rata Sumatif × <strong><?= $formulaAktif['rata_sumatif'] ?>%</strong></span>
        + <span style="background:#e3f2fd;padding:2px 7px;border-radius:4px;">STS × <strong><?= $formulaAktif['sts'] ?>%</strong></span>
        + <span style="background:#fff8e1;padding:2px 7px;border-radius:4px;">SAS × <strong><?= $formulaAktif['sas'] ?>%</strong></span>
        &nbsp;|&nbsp; <strong><?= $jsSumatif ?></strong> kolom sumatif
      </div>
    </div>

    <!-- Tombol -->
    <div style="display:flex;gap:8px;flex-shrink:0;align-items:flex-start;">
      <button type="button" onclick="toggleFormulaPanel()"
              class="btn btn-outline btn-sm" id="btnToggleFormula">
        <i class="fas fa-sliders-h"></i> Ubah Formula Sesi Ini
      </button>
      <?php if ($isOverride): ?>
      <a href="?kelas_id=<?= $kelasId ?>&mapel_id=<?= $mapelId ?>&reset_formula=1"
         class="btn btn-outline btn-sm" style="color:var(--danger);border-color:var(--danger);"
         onclick="return confirm('Reset ke formula global?')">
        <i class="fas fa-undo"></i> Reset ke Global
      </a>
      <?php endif; ?>
      <?php if ($isAdmin): ?>
      <a href="<?= BASE_URL ?>/modules/pengaturan.php" class="btn btn-outline btn-sm" target="_blank">
        <i class="fas fa-cog"></i> Pengaturan Global
      </a>
      <?php endif; ?>
    </div>
  </div>

  <!-- Panel Override (hidden by default) -->
  <div id="formulaPanel" style="display:none;margin-top:14px;padding-top:14px;border-top:1px solid <?= $isOverride ? '#ffc107' : '#a7d7b8' ?>;">
    <form method="POST">
      <input type="hidden" name="save_formula_override" value="1">
      <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;">

        <div>
          <label style="font-size:12px;font-weight:700;color:var(--text-muted);display:block;margin-bottom:4px;">
            Jumlah Kolom Sumatif
          </label>
          <div style="display:flex;align-items:center;gap:10px;">
            <input type="range" name="fo_jumlah_sumatif" id="fo_js" min="1" max="10" step="1"
                   value="<?= $formulaAktif['jumlah_sumatif'] ?>"
                   style="flex:1;accent-color:var(--primary);" oninput="updateFoPreview()">
            <span id="fo_lbl_js" style="font-weight:800;font-size:18px;color:var(--primary);min-width:20px;"><?= $formulaAktif['jumlah_sumatif'] ?></span>
          </div>
        </div>

        <div>
          <label style="font-size:12px;font-weight:700;color:var(--success);display:block;margin-bottom:4px;">
            Bobot Rata Sumatif: <span id="fo_lbl_rs"><?= $formulaAktif['rata_sumatif'] ?>%</span>
          </label>
          <input type="range" name="fo_rata_sumatif" id="fo_rs" min="0" max="100" step="5"
                 value="<?= $formulaAktif['rata_sumatif'] ?>"
                 style="width:100%;accent-color:var(--success);" oninput="updateFoPreview()">
        </div>

        <div>
          <label style="font-size:12px;font-weight:700;color:var(--info);display:block;margin-bottom:4px;">
            Bobot STS: <span id="fo_lbl_sts"><?= $formulaAktif['sts'] ?>%</span>
          </label>
          <input type="range" name="fo_sts" id="fo_sts" min="0" max="100" step="5"
                 value="<?= $formulaAktif['sts'] ?>"
                 style="width:100%;accent-color:var(--info);" oninput="updateFoPreview()">
        </div>

        <div>
          <label style="font-size:12px;font-weight:700;color:var(--accent);display:block;margin-bottom:4px;">
            Bobot SAS: <span id="fo_lbl_sas"><?= $formulaAktif['sas'] ?>%</span>
          </label>
          <input type="range" name="fo_sas" id="fo_sas" min="0" max="100" step="5"
                 value="<?= $formulaAktif['sas'] ?>"
                 style="width:100%;accent-color:var(--accent);" oninput="updateFoPreview()">
        </div>
      </div>

      <div id="fo_bobot_status" style="margin-top:10px;padding:8px 12px;border-radius:6px;font-size:13px;font-weight:600;"></div>

      <button type="submit" id="fo_btnSimpan" class="btn btn-warning btn-sm" style="margin-top:10px;">
        <i class="fas fa-check"></i> Terapkan Formula untuk Sesi Ini
      </button>
    </form>
  </div>
</div>

<!-- Tabel input nilai -->
<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-edit" style="color:var(--primary);margin-right:8px;"></i>
      Input Nilai &mdash; <?= htmlspecialchars($selectedMapel['nama_mapel']) ?>
      <span class="badge badge-blue" style="margin-left:8px;"><?= count($siswas) ?> Siswa</span>
    </span>
    <button type="button" class="btn btn-outline btn-sm" onclick="fillAllZero()">
      <i class="fas fa-fill-drip"></i> Isi 0 Semua
    </button>
  </div>

  <form method="POST" data-nilai>
    <input type="hidden" name="save_nilai" value="1">
    <div style="overflow-x:auto;">
      <table style="width:100%;border-collapse:collapse;font-size:13px;min-width:<?= 650 + ($jsSumatif * 70) ?>px;">
        <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 colspan="<?= $jsSumatif ?>" style="padding:8px;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:80px;background:rgba(255,220,80,.15);border-left:1px solid rgba(255,255,255,.2);">Rata-rata<br>Sumatif</th>
            <?php if ($formulaAktif['sts'] > 0): ?>
            <th rowspan="2" style="padding:10px 8px;text-align:center;width:72px;border-left:1px solid rgba(255,255,255,.2);">STS</th>
            <?php endif; ?>
            <?php if ($formulaAktif['sas'] > 0): ?>
            <th rowspan="2" style="padding:10px 8px;text-align:center;width:72px;border-left:1px solid rgba(255,255,255,.2);">SAS</th>
            <?php endif; ?>
            <th rowspan="2" style="padding:10px 8px;text-align:center;width:85px;background:rgba(232,160,32,.25);border-left:2px solid rgba(255,200,50,.5);">Nilai<br>Rapor</th>
          </tr>
          <tr style="background:var(--primary);color:#fff;">
            <?php for ($i=1; $i<=$jsSumatif; $i++): ?>
            <th style="padding:7px 8px;text-align:center;width:70px;border-left:1px solid rgba(255,255,255,.15);font-size:12px;">S<?= $i ?></th>
            <?php endfor; ?>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($siswas as $idx => $s): ?>
          <?php $n = isset($nilaiExisting[$s['id']]) ? $nilaiExisting[$s['id']] : array(); ?>
          <tr class="nilai-row" data-siswa="<?= $s['id'] ?>" 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($s['nis']) ?></code></td>
            <td style="padding:8px 12px;font-weight:600;"><?= htmlspecialchars($s['nama']) ?></td>

            <?php for ($i=1; $i<=$jsSumatif; $i++):
                $fn  = 'sumatif_'.$i;
                $val = (isset($n[$fn]) && $n[$fn] !== null) ? number_format($n[$fn], 0) : '';
            ?>
            <td style="padding:5px 6px;text-align:center;border-left:1px solid var(--border);">
              <input type="number" name="nilai[<?= $s['id'] ?>][<?= $fn ?>]"
                     class="sumatif-input"
                     data-row="<?= $idx ?>" data-col="<?= $i - 1 ?>" data-type="sumatif"
                     style="width:60px;padding:5px;text-align:center;border:1px solid var(--border);border-radius:6px;font-size:13px;"
                     min="0" max="100" step="1" value="<?= $val ?>" placeholder="-"
                     oninput="hitungBaris(this.closest('tr'))"
                     onkeydown="handleEnter(event,this)">
            </td>
            <?php endfor; ?>

            <td style="padding:8px 6px;text-align:center;background:#fffbf0;border-left:1px solid var(--border);">
              <span class="rata-sumatif-cell" style="font-weight:700;color:var(--accent);">
                <?= (isset($n['rata_sumatif']) && $n['rata_sumatif'] !== null) ? number_format($n['rata_sumatif'],1) : '-' ?>
              </span>
            </td>

            <?php if ($formulaAktif['sts'] > 0): ?>
            <td style="padding:5px 6px;text-align:center;border-left:1px solid var(--border);">
              <input type="number" name="nilai[<?= $s['id'] ?>][sts]" class="sts-input"
                     data-row="<?= $idx ?>" data-type="sts"
                     style="width:60px;padding:5px;text-align:center;border:1px solid var(--border);border-radius:6px;font-size:13px;"
                     min="0" max="100" step="1"
                     value="<?= (isset($n['sts']) && $n['sts'] !== null) ? number_format($n['sts'],0) : '' ?>"
                     placeholder="-" oninput="hitungBaris(this.closest('tr'))"
                     onkeydown="handleEnter(event,this)">
            </td>
            <?php endif; ?>

            <?php if ($formulaAktif['sas'] > 0): ?>
            <td style="padding:5px 6px;text-align:center;border-left:1px solid var(--border);">
              <input type="number" name="nilai[<?= $s['id'] ?>][sas]" class="sas-input"
                     data-row="<?= $idx ?>" data-type="sas"
                     style="width:60px;padding:5px;text-align:center;border:1px solid var(--border);border-radius:6px;font-size:13px;"
                     min="0" max="100" step="1"
                     value="<?= (isset($n['sas']) && $n['sas'] !== null) ? number_format($n['sas'],0) : '' ?>"
                     placeholder="-" oninput="hitungBaris(this.closest('tr'))"
                     onkeydown="handleEnter(event,this)">
            </td>
            <?php endif; ?>

            <td style="padding:8px 6px;text-align:center;background:#fff8e8;border-left:2px solid var(--accent);">
              <span class="nilai-akhir-cell" style="font-weight:800;font-size:16px;color:var(--primary);">
                <?= (isset($n['nilai_akhir']) && $n['nilai_akhir'] !== null) ? number_format($n['nilai_akhir'],0) : '-' ?>
              </span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Catatan -->
    <div style="padding:10px 16px;border-top:1px solid var(--border);background:var(--surface-2);">
      <details>
        <summary style="cursor:pointer;font-size:13px;font-weight:600;color:var(--text-muted);">
          <i class="fas fa-comment-alt"></i> Catatan per Siswa (opsional)
        </summary>
        <div style="margin-top:10px;display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:8px;">
          <?php foreach ($siswas as $s): ?>
          <?php $n = isset($nilaiExisting[$s['id']]) ? $nilaiExisting[$s['id']] : array(); ?>
          <div style="display:flex;align-items:center;gap:8px;">
            <span style="font-size:12px;font-weight:600;min-width:130px;"><?= htmlspecialchars($s['nama']) ?></span>
            <input type="text" name="nilai[<?= $s['id'] ?>][catatan]" class="form-control"
                   style="font-size:12px;padding:5px 8px;"
                   value="<?= htmlspecialchars(isset($n['catatan']) ? $n['catatan'] : '') ?>" placeholder="Catatan...">
          </div>
          <?php endforeach; ?>
        </div>
      </details>
    </div>

    <div style="padding:14px 20px;border-top:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
      <span style="font-size:12px;color:var(--text-muted);">
        <i class="fas fa-info-circle"></i> Kolom kosong tidak masuk perhitungan.
      </span>
      <div style="display:flex;gap:10px;align-items:center;">
        <div id="save-indicator" style="display:none;align-items:center;gap:6px;font-size:13px;color:var(--primary);font-weight:600;">
          <i class="fas fa-spinner fa-spin"></i> Menyimpan...
        </div>
        <a href="<?= BASE_URL ?>/<?= $isAdmin?'admin.php':'guru.php' ?>" class="btn btn-outline">Batal</a>
        <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan Semua Nilai</button>
      </div>
    </div>
  </form>
</div>

<style>
/* Segitiga error di pojok kanan atas sel */
.cell-error-wrap {
    position: relative;
    display: inline-block;
}
.cell-error-wrap::after {
    content: '';
    position: absolute;
    top: -2px; right: -2px;
    width: 0; height: 0;
    border-style: solid;
    border-width: 0 10px 10px 0;
    border-color: transparent #dc2626 transparent transparent;
}
.cell-error-wrap .cell-error-tooltip {
    display: none;
    position: absolute;
    top: -36px; right: -4px;
    background: #dc2626;
    color: #fff;
    font-size: 10px;
    font-weight: 700;
    padding: 4px 8px;
    border-radius: 5px;
    white-space: nowrap;
    z-index: 999;
    pointer-events: none;
}
.cell-error-wrap:hover .cell-error-tooltip { display: block; }
</style>

<script>
var FORMULA = {
    rs:  <?= $formulaAktif['rata_sumatif'] ?>,
    sts: <?= $formulaAktif['sts'] ?>,
    sas: <?= $formulaAktif['sas'] ?>,
    js:  <?= $jsSumatif ?>
};

function hitungBaris(row) {
    var inputs = row.querySelectorAll('.sumatif-input');
    var sum = 0, cnt = 0;
    inputs.forEach(function(inp) {
        if (inp.value !== '') { sum += parseFloat(inp.value)||0; cnt++; }
    });
    // Rata hanya valid jika S1 dan S2 terisi
    var inpS1 = row.querySelector('.sumatif-input[data-col="0"]');
    var inpS2 = row.querySelector('.sumatif-input[data-col="1"]');
    var adaS1 = inpS1 && inpS1.value !== '';
    var adaS2 = inpS2 && inpS2.value !== '';
    var rata  = (cnt > 0 && adaS1 && adaS2) ? sum / cnt : null;

    // Rata sumatif hanya tampil jika minimal S1 (col=0) dan S2 (col=1) terisi
    var inpS1 = row.querySelector('.sumatif-input[data-col="0"]');
    var inpS2 = row.querySelector('.sumatif-input[data-col="1"]');
    var adaS1 = inpS1 && inpS1.value !== '';
    var adaS2 = inpS2 && inpS2.value !== '';
    var rataEl = row.querySelector('.rata-sumatif-cell');
    if (rataEl) {
        if (adaS1 && adaS2 && rata !== null) {
            var rataVal = rata;
            if (rataVal < 0 || rataVal > 100) {
                rataEl.innerHTML = '<span class="cell-error-wrap" style="color:#dc2626;font-weight:800;">'
                    + '! ' + rata.toFixed(1)
                    + '<span class="cell-error-tooltip">Rata-rata di luar range 0–100!</span>'
                    + '</span>';
            } else {
                rataEl.innerHTML = rata.toFixed(1);
                rataEl.style.color = '';
            }
        } else {
            rataEl.innerHTML = '-';
            rataEl.style.color = cnt > 0 ? '#ef4444' : '';
            rataEl.title = cnt > 0 && (!adaS1 || !adaS2) ? 'S1 dan S2 harus terisi' : '';
        }
    }

    var stsInp = row.querySelector('.sts-input');
    var sasInp = row.querySelector('.sas-input');
    var sts = (stsInp && stsInp.value !== '') ? parseFloat(stsInp.value) : null;
    var sas = (sasInp && sasInp.value !== '') ? parseFloat(sasInp.value) : null;

    var totalB = 0, totalN = 0;
    if (rata !== null && FORMULA.rs > 0) { totalN += rata * FORMULA.rs; totalB += FORMULA.rs; }
    if (sts  !== null && FORMULA.sts> 0) { totalN += sts  * FORMULA.sts; totalB += FORMULA.sts; }
    if (sas  !== null && FORMULA.sas> 0) { totalN += sas  * FORMULA.sas; totalB += FORMULA.sas; }

    // Validasi syarat nilai rapor
    var jumlahSumatif = 0;
    row.querySelectorAll('.sumatif-input').forEach(function(inp){
        if (inp.value !== '') jumlahSumatif++;
    });
    var stsOk  = !HAS_STS  || (stsInp  && stsInp.value  !== '');
    var sasOk  = !HAS_SAS  || (sasInp  && sasInp.value  !== '');
    var syarat = jumlahSumatif >= 2 && stsOk && sasOk;

    var akhir = (totalB > 0 && syarat) ? Math.round(totalN / totalB) : null;
    var el = row.querySelector('.nilai-akhir-cell');
    if (el) {
        if (!syarat && (jumlahSumatif > 0 || (stsInp && stsInp.value) || (sasInp && sasInp.value))) {
            // Tampilkan hint syarat belum terpenuhi
            var hint = [];
            if (jumlahSumatif < 2) hint.push('min. 2 sumatif');
            if (HAS_STS && stsInp && stsInp.value === '') hint.push('STS wajib');
            if (HAS_SAS && sasInp && sasInp.value === '') hint.push('SAS wajib');
            el.textContent = '-';
            el.title = 'Belum memenuhi syarat: ' + hint.join(', ');
            el.style.color = '#ef4444';
            el.style.fontWeight = '800';
        } else if (akhir !== null && (akhir < 0 || akhir > 100)) {
            // Hasil kalkulasi di luar range — tampil segitiga merah
            el.innerHTML = '<span class="cell-error-wrap" style="color:#dc2626;font-weight:900;">'
                + '! ' + akhir
                + '<span class="cell-error-tooltip">Nilai Rapor ' + akhir + ' di luar range 0–100!</span>'
                + '</span>';
        } else {
            el.innerHTML = akhir !== null ? akhir : '-';
            el.title = '';
            el.style.color = '';
            el.style.fontWeight = '800';
        }
    }
}

function fillAllZero() {
    document.querySelectorAll('.sumatif-input,.sts-input,.sas-input').forEach(function(inp) {
        if (inp.value === '') { inp.value = '0'; hitungBaris(inp.closest('tr')); }
    });
}

function toggleFormulaPanel() {
    var p = document.getElementById('formulaPanel');
    p.style.display = p.style.display === 'none' ? 'block' : 'none';
}

function updateFoPreview() {
    var rs  = parseFloat(document.getElementById('fo_rs').value)  || 0;
    var sts = parseFloat(document.getElementById('fo_sts').value) || 0;
    var sas = parseFloat(document.getElementById('fo_sas').value) || 0;
    var js  = parseInt(document.getElementById('fo_js').value)    || 5;
    var total = rs + sts + sas;

    document.getElementById('fo_lbl_rs').textContent  = rs  + '%';
    document.getElementById('fo_lbl_sts').textContent = sts + '%';
    document.getElementById('fo_lbl_sas').textContent = sas + '%';
    document.getElementById('fo_lbl_js').textContent  = js;

    var status = document.getElementById('fo_bobot_status');
    var btn    = document.getElementById('fo_btnSimpan');
    if (Math.abs(total - 100) < 0.01) {
        status.style.cssText = 'background:#d4edda;color:#155724;border:1px solid #c3e6cb;padding:7px 12px;border-radius:6px;font-size:12px;font-weight:600;margin-top:10px;';
        status.innerHTML = '<i class="fas fa-check-circle"></i> Total bobot: 100% ✓';
        btn.disabled = false; btn.style.opacity = '1';
    } else {
        status.style.cssText = 'background:#f8d7da;color:#721c24;border:1px solid #f5c6cb;padding:7px 12px;border-radius:6px;font-size:12px;font-weight:600;margin-top:10px;';
        status.innerHTML = '<i class="fas fa-times-circle"></i> Total: ' + total + '% — harus 100%';
        btn.disabled = true; btn.style.opacity = '.5';
    }
}

// ── Navigasi Enter ──────────────────────────────────────────
var TOTAL_ROWS = <?= count($siswas) ?>;
var JS_SUMATIF = <?= $jsSumatif ?>;
var HAS_STS    = <?= $formulaAktif['sts'] > 0 ? 'true' : 'false' ?>;
var HAS_SAS    = <?= $formulaAktif['sas'] > 0 ? 'true' : 'false' ?>;

// Urutan kolom: sumatif0..N, sts, sas
function buildColOrder() {
    var cols = [];
    for (var i = 0; i < JS_SUMATIF; i++) cols.push({type:'sumatif', col:i});
    if (HAS_STS) cols.push({type:'sts',    col:0});
    if (HAS_SAS) cols.push({type:'sas',    col:0});
    return cols;
}
var COL_ORDER = buildColOrder();

function getInput(row, colDef) {
    if (colDef.type === 'sumatif') {
        return document.querySelector(
            '.sumatif-input[data-row="'+row+'"][data-col="'+colDef.col+'"]'
        );
    }
    return document.querySelector('.'+colDef.type+'-input[data-row="'+row+'"]');
}

function getCurrentColIndex(inp) {
    var type = inp.getAttribute('data-type');
    var col  = inp.getAttribute('data-col');
    for (var i = 0; i < COL_ORDER.length; i++) {
        var c = COL_ORDER[i];
        if (c.type === type && (type !== 'sumatif' || String(c.col) === String(col))) {
            return i;
        }
    }
    return 0;
}

function handleEnter(e, inp) {
    if (e.key !== 'Enter') return;
    e.preventDefault();

    var row    = parseInt(inp.getAttribute('data-row'));
    var colIdx = getCurrentColIndex(inp);
    var nextRow = row + 1;

    if (nextRow < TOTAL_ROWS) {
        // Pindah baris berikutnya, kolom sama
        var next = getInput(nextRow, COL_ORDER[colIdx]);
        if (next) { next.focus(); next.select(); return; }
    }

    // Baris terakhir — pindah ke kolom berikutnya, baris pertama
    var nextColIdx = colIdx + 1;
    if (nextColIdx < COL_ORDER.length) {
        var next = getInput(0, COL_ORDER[nextColIdx]);
        if (next) { next.focus(); next.select(); return; }
    }

    // Semua selesai — auto simpan
    autoSave();
}

var saveTimer = null;
function autoSave() {
    var ind = document.getElementById('save-indicator');
    if (ind) { ind.style.display = 'flex'; }
    clearTimeout(saveTimer);
    saveTimer = setTimeout(function() {
        document.querySelector('form[data-nilai]').submit();
    }, 300);
}

// ── Highlight fokus + validasi range 0-100 ─────────────────
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.sumatif-input,.sts-input,.sas-input').forEach(function(inp) {
        inp.addEventListener('focus', function() {
            this.select();
            if (!this.classList.contains('input-error')) {
                this.style.background  = '#eff6ff';
                this.style.borderColor = 'var(--primary)';
            }
            this.style.outline = 'none';
        });
        inp.addEventListener('blur', function() {
            validasiRange(this);
        });
        inp.addEventListener('input', function() {
            validasiRange(this);
            hitungBaris(this.closest('tr'));
        });
    });
});

function validasiRange(inp) {
    if (inp.value === '') {
        // Kosong — reset ke normal
        inp.classList.remove('input-error');
        inp.style.background  = '';
        inp.style.borderColor = '';
        inp.title = '';
        sembunyikanError(inp);
        return true;
    }
    var val = parseFloat(inp.value);
    if (isNaN(val) || val < 0 || val > 100) {
        // Error
        inp.classList.add('input-error');
        inp.style.background  = '#fef2f2';
        inp.style.borderColor = '#ef4444';
        inp.style.color       = '#dc2626';
        var msg = isNaN(val) ? 'Nilai tidak valid' :
                  val < 0   ? 'Nilai tidak boleh kurang dari 0' :
                               'Nilai tidak boleh lebih dari 100';
        inp.title = msg;
        tampilkanError(inp, msg);
        return false;
    } else {
        // Valid
        inp.classList.remove('input-error');
        inp.style.background  = '#eff6ff';
        inp.style.borderColor = 'var(--primary)';
        inp.style.color       = '';
        inp.title = '';
        sembunyikanError(inp);
        return true;
    }
}

function tampilkanError(inp, msg) {
    var id  = 'err-' + inp.name.replace(/[\[\]]/g, '_');
    var old = document.getElementById(id);
    if (old) { old.textContent = msg; return; }
    var el = document.createElement('div');
    el.id = id;
    el.textContent = msg;
    el.style.cssText = 'position:absolute;background:#dc2626;color:#fff;font-size:10px;'
        + 'padding:3px 8px;border-radius:4px;white-space:nowrap;z-index:100;'
        + 'margin-top:2px;font-weight:600;pointer-events:none;';
    inp.parentNode.style.position = 'relative';
    inp.parentNode.appendChild(el);
}

function sembunyikanError(inp) {
    var id  = 'err-' + inp.name.replace(/[\[\]]/g, '_');
    var old = document.getElementById(id);
    if (old) old.remove();
}

// Validasi sebelum submit — cegah jika ada nilai error
document.querySelector('form[data-nilai]').addEventListener('submit', function(e) {
    var errors = document.querySelectorAll('.input-error');
    if (errors.length > 0) {
        e.preventDefault();
        errors[0].focus();
        // Tampilkan alert ringkas
        var existing = document.getElementById('global-error-msg');
        if (existing) existing.remove();
        var div = document.createElement('div');
        div.id = 'global-error-msg';
        div.style.cssText = 'position:fixed;top:80px;left:50%;transform:translateX(-50%);'
            + 'background:#dc2626;color:#fff;padding:12px 24px;border-radius:10px;'
            + 'font-size:13px;font-weight:700;z-index:9999;box-shadow:0 4px 20px rgba(0,0,0,.2);';
        div.innerHTML = '<i class="fas fa-exclamation-triangle"></i> '
            + 'Ada ' + errors.length + ' nilai yang tidak valid (harus 0–100). Periksa kembali sebelum menyimpan.';
        document.body.appendChild(div);
        setTimeout(function(){ div.remove(); }, 4000);
    }
});

// Init
document.querySelectorAll('.nilai-row').forEach(function(row) { hitungBaris(row); });
updateFoPreview();
</script>

<?php elseif ($kelasId && $mapelId && empty($siswas)): ?>
<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> Tidak ada siswa aktif di kelas ini.</div>

<?php else: ?>
<div class="card">
  <div class="card-body" style="text-align:center;padding:48px;color:var(--text-muted);">
    <i class="fas fa-edit" style="font-size:48px;color:var(--border);display:block;margin-bottom:16px;opacity:.4;"></i>
    <p>Pilih kelas dan mata pelajaran untuk memulai input nilai.</p>
  </div>
</div>
<?php endif; ?>

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