<?php
/**
 * SisPen Snesaka - Input Nilai PSAJ (Penilaian Sumatif Akhir Jenjang)
 * Khusus Kelas 9
 */
require_once '../../includes/functions.php';
requireLogin();

$pageTitle   = 'Input Nilai PSAJ';
$activeMenu  = 'psaj-input';
$pengaturan  = getPengaturan();
$isAdmin     = $_SESSION['role'] === 'admin';
$currentUser = getCurrentUser();
$guruId      = $currentUser['guru_id'] ?? null;
$ta          = $pengaturan['tahun_ajaran_aktif'];

// Bobot PSAJ dari pengaturan
$bobot = array(
    'tertulis'   => floatval($pengaturan['psaj_bobot_tertulis']   ?? 40),
    'praktik'    => floatval($pengaturan['psaj_bobot_praktik']    ?? 20),
    'proyek'     => floatval($pengaturan['psaj_bobot_proyek']     ?? 15),
    'portofolio' => floatval($pengaturan['psaj_bobot_portofolio'] ?? 15),
    'presentasi' => floatval($pengaturan['psaj_bobot_presentasi'] ?? 10),
);

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

// Daftar kelas 9 sesuai role
if ($isAdmin) {
    $kelasList = db_fetchAll(
        "SELECT * FROM kelas WHERE tingkat='9' AND tahun_ajaran=? ORDER BY nama_kelas",
        array($ta)
    );
    $mapelList = $kelasId ? db_fetchAll(
        "SELECT * FROM mata_pelajaran WHERE status='aktif' ORDER BY kelompok, urutan"
    ) : array();
} else {
    $kelasList = $guruId ? db_fetchAll(
        "SELECT DISTINCT k.* FROM pengampu p
         JOIN kelas k ON k.id=p.kelas_id
         WHERE p.guru_id=? AND k.tingkat='9' AND p.tahun_ajaran=?
         ORDER BY k.nama_kelas",
        array($guruId, $ta)
    ) : array();
    $mapelList = ($kelasId && $guruId) ? 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=?",
        array($guruId, $kelasId, $ta)
    ) : array();
}

// ── SIMPAN NILAI PSAJ ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_psaj'])) {
    $nilaiData = isset($_POST['nilai']) ? $_POST['nilai'] : array();
    $saved = 0;
    foreach ($nilaiData as $siswaId => $n) {
        $tertulis   = (isset($n['tertulis'])   && $n['tertulis']   !== '') ? floatval($n['tertulis'])   : null;
        $praktik    = (isset($n['praktik'])    && $n['praktik']    !== '') ? floatval($n['praktik'])    : null;
        $proyek     = (isset($n['proyek'])     && $n['proyek']     !== '') ? floatval($n['proyek'])     : null;
        $portofolio = (isset($n['portofolio']) && $n['portofolio'] !== '') ? floatval($n['portofolio']) : null;
        $presentasi = (isset($n['presentasi']) && $n['presentasi'] !== '') ? floatval($n['presentasi']) : null;

        // Hitung nilai akhir proporsional
        $totalBobot = 0; $totalNilai = 0;
        if ($tertulis   !== null) { $totalNilai += $tertulis   * $bobot['tertulis'];   $totalBobot += $bobot['tertulis']; }
        if ($praktik    !== null) { $totalNilai += $praktik    * $bobot['praktik'];    $totalBobot += $bobot['praktik']; }
        if ($proyek     !== null) { $totalNilai += $proyek     * $bobot['proyek'];     $totalBobot += $bobot['proyek']; }
        if ($portofolio !== null) { $totalNilai += $portofolio * $bobot['portofolio']; $totalBobot += $bobot['portofolio']; }
        if ($presentasi !== null) { $totalNilai += $presentasi * $bobot['presentasi']; $totalBobot += $bobot['presentasi']; }
        $nilaiAkhir = $totalBobot > 0 ? round($totalNilai / $totalBobot, 0) : null;

        $row = array(
            'tertulis'    => $tertulis,
            'praktik'     => $praktik,
            'proyek'      => $proyek,
            'portofolio'  => $portofolio,
            'presentasi'  => $presentasi,
            'nilai_akhir' => $nilaiAkhir,
            'catatan'     => sanitize(isset($n['catatan']) ? $n['catatan'] : ''),
            'guru_id'     => $guruId,
        );
        $existing = db_fetch(
            "SELECT id FROM nilai_psaj WHERE siswa_id=? AND mapel_id=? AND kelas_id=? AND tahun_ajaran=?",
            array(intval($siswaId), $mapelId, $kelasId, $ta)
        );
        if ($existing) {
            db_update('nilai_psaj', $row, 'id = :id', array('id' => $existing['id']));
        } else {
            db_insert('nilai_psaj', array_merge($row, array(
                'siswa_id'     => intval($siswaId),
                'mapel_id'     => $mapelId,
                'kelas_id'     => $kelasId,
                'tahun_ajaran' => $ta,
            )));
        }
        $saved++;
    }
    setFlash('success', "Nilai PSAJ berhasil disimpan untuk $saved siswa!");
    header("Location: input.php?kelas_id=$kelasId&mapel_id=$mapelId"); exit;
}

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

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

$komponen = array(
    'tertulis'   => 'Tes Tertulis',
    'praktik'    => 'Praktik / Unjuk Kerja',
    'proyek'     => 'Proyek',
    'portofolio' => 'Portofolio',
    'presentasi' => 'Presentasi / Penugasan',
);
$chipColors = array(
    'tertulis'   => array('#1e40af','#dbeafe'),
    'praktik'    => array('#065f46','#d1fae5'),
    'proyek'     => array('#92400e','#fef3c7'),
    'portofolio' => array('#4c1d95','#ede9fe'),
    'presentasi' => array('#991b1b','#fee2e2'),
);

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:160px;">
        <label class="form-label">Kelas 9</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 & Bobot chips -->
<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px;align-items:center;">
  <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']) ?>
    &nbsp;|&nbsp;<strong>Mapel:</strong> <?= htmlspecialchars($selectedMapel['nama_mapel']) ?>
    &nbsp;|&nbsp;<strong>TA:</strong> <?= $ta ?>
  </div>
  <?php foreach ($komponen as $key => $label):
    $c = $chipColors[$key]; ?>
  <span style="background:<?= $c[1] ?>;color:<?= $c[0] ?>;border-radius:20px;padding:4px 12px;font-size:11px;font-weight:700;">
    <?= $label ?>: <?= $bobot[$key] ?>%
  </span>
  <?php endforeach; ?>
  <?php if ($isAdmin): ?>
  <a href="<?= BASE_URL ?>/modules/pengaturan.php" style="font-size:12px;color:var(--primary);">
    <i class="fas fa-cog"></i> Ubah Bobot
  </a>
  <?php endif; ?>
</div>

<!-- Tabel Input -->
<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-graduation-cap" style="color:var(--primary);margin-right:8px;"></i>
      Input Nilai PSAJ &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-psaj>
    <input type="hidden" name="save_psaj" value="1">
    <div style="overflow-x:auto;">
      <table style="width:100%;border-collapse:collapse;font-size:13px;min-width:800px;">
        <thead>
          <tr style="background:var(--primary-dark);color:#fff;">
            <th style="padding:10px 10px;width:36px;">No</th>
            <th style="padding:10px 12px;text-align:left;min-width:180px;">Nama Siswa</th>
            <?php foreach ($komponen as $key => $label):
              $c = $chipColors[$key]; ?>
            <th style="padding:8px;text-align:center;width:95px;background:rgba(255,255,255,.07);border-left:1px solid rgba(255,255,255,.15);">
              <div style="font-size:11px;line-height:1.3;"><?= $label ?></div>
              <div style="font-size:10px;opacity:.7;">(<?= $bobot[$key] ?>%)</div>
            </th>
            <?php endforeach; ?>
            <th style="padding:10px 8px;text-align:center;width:76px;background:rgba(232,160,32,.25);border-left:2px solid rgba(255,200,50,.5);">
              Nilai<br>Akhir
            </th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($siswas as $idx => $s):
            $n = isset($nilaiExisting[$s['id']]) ? $nilaiExisting[$s['id']] : array();
          ?>
          <tr class="psaj-row" style="<?= $idx%2===0?'':'background:var(--surface-2);' ?>">
            <td style="padding:8px 10px;text-align:center;color:var(--text-muted);"><?= $idx+1 ?></td>
            <td style="padding:8px 12px;font-weight:600;"><?= htmlspecialchars($s['nama']) ?></td>
            <?php foreach ($komponen as $key => $label):
              $val = (isset($n[$key]) && $n[$key] !== null) ? number_format($n[$key], 0) : '';
            ?>
            <td style="padding:5px 6px;text-align:center;border-left:1px solid var(--border);">
              <input type="number"
                     name="nilai[<?= $s['id'] ?>][<?= $key ?>]"
                     class="psaj-input" data-key="<?= $key ?>"
                     data-row="<?= $idx ?>" data-col="<?= array_search($key, array_keys($komponen)) ?>"
                     style="width:70px;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 endforeach; ?>
            <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>
    <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. Nilai akhir dihitung proporsional dari bobot.
      </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 Nilai PSAJ
        </button>
      </div>
    </div>
  </form>
</div>

<script>
var BOBOT = {
    tertulis:   <?= $bobot['tertulis'] ?>,
    praktik:    <?= $bobot['praktik'] ?>,
    proyek:     <?= $bobot['proyek'] ?>,
    portofolio: <?= $bobot['portofolio'] ?>,
    presentasi: <?= $bobot['presentasi'] ?>
};
var TOTAL_ROWS = <?= count($siswas) ?>;
var TOTAL_COLS = <?= count($komponen) ?>;

function hitungBaris(row) {
    var inputs = row.querySelectorAll('.psaj-input');
    var totalBobot = 0, totalNilai = 0;
    inputs.forEach(function(inp) {
        var key = inp.getAttribute('data-key');
        if (inp.value !== '' && BOBOT[key]) {
            totalNilai += parseFloat(inp.value) * BOBOT[key];
            totalBobot += BOBOT[key];
        }
    });
    var akhir = totalBobot > 0 ? Math.round(totalNilai / totalBobot) : null;
    var el = row.querySelector('.nilai-akhir-cell');
    if (el) el.textContent = akhir !== null ? akhir : '-';
}

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

// ── Navigasi Enter: pindah ke baris berikutnya, kolom sama ──
function handleEnter(e, inp) {
    if (e.key !== 'Enter') return;
    e.preventDefault();

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

    if (nextRow < TOTAL_ROWS) {
        // Pindah ke baris berikutnya, kolom sama
        var next = document.querySelector(
            '.psaj-input[data-row="' + nextRow + '"][data-col="' + col + '"]'
        );
        if (next) {
            next.focus();
            next.select();
        }
    } else {
        // Sudah baris terakhir — pindah ke kolom berikutnya baris pertama
        var nextCol = col + 1;
        if (nextCol < TOTAL_COLS) {
            var next = document.querySelector(
                '.psaj-input[data-row="0"][data-col="' + nextCol + '"]'
            );
            if (next) {
                next.focus();
                next.select();
                return; // jangan save dulu
            }
        }
        // Semua kolom selesai — auto submit/simpan
        autoSave();
    }
}

// ── Auto-save saat Enter di baris terakhir kolom terakhir ──
var saveTimer = null;
function autoSave() {
    // Tampilkan indikator
    var indicator = document.getElementById('save-indicator');
    if (indicator) {
        indicator.style.display = 'flex';
        indicator.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menyimpan...';
    }
    clearTimeout(saveTimer);
    saveTimer = setTimeout(function() {
        document.querySelector('form[data-psaj]').submit();
    }, 300);
}

// ── Highlight input saat fokus ──────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.psaj-row').forEach(function(row) { hitungBaris(row); });

    document.querySelectorAll('.psaj-input').forEach(function(inp) {
        inp.addEventListener('focus', function() {
            this.select();
            this.style.background = '#eff6ff';
            this.style.borderColor = 'var(--primary)';
        });
        inp.addEventListener('blur', function() {
            this.style.background = '';
            this.style.borderColor = '';
        });
    });
});
</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-graduation-cap" style="font-size:48px;color:var(--border);display:block;margin-bottom:16px;opacity:.4;"></i>
    <p>Pilih kelas 9 dan mata pelajaran untuk input nilai PSAJ.</p>
  </div>
</div>
<?php endif; ?>

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