<?php // app/Views/guru/assessment/koreksi.php ?>
<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<style>
/* Input belum diisi = abu-abu, sudah diisi = putih/normal */
.input-kosong {
    background-color: #e9ecef !important;
    color: #6c757d !important;
    border-color: #ced4da !important;
    transition: background-color .2s, color .2s;
}
</style>

<div class="container-fluid py-4">

    <?php if (!$isPeriodActive): ?>
        <div class="alert alert-danger border-0 shadow-sm d-flex align-items-center mb-4 rounded-3">
            <i class="bi bi-exclamation-triangle-fill fs-4 me-3"></i>
            <div>
                <h6 class="alert-heading mb-1 fw-bold">Periode Akademik Telah Ditutup</h6>
                <span class="small">Status periode akademik untuk asesmen ini tidak aktif. Seluruh form input dinonaktifkan dan perubahan nilai tidak dapat disimpan. Silakan hubungi administrator untuk membuka kembali.</span>
            </div>
        </div>
    <?php endif; ?>

    <!-- Header -->
    <div class="d-flex align-items-center gap-2 mb-3">
        <a href="/guru/assessment" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div class="flex-grow-1">
            <h4 class="mb-0 fw-bold"><?= esc($assessment['name']) ?></h4>
            <small class="text-muted">
                <?= esc($subject['name'] ?? '-') ?> &mdash;
                Kelas <?= esc($classroom['name'] ?? '-') ?> &mdash;
                Semester <?= esc($activePeriod['semester'] ?? '') ?>
            </small>
        </div>
        <a href="/guru/assessment/export/<?= $assessment['id'] ?>/<?= $classroom['id'] ?>/<?= $subject['id'] ?>"
           class="btn btn-outline-success btn-sm">
            <i class="bi bi-file-earmark-excel me-1"></i> Export Excel
        </a>
    </div>

    <div id="alert_box" class="d-none mb-3"></div>

    <!-- ===================== PANEL SETTING (ATAS) ===================== -->
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-white fw-semibold border-bottom d-flex justify-content-between align-items-center">
            <span><i class="bi bi-gear me-2 text-primary"></i>Setting Koreksi</span>
            <div class="d-flex align-items-center gap-2">
                <?php if ($bobotByAdmin): ?>
                <span class="badge bg-primary">
                    <i class="bi bi-shield-lock me-1"></i>Bobot diatur Admin
                </span>
                <?php endif; ?>
                <?php if ($setting['bobot_filled']): ?>
                    <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Setting Aktif</span>
                <?php else: ?>
                    <span class="badge bg-warning text-dark"><i class="bi bi-exclamation-triangle me-1"></i>Belum Disimpan</span>
                <?php endif; ?>
            </div>
        </div>
        <div class="card-body">
            <div class="row g-4">

                <!-- KKTP -->
                <div class="<?= $bobotByAdmin ? 'col-md-3' : 'col-md-2' ?>">
                    <label class="form-label fw-semibold small">KKTP / KKM</label>
                    <div class="input-group input-group-sm">
                        <input type="number" id="kktp" class="form-control text-center fw-bold"
                               min="0" max="100" value="<?= $setting['kktp'] ?? 75 ?>" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                        <span class="input-group-text">/100</span>
                    </div>
                </div>

                <?php if (!$bobotByAdmin): ?>
                <!-- BOBOT — hanya tampil jika bobot diatur guru -->
                <div class="col-md-4">
                    <label class="form-label fw-semibold small">
                        Bobot Penilaian
                        <span id="total_bobot_badge" class="badge ms-2 <?= $setting['bobot_filled'] ? 'bg-success' : 'bg-danger' ?>">
                            Total: <?= ($setting['bobot_pg'] ?? 0) + ($setting['bobot_bs'] ?? 0) + ($setting['bobot_isian'] ?? 0) + ($setting['bobot_essay'] ?? 0) ?>%
                        </span>
                    </label>
                    <div class="row g-2">
                        <?php if ($assessment['has_pg']): ?>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-info-subtle text-info fw-bold">PG</span>
                                <input type="number" id="bobot_pg" class="form-control bobot-input text-center"
                                       min="0" max="100" value="<?= $setting['bobot_pg'] ?? 0 ?>"
                                       onchange="updateTotalBobot()"
                                       <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php if ($assessment['has_bs']): ?>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-warning-subtle text-warning fw-bold">BS</span>
                                <input type="number" id="bobot_bs" class="form-control bobot-input text-center"
                                       min="0" max="100" value="<?= $setting['bobot_bs'] ?? 0 ?>"
                                       onchange="updateTotalBobot()"
                                       <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php if ($assessment['has_isian']): ?>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-success-subtle text-success fw-bold">Isian</span>
                                <input type="number" id="bobot_isian" class="form-control bobot-input text-center"
                                       min="0" max="100" value="<?= $setting['bobot_isian'] ?? 0 ?>"
                                       onchange="updateTotalBobot()"
                                       <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php if ($assessment['has_essay']): ?>
                        <div class="col-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-secondary-subtle text-secondary fw-bold">Essay</span>
                                <input type="number" id="bobot_essay" class="form-control bobot-input text-center"
                                       min="0" max="100" value="<?= $setting['bobot_essay'] ?? 0 ?>"
                                       onchange="updateTotalBobot()"
                                       <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                <span class="input-group-text">%</span>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- KUNCI JAWABAN -->
                <div class="<?= $bobotByAdmin ? 'col-md-7' : 'col-md-4' ?>">
                    <label class="form-label fw-semibold small">Kunci Jawaban</label>
                    <div class="row g-2">
                        <?php if ($assessment['has_pg']): ?>
                        <div class="<?= $bobotByAdmin ? 'col-6' : 'col-12' ?>">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-info-subtle text-info fw-bold" style="width:60px">
                                    PG
                                    <span id="total_soal_pg_badge" class="badge bg-secondary ms-1 fs-8">
                                        <?= $totalSoalPg ?>
                                    </span>
                                </span>
                                <input type="text" id="kunci_pg" class="form-control font-monospace"
                                       placeholder="cth: AABBCCDDAA"
                                       value="<?= esc($setting['kunci_pg'] ?? '') ?>"
                                       oninput="updateTotalSoal('pg')" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                            </div>
                            <div class="form-text">Spasi = jawaban kosong (salah)</div>
                        </div>
                        <?php endif; ?>
                        <?php if ($assessment['has_bs']): ?>
                        <div class="<?= $bobotByAdmin ? 'col-6' : 'col-12' ?>">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text bg-warning-subtle text-warning fw-bold" style="width:60px">
                                    BS
                                    <span id="total_soal_bs_badge" class="badge bg-secondary ms-1 fs-8">
                                        <?= $totalSoalBs ?>
                                    </span>
                                </span>
                                <input type="text" id="kunci_bs" class="form-control font-monospace"
                                       placeholder="cth: BBSSB"
                                       value="<?= esc($setting['kunci_bs'] ?? '') ?>"
                                       oninput="updateTotalSoal('bs')" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- TOMBOL SIMPAN -->
                <div class="col-md-2 d-flex align-items-end">
                    <?php if ($isPeriodActive): ?>
                    <button class="btn btn-primary w-100" onclick="saveSetting()">
                        <i class="bi bi-floppy me-1"></i><?= $bobotByAdmin ? ' Simpan KKTP & Kunci' : ' Simpan Setting' ?>
                    </button>
                    <?php else: ?>
                    <button class="btn btn-secondary w-100" disabled>
                        <i class="bi bi-lock-fill me-1"></i> Setting Terkunci
                    </button>
                    <?php endif; ?>
                </div>

            </div>
        </div>
    </div>

    <!-- ===================== TABEL KOREKSI (BAWAH) ===================== -->
    <div class="card shadow-sm" id="card_koreksi">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span class="fw-semibold">
                <i class="bi bi-table me-2 text-success"></i>
                Koreksi Siswa
                <span class="badge bg-secondary ms-1"><?= count($students) ?> siswa</span>
            </span>
            <span id="koreksi_status_badge">
                <?php
                $sudahKoreksi = 0;
                foreach ($students as $s) {
                    if (isset($s['score']['nilai_akhir']) && $s['score']['nilai_akhir'] !== null) $sudahKoreksi++;
                }
                $total = count($students);
                ?>
                <span class="badge <?= $sudahKoreksi === $total && $total > 0 ? 'bg-success' : 'bg-warning text-dark' ?>">
                    <?= $sudahKoreksi ?>/<?= $total ?> selesai
                </span>
            </span>
        </div>

        <?php if (!$setting['bobot_filled']): ?>
        <!-- Tabel terkunci -->
        <div class="card-body text-center py-5 text-muted" id="tabel_locked">
            <i class="bi bi-lock fs-2 d-block mb-2 opacity-50"></i>
            <div class="fw-semibold">Tabel koreksi belum aktif</div>
            <small>Isi setting bobot di atas, total harus 100%, lalu simpan</small>
        </div>
        <div class="d-none" id="tabel_wrapper">
        <?php else: ?>
        <div class="d-none" id="tabel_locked"></div>
        <div id="tabel_wrapper">
        <?php endif; ?>

            <div class="table-responsive">
                <table class="table table-bordered align-middle mb-0 table-sm" id="tabel_koreksi" style="min-width:900px">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-3 text-center" style="width:40px">#</th>
                            <th style="min-width:180px">Nama Siswa</th>
                            <?php if ($assessment['has_pg']): ?>
                                <th style="min-width:320px">
                                    Jawaban PG
                                    <small class="d-block text-muted fw-normal" id="th_soal_pg">
                                        <?= $totalSoalPg ?> soal
                                    </small>
                                </th>
                            <?php endif; ?>
                            <?php if ($assessment['has_bs']): ?>
                                <th style="min-width:220px">
                                    Jawaban BS
                                    <small class="d-block text-muted fw-normal" id="th_soal_bs">
                                        <?= $totalSoalBs ?> soal
                                    </small>
                                </th>
                            <?php endif; ?>
                            <?php if ($assessment['has_isian']): ?>
                                <?php
                                $isianMaxPerSoal = $assessment['isian_mode'] === 'per_nomor' && $assessment['isian_total_soal'] > 0
                                    ? (int) floor(100 / $assessment['isian_total_soal']) : 100;
                                // lebih compact: 48px per soal, min 80px
                                $isianMinWidth = $assessment['isian_mode'] === 'per_nomor'
                                    ? (5 * 48 + 4 * 4 + 8) : 80; // 5 kolom × 48px + gap + padding
                                ?>
                                <th style="min-width:<?= $isianMinWidth ?>px">
                                    Skor Isian
                                    <?php if ($assessment['isian_mode'] === 'per_nomor'): ?>
                                        <small class="d-block text-muted fw-normal">
                                            <?= $assessment['isian_total_soal'] ?> soal &mdash; max <?= $isianMaxPerSoal ?>/soal
                                        </small>
                                    <?php else: ?>
                                        <small class="d-block text-muted fw-normal">0-100</small>
                                    <?php endif; ?>
                                </th>
                            <?php endif; ?>
                            <?php if ($assessment['has_essay']): ?>
                                <?php
                                $essayMaxPerSoal = $assessment['essay_mode'] === 'per_nomor' && $assessment['essay_total_soal'] > 0
                                    ? (int) floor(100 / $assessment['essay_total_soal']) : 100;
                                $essayMinWidth = $assessment['essay_mode'] === 'per_nomor'
                                    ? (5 * 48 + 4 * 4 + 8) : 80; // 5 kolom × 48px + gap + padding
                                ?>
                                <th style="min-width:<?= $essayMinWidth ?>px">
                                    Skor Essay
                                    <?php if ($assessment['essay_mode'] === 'per_nomor'): ?>
                                        <small class="d-block text-muted fw-normal">
                                            <?= $assessment['essay_total_soal'] ?> soal &mdash; max <?= $essayMaxPerSoal ?>/soal
                                        </small>
                                    <?php else: ?>
                                        <small class="d-block text-muted fw-normal">0-100</small>
                                    <?php endif; ?>
                                </th>
                            <?php endif; ?>
                            <th class="text-center" style="width:75px">Nilai</th>
                            <th class="text-center" style="width:90px">Tercapai</th>
                            <th class="text-center" style="width:60px">Simpan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $no = 1; foreach ($students as $s): ?>
                        <?php $score = $s['score'] ?? null; ?>
                        <tr id="row_<?= $s['id'] ?>">
                            <td class="text-center"><?= $no++ ?></td>
                            <td>
                                <div class="fw-semibold small"><?= esc($s['full_name']) ?></div>
                                <small class="text-muted"><?= esc($s['nis']) ?></small>
                                <div id="notif_<?= $s['id'] ?>">
                                    <?php if ($score && $score['notif_pg']): ?>
                                        <div class="badge bg-warning text-dark d-block mt-1">
                                            <i class="bi bi-exclamation-triangle me-1"></i>PG: <?= esc($score['notif_pg']) ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if ($score && $score['notif_bs']): ?>
                                        <div class="badge bg-warning text-dark d-block mt-1">
                                            <i class="bi bi-exclamation-triangle me-1"></i>BS: <?= esc($score['notif_bs']) ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>

                            <!-- PG -->
                            <?php if ($assessment['has_pg']): ?>
                            <td>
                                <?php $pgVal = $score['jawaban_pg'] ?? ''; ?>
                                <textarea
                                       class="form-control form-control-sm font-monospace <?= empty($pgVal) ? 'input-kosong' : '' ?>"
                                       id="pg_<?= $s['id'] ?>"
                                       rows="2"
                                       placeholder="Ketik jawaban, otomatis wrap tiap baris..."
                                       style="resize:none; white-space:pre-wrap; word-break:break-all" <?= !$isPeriodActive ? 'disabled' : '' ?>><?= esc($pgVal) ?></textarea>
                                <small class="text-muted" id="skor_pg_<?= $s['id'] ?>">
                                    <?= $score && $score['skor_pg'] !== null ? 'Skor: ' . number_format($score['skor_pg'], 1) : '' ?>
                                </small>
                            </td>
                            <?php endif; ?>

                            <!-- BS -->
                            <?php if ($assessment['has_bs']): ?>
                            <td>
                                <?php $bsVal = $score['jawaban_bs'] ?? ''; ?>
                                <textarea
                                       class="form-control form-control-sm font-monospace <?= empty($bsVal) ? 'input-kosong' : '' ?>"
                                       id="bs_<?= $s['id'] ?>"
                                       rows="2"
                                       placeholder="Ketik jawaban..."
                                       style="resize:none; white-space:pre-wrap; word-break:break-all" <?= !$isPeriodActive ? 'disabled' : '' ?>><?= esc($bsVal) ?></textarea>
                                <small class="text-muted" id="skor_bs_<?= $s['id'] ?>">
                                    <?= $score && $score['skor_bs'] !== null ? 'Skor: ' . number_format($score['skor_bs'], 1) : '' ?>
                                </small>
                            </td>
                            <?php endif; ?>

                            <!-- ISIAN -->
                            <?php if ($assessment['has_isian']): ?>
                            <td>
                                <?php if ($assessment['isian_mode'] === 'total'): ?>
                                    <?php $isianVal = ($score && $score['skor_isian'] !== null) ? (int)$score['skor_isian'] : ''; ?>
                                    <input type="number"
                                           class="form-control form-control-sm text-center <?= ($isianVal === '') ? 'input-kosong' : '' ?>"
                                           id="isian_<?= $s['id'] ?>"
                                           min="0" max="100" step="1" style="width:65px"
                                           value="<?= $isianVal ?>"
                                           placeholder="0-100" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                <?php else: ?>
                                    <?php
                                    $isianMax = $assessment['isian_total_soal'] > 0
                                        ? (int) floor(100 / $assessment['isian_total_soal']) : 100;
                                    ?>
                                    <!-- Grid 5 kolom, rapi walau jumlah soal tidak genap 5 -->
                                    <div style="display:grid; grid-template-columns:repeat(5, 48px); gap:4px;">
                                        <?php for ($n = 1; $n <= $assessment['isian_total_soal']; $n++): ?>
                                        <?php $isianNVal = isset($isianDetails[$s['id']][$n]) ? (int)$isianDetails[$s['id']][$n] : ''; ?>
                                        <div class="text-center">
                                            <div style="font-size:.65rem; color:#6c757d; margin-bottom:2px">No.<?= $n ?></div>
                                            <input type="number"
                                                   class="form-control form-control-sm text-center p-1 isian-detail-<?= $s['id'] ?> <?= ($isianNVal === '') ? 'input-kosong' : '' ?>"
                                                   data-nomor="<?= $n ?>"
                                                   min="0" max="<?= $isianMax ?>" step="1"
                                                   value="<?= $isianNVal ?>"
                                                   placeholder="<?= $isianMax ?>"
                                                   style="width:100%; font-size:.8rem" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                        </div>
                                        <?php endfor; ?>
                                    </div>
                                    <small class="text-muted d-block mt-1" id="skor_isian_<?= $s['id'] ?>">
                                        <?= $score && $score['skor_isian'] !== null
                                            ? 'Total: ' . (int)$score['skor_isian'] . ' / 100'
                                            : '' ?>
                                    </small>
                                <?php endif; ?>
                            </td>
                            <?php endif; ?>

                            <!-- ESSAY -->
                            <?php if ($assessment['has_essay']): ?>
                            <td>
                                <?php if ($assessment['essay_mode'] === 'total'): ?>
                                    <?php $essayVal = ($score && $score['skor_essay'] !== null) ? (int)$score['skor_essay'] : ''; ?>
                                    <input type="number"
                                           class="form-control form-control-sm text-center <?= ($essayVal === '') ? 'input-kosong' : '' ?>"
                                           id="essay_<?= $s['id'] ?>"
                                           min="0" max="100" step="1" style="width:65px"
                                           value="<?= $essayVal ?>"
                                           placeholder="0-100" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                <?php else: ?>
                                    <?php
                                    $essayMax = $assessment['essay_total_soal'] > 0
                                        ? (int) floor(100 / $assessment['essay_total_soal']) : 100;
                                    ?>
                                    <!-- Grid 5 kolom -->
                                    <div style="display:grid; grid-template-columns:repeat(5, 48px); gap:4px;">
                                        <?php for ($n = 1; $n <= $assessment['essay_total_soal']; $n++): ?>
                                        <?php $essayNVal = isset($essayDetails[$s['id']][$n]) ? (int)$essayDetails[$s['id']][$n] : ''; ?>
                                        <div class="text-center">
                                            <div style="font-size:.65rem; color:#6c757d; margin-bottom:2px">No.<?= $n ?></div>
                                            <input type="number"
                                                   class="form-control form-control-sm text-center p-1 essay-detail-<?= $s['id'] ?> <?= ($essayNVal === '') ? 'input-kosong' : '' ?>"
                                                   data-nomor="<?= $n ?>"
                                                   min="0" max="<?= $essayMax ?>" step="1"
                                                   value="<?= $essayNVal ?>"
                                                   placeholder="<?= $essayMax ?>"
                                                   style="width:100%; font-size:.8rem" <?= !$isPeriodActive ? 'disabled' : '' ?>>
                                        </div>
                                        <?php endfor; ?>
                                    </div>
                                    <small class="text-muted d-block mt-1" id="skor_essay_<?= $s['id'] ?>">
                                        <?= $score && $score['skor_essay'] !== null
                                            ? 'Total: ' . (int)$score['skor_essay'] . ' / 100'
                                            : '' ?>
                                    </small>
                                <?php endif; ?>
                            </td>
                            <?php endif; ?>

                            <!-- Nilai Akhir -->
                            <td class="text-center">
                                <span class="fw-bold fs-5" id="nilai_<?= $s['id'] ?>">
                                    <?php if ($score && $score['nilai_akhir'] !== null): ?>
                                        <?php
                                        $na = $score['nilai_akhir'];
                                        $naTampil = (floor($na) == $na) ? (int)$na : number_format($na, 2);
                                        $tercapai = $na >= ($setting['kktp'] ?? 75);
                                        ?>
                                        <span class="<?= $tercapai ? 'text-success' : 'text-danger' ?>">
                                            <?= $naTampil ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </span>
                            </td>

                            <!-- Tercapai -->
                            <td class="text-center" id="tercapai_<?= $s['id'] ?>">
                                <?php if ($score && $score['nilai_akhir'] !== null): ?>
                                    <?php if ($score['nilai_akhir'] >= ($setting['kktp'] ?? 75)): ?>
                                        <span class="badge bg-success">
                                            <i class="bi bi-check-circle me-1"></i>Tercapai
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">
                                            <i class="bi bi-x-circle me-1"></i>Belum
                                        </span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted small">—</span>
                                <?php endif; ?>
                            </td>

                            <!-- Tombol Simpan -->
                            <td class="text-center">
                                <?php if ($isPeriodActive): ?>
                                <button class="btn btn-sm btn-primary" onclick="saveScore(<?= $s['id'] ?>)" title="Simpan">
                                    <i class="bi bi-floppy"></i>
                                </button>
                                <?php else: ?>
                                <span class="badge bg-secondary-subtle text-secondary py-1.5 px-2" title="Terkunci">
                                    <i class="bi bi-lock-fill"></i>
                                </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

        </div><!-- end tabel_wrapper -->
    </div>

</div>

<script>
const ASSESSMENT_ID = <?= $assessment['id'] ?>;
const CLASSROOM_ID  = <?= $classroom['id'] ?>;
const SUBJECT_ID    = <?= $subject['id'] ?>;
const KKTP          = <?= $setting['kktp'] ?? 75 ?>;
const HAS_PG        = <?= $assessment['has_pg'] ? 'true' : 'false' ?>;
const HAS_BS        = <?= $assessment['has_bs'] ? 'true' : 'false' ?>;
const HAS_ISIAN     = <?= $assessment['has_isian'] ? 'true' : 'false' ?>;
const HAS_ESSAY     = <?= $assessment['has_essay'] ? 'true' : 'false' ?>;
const ISIAN_MODE    = '<?= $assessment['isian_mode'] ?>';
const ESSAY_MODE    = '<?= $assessment['essay_mode'] ?>';
const CSRF_TOKEN    = '<?= csrf_token() ?>';
let   CSRF_HASH      = '<?= csrf_hash() ?>';
const BOBOT_BY_ADMIN = <?= $bobotByAdmin ? 'true' : 'false' ?>;

// ---- Update total bobot badge ----
function updateTotalBobot() {
    if (BOBOT_BY_ADMIN) return; // bobot diatur admin, tidak perlu hitung di sisi guru
    let total = 0;
    document.querySelectorAll('.bobot-input').forEach(el => {
        total += parseInt(el.value || 0);
    });
    const badge = document.getElementById('total_bobot_badge');
    if (!badge) return;
    badge.textContent = 'Total: ' + total + '%';
    badge.className = 'badge ms-2 ' + (total === 100 ? 'bg-success' : 'bg-danger');
}

// ---- Update jumlah soal dari kunci ----
function updateTotalSoal(jenis) {
    const kunci = document.getElementById('kunci_' + jenis)?.value ?? '';
    const total = kunci.length; // spasi tetap dihitung
    const badge = document.getElementById('total_soal_' + jenis + '_badge');
    const th    = document.getElementById('th_soal_' + jenis);
    if (badge) badge.textContent = total;
    if (th) th.textContent = total + ' soal';
}

// ---- Simpan setting — FIX: aktifkan tabel tanpa reload ----
function saveSetting() {
    const data = new FormData();
    data.append(CSRF_TOKEN, CSRF_HASH);
    data.append('kktp', document.getElementById('kktp').value);
    // Hanya kirim bobot jika diatur oleh guru (bukan admin)
    if (!BOBOT_BY_ADMIN) {
        if (HAS_PG)    data.append('bobot_pg',    document.getElementById('bobot_pg')?.value    || 0);
        if (HAS_BS)    data.append('bobot_bs',    document.getElementById('bobot_bs')?.value    || 0);
        if (HAS_ISIAN) data.append('bobot_isian', document.getElementById('bobot_isian')?.value || 0);
        if (HAS_ESSAY) data.append('bobot_essay', document.getElementById('bobot_essay')?.value || 0);
    }
    if (HAS_PG)    data.append('kunci_pg',    document.getElementById('kunci_pg')?.value    || '');
    if (HAS_BS)    data.append('kunci_bs',    document.getElementById('kunci_bs')?.value    || '');

    fetch(`/guru/assessment/save-setting/${ASSESSMENT_ID}/${CLASSROOM_ID}/${SUBJECT_ID}`, {
        method: 'POST', body: data
    })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            showAlert('success', res.message, 2000);

            // Update badge soal di header
            if (res.total_soal_pg !== undefined) {
                const b = document.getElementById('total_soal_pg_badge');
                const t = document.getElementById('th_soal_pg');
                if (b) b.textContent = res.total_soal_pg;
                if (t) t.textContent = res.total_soal_pg + ' soal';
            }
            if (res.total_soal_bs !== undefined) {
                const b = document.getElementById('total_soal_bs_badge');
                const t = document.getElementById('th_soal_bs');
                if (b) b.textContent = res.total_soal_bs;
                if (t) t.textContent = res.total_soal_bs + ' soal';
            }

            // Aktifkan tabel koreksi tanpa refresh
            if (res.bobot_filled) {
                document.getElementById('tabel_locked').classList.add('d-none');
                document.getElementById('tabel_wrapper').classList.remove('d-none');
            }
        } else {
            showAlert('danger', res.message);
        }
    });
}

// ---- Simpan skor siswa ----
function saveScore(studentId) {
    const data = new FormData();
    data.append(CSRF_TOKEN, CSRF_HASH);
    data.append('assessment_id', ASSESSMENT_ID);
    data.append('classroom_id',  CLASSROOM_ID);
    data.append('subject_id',    SUBJECT_ID);
    data.append('student_id',    studentId);

    if (HAS_PG) {
        // Strip newline/spasi berlebih dari textarea — guru mungkin paste dengan enter
        const pgRaw = document.getElementById('pg_' + studentId)?.value || '';
        data.append('jawaban_pg', pgRaw.replace(/[\r\n\t]/g, ''));
    }
    if (HAS_BS) {
        const bsRaw = document.getElementById('bs_' + studentId)?.value || '';
        data.append('jawaban_bs', bsRaw.replace(/[\r\n\t]/g, ''));
    }
    if (HAS_ISIAN) {
        if (ISIAN_MODE === 'total') {
            data.append('skor_isian', document.getElementById('isian_' + studentId)?.value || 0);
        } else {
            // Per nomor: kumpulkan semua input
            document.querySelectorAll('.isian-detail-' + studentId).forEach(el => {
                data.append('isian_details[' + el.dataset.nomor + ']', el.value || 0);
            });
        }
    }
    if (HAS_ESSAY) {
        if (ESSAY_MODE === 'total') {
            data.append('skor_essay', document.getElementById('essay_' + studentId)?.value || 0);
        } else {
            document.querySelectorAll('.essay-detail-' + studentId).forEach(el => {
                data.append('essay_details[' + el.dataset.nomor + ']', el.value || 0);
            });
        }
    }

    fetch('/guru/assessment/save-score', { method: 'POST', body: data })
    .then(r => r.json())
    .then(res => {
        if (res.success) {
            // Update nilai akhir — desimal kalau perlu
            const nilaiEl = document.getElementById('nilai_' + studentId);
            const warna = res.nilai_akhir >= KKTP ? 'text-success' : 'text-danger';
            const nilaiTampil = Number.isInteger(res.nilai_akhir)
                ? res.nilai_akhir
                : parseFloat(res.nilai_akhir).toFixed(2);
            nilaiEl.innerHTML = `<span class="${warna}">${nilaiTampil}</span>`;

            // Update kolom Tercapai
            const tercapaiEl = document.getElementById('tercapai_' + studentId);
            if (tercapaiEl) {
                if (res.nilai_akhir >= KKTP) {
                    tercapaiEl.innerHTML = `<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Tercapai</span>`;
                } else {
                    tercapaiEl.innerHTML = `<span class="badge bg-danger"><i class="bi bi-x-circle me-1"></i>Belum</span>`;
                }
            }

            // Update skor PG — 1 desimal
            if (res.skor_pg !== undefined) {
                const el = document.getElementById('skor_pg_' + studentId);
                if (el) el.textContent = 'Skor: ' + parseFloat(res.skor_pg).toFixed(1);
            }
            // Update skor BS — 1 desimal
            if (res.skor_bs !== undefined) {
                const el = document.getElementById('skor_bs_' + studentId);
                if (el) el.textContent = 'Skor: ' + parseFloat(res.skor_bs).toFixed(1);
            }
            // Update total isian per nomor — bulat
            if (ISIAN_MODE === 'per_nomor' && res.skor_isian !== undefined) {
                const el = document.getElementById('skor_isian_' + studentId);
                if (el) el.textContent = 'Total: ' + Math.round(res.skor_isian) + ' / 100';
            }
            // Update total essay per nomor — bulat
            if (ESSAY_MODE === 'per_nomor' && res.skor_essay !== undefined) {
                const el = document.getElementById('skor_essay_' + studentId);
                if (el) el.textContent = 'Total: ' + Math.round(res.skor_essay) + ' / 100';
            }

            // Update notif
            const notifEl = document.getElementById('notif_' + studentId);
            if (notifEl) {
                let notifHtml = '';
                if (res.notif_pg) notifHtml += `<div class="badge bg-warning text-dark d-block mt-1"><i class="bi bi-exclamation-triangle me-1"></i>PG: ${res.notif_pg}</div>`;
                if (res.notif_bs) notifHtml += `<div class="badge bg-warning text-dark d-block mt-1"><i class="bi bi-exclamation-triangle me-1"></i>BS: ${res.notif_bs}</div>`;
                notifEl.innerHTML = notifHtml;
            }

            // Update counter selesai
            updateKoreksiCounter();
            showAlert('success', 'Nilai berhasil disimpan!', 1500);
        } else {
            showAlert('danger', res.message || 'Gagal menyimpan!');
        }
    });
}

// ---- Update counter selesai ----
function updateKoreksiCounter() {
    const total = document.querySelectorAll('[id^="nilai_"]').length;
    let done = 0;
    document.querySelectorAll('[id^="nilai_"]').forEach(el => {
        if (!el.querySelector('.text-muted')) done++;
    });
    const badge = document.getElementById('koreksi_status_badge');
    if (badge) {
        badge.innerHTML = `<span class="badge ${done === total && total > 0 ? 'bg-success' : 'bg-warning text-dark'}">${done}/${total} selesai</span>`;
    }
}

// ---- Helper alert ----
function showAlert(type, message, autohide = 0) {
    const box = document.getElementById('alert_box');
    box.className = `alert alert-${type} alert-dismissible fade show mb-3`;
    box.innerHTML = `${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
    if (autohide) setTimeout(() => { box.classList.add('d-none'); }, autohide);
}

// Init
updateTotalBobot();
<?php if ($assessment['has_pg']): ?>updateTotalSoal('pg');<?php endif; ?>
<?php if ($assessment['has_bs']): ?>updateTotalSoal('bs');<?php endif; ?>

// ---- Toggle warna input kosong/isi ----
// Satu listener untuk seluruh tabel, berlaku semua input/textarea
const tabelKoreksi = document.getElementById('tabel_koreksi');
if (tabelKoreksi) {
    tabelKoreksi.addEventListener('input', function(e) {
        const el = e.target;
        if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
            el.classList.toggle('input-kosong', el.value.trim() === '');
        }
    });
}
</script>

<?= $this->endSection() ?>