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

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

    <div class="d-flex align-items-center gap-2 mb-4">
        <a href="/assessment" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div>
            <h4 class="mb-0 fw-bold">Buat Event Asesmen</h4>
            <small class="text-muted">Event asesmen bersama (ASTS, ASAS, ASAT) — berlaku untuk semua kelas</small>
        </div>
    </div>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('errors')): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach (session()->getFlashdata('errors') as $err): ?>
                    <li><?= esc($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form action="/assessment/store" method="POST">
        <?= csrf_field() ?>

        <div class="row g-4">

            <!-- Kolom kiri: info dasar -->
            <div class="col-lg-7">
                <div class="card shadow-sm">
                    <div class="card-header fw-semibold bg-white border-bottom">
                        <i class="bi bi-info-circle me-2 text-primary"></i>Informasi Event
                    </div>
                    <div class="card-body">

                        <!-- Tipe Asesmen -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Tipe Asesmen <span class="text-danger">*</span></label>
                            <div class="row g-2">
                                <?php foreach ($assessmentTypes as $type): ?>
                                <div class="col-md-4">
                                    <input type="radio" class="btn-check" name="assessment_type_id"
                                           id="type_<?= $type['id'] ?>" value="<?= $type['id'] ?>" required
                                           <?= old('assessment_type_id') == $type['id'] ? 'checked' : '' ?>>
                                    <label class="btn btn-outline-primary w-100 text-start" for="type_<?= $type['id'] ?>">
                                        <div class="fw-bold"><?= esc($type['code']) ?></div>
                                        <small class="text-muted"><?= esc($type['name']) ?></small>
                                    </label>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Nama Event -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Nama Event <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control"
                                   placeholder="misal: ASTS Ganjil 2026/2027"
                                   value="<?= old('name') ?>" required>
                            <div class="form-text">Nama ini akan muncul di laman koreksi guru</div>
                        </div>

                        <!-- Deskripsi -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Deskripsi <small class="text-muted fw-normal">(opsional)</small></label>
                            <textarea name="description" class="form-control" rows="2"
                                      placeholder="Keterangan tambahan..."><?= old('description') ?></textarea>
                        </div>

                        <!-- Periode Akademik -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Periode Akademik <span class="text-danger">*</span></label>
                            <select name="academic_period_id" class="form-select" required>
                                <option value="">-- Pilih Periode --</option>
                                <?php foreach ($periods as $p): ?>
                                    <option value="<?= $p['id'] ?>"
                                        <?= (old('academic_period_id') == $p['id'] || $activePeriod['id'] == $p['id']) ? 'selected' : '' ?>>
                                        <?= esc($p['year_name']) ?> — Semester <?= esc($p['semester']) ?>
                                        <?= $p['is_active'] ? '(Aktif)' : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Tanggal -->
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Tanggal Mulai <span class="text-danger">*</span></label>
                                <input type="date" name="start_date" class="form-control"
                                       value="<?= old('start_date') ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold">Tanggal Selesai <span class="text-danger">*</span></label>
                                <input type="date" name="end_date" class="form-control"
                                       value="<?= old('end_date') ?>" required>
                            </div>
                        </div>

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

            <!-- Kolom kanan: jenis soal -->
            <div class="col-lg-5">
                <div class="card shadow-sm">
                    <div class="card-header fw-semibold bg-white border-bottom">
                        <i class="bi bi-list-check me-2 text-success"></i>Jenis Soal
                        <small class="text-muted fw-normal ms-1">— pilih minimal 1</small>
                    </div>
                    <div class="card-body">

                        <!-- PG -->
                        <div class="border rounded p-3 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="has_pg"
                                       id="has_pg" value="1" <?= old('has_pg') ? 'checked' : '' ?>>
                                <label class="form-check-label fw-semibold" for="has_pg">
                                    Pilihan Ganda (PG)
                                </label>
                                <div class="form-text mt-1">Koreksi otomatis dari kunci jawaban</div>
                            </div>
                        </div>

                        <!-- BS -->
                        <div class="border rounded p-3 mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="has_bs"
                                       id="has_bs" value="1" <?= old('has_bs') ? 'checked' : '' ?>>
                                <label class="form-check-label fw-semibold" for="has_bs">
                                    Benar Salah (BS)
                                </label>
                                <div class="form-text mt-1">Koreksi otomatis dari kunci jawaban</div>
                            </div>
                        </div>

                        <!-- ISIAN -->
                        <div class="border rounded p-3 mb-3">
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" name="has_isian"
                                       id="has_isian" value="1"
                                       <?= old('has_isian') ? 'checked' : '' ?>
                                       onchange="toggleIsian(this.checked)">
                                <label class="form-check-label fw-semibold" for="has_isian">
                                    Isian Singkat
                                </label>
                            </div>
                            <div id="isian_options" class="<?= old('has_isian') ? '' : 'd-none' ?> ms-3">
                                <label class="form-label small fw-semibold">Mode Input Skor</label>
                                <div class="d-flex gap-3 mb-2">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="isian_mode"
                                               id="isian_total" value="total"
                                               <?= old('isian_mode', 'total') === 'total' ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="isian_total">Total Skor</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="isian_mode"
                                               id="isian_per_nomor" value="per_nomor"
                                               <?= old('isian_mode') === 'per_nomor' ? 'checked' : '' ?>
                                               onchange="toggleIsianSoal()">
                                        <label class="form-check-label" for="isian_per_nomor">Per Nomor Soal</label>
                                    </div>
                                </div>
                                <div id="isian_total_soal_wrap" class="<?= old('isian_mode') === 'per_nomor' ? '' : 'd-none' ?>">
                                    <label class="form-label small">Jumlah Soal Isian</label>
                                    <input type="number" name="isian_total_soal" class="form-control form-control-sm"
                                           min="1" max="50" value="<?= old('isian_total_soal', 5) ?>">
                                </div>
                            </div>
                        </div>

                        <!-- ESSAY -->
                        <div class="border rounded p-3 mb-3">
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" name="has_essay"
                                       id="has_essay" value="1"
                                       <?= old('has_essay') ? 'checked' : '' ?>
                                       onchange="toggleEssay(this.checked)">
                                <label class="form-check-label fw-semibold" for="has_essay">
                                    Essay
                                </label>
                            </div>
                            <div id="essay_options" class="<?= old('has_essay') ? '' : 'd-none' ?> ms-3">
                                <label class="form-label small fw-semibold">Mode Input Skor</label>
                                <div class="d-flex gap-3 mb-2">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="essay_mode"
                                               id="essay_total" value="total"
                                               <?= old('essay_mode', 'total') === 'total' ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="essay_total">Total Skor</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="essay_mode"
                                               id="essay_per_nomor" value="per_nomor"
                                               <?= old('essay_mode') === 'per_nomor' ? 'checked' : '' ?>
                                               onchange="toggleEssaySoal()">
                                        <label class="form-check-label" for="essay_per_nomor">Per Nomor Soal</label>
                                    </div>
                                </div>
                                <div id="essay_total_soal_wrap" class="<?= old('essay_mode') === 'per_nomor' ? '' : 'd-none' ?>">
                                    <label class="form-label small">Jumlah Soal Essay</label>
                                    <input type="number" name="essay_total_soal" class="form-control form-control-sm"
                                           min="1" max="20" value="<?= old('essay_total_soal', 5) ?>">
                                </div>
                            </div>
                        </div>

                        <div class="alert alert-info py-2 small mb-0">
                            <i class="bi bi-info-circle me-1"></i>
                            Event ini berlaku untuk <strong>semua kelas dan semua mapel</strong>.
                            Guru akan melihat event ini sesuai kelas yang diampu.
                        </div>

                    </div>
                </div>

                <!-- Card Bobot Admin -->
                <div class="card shadow-sm mt-3">
                    <div class="card-header fw-semibold bg-white border-bottom">
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" name="bobot_by_admin"
                                   id="bobot_by_admin" value="1"
                                   <?= old('bobot_by_admin') ? 'checked' : '' ?>
                                   onchange="toggleBobotAdmin(this.checked)">
                            <label class="form-check-label fw-semibold" for="bobot_by_admin">
                                <i class="bi bi-shield-lock me-1 text-primary"></i>
                                Bobot Diatur Admin
                            </label>
                            <div class="form-text fw-normal mt-1">
                                Jika aktif, guru tidak bisa mengubah bobot — hanya KKTP yang bisa diatur tiap guru.
                            </div>
                        </div>
                    </div>
                    <div id="admin_bobot_section" class="card-body <?= old('bobot_by_admin') ? '' : 'd-none' ?>">
                        <label class="form-label fw-semibold small">
                            Bobot Penilaian
                            <span id="admin_total_bobot_badge" class="badge ms-2 bg-danger">Total: 0%</span>
                        </label>
                        <div class="row g-2">
                            <div class="col-6" id="admin_bobot_pg_wrap">
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text bg-info-subtle text-info fw-bold">PG</span>
                                    <input type="number" name="admin_bobot_pg" id="admin_bobot_pg"
                                           class="form-control admin-bobot-input text-center"
                                           min="0" max="100" value="<?= old('admin_bobot_pg', 0) ?>"
                                           onchange="updateAdminBobot()">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                            <div class="col-6" id="admin_bobot_bs_wrap">
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text bg-warning-subtle text-warning fw-bold">BS</span>
                                    <input type="number" name="admin_bobot_bs" id="admin_bobot_bs"
                                           class="form-control admin-bobot-input text-center"
                                           min="0" max="100" value="<?= old('admin_bobot_bs', 0) ?>"
                                           onchange="updateAdminBobot()">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                            <div class="col-6" id="admin_bobot_isian_wrap">
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text bg-success-subtle text-success fw-bold">Isian</span>
                                    <input type="number" name="admin_bobot_isian" id="admin_bobot_isian"
                                           class="form-control admin-bobot-input text-center"
                                           min="0" max="100" value="<?= old('admin_bobot_isian', 0) ?>"
                                           onchange="updateAdminBobot()">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                            <div class="col-6" id="admin_bobot_essay_wrap">
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text bg-secondary-subtle text-secondary fw-bold">Essay</span>
                                    <input type="number" name="admin_bobot_essay" id="admin_bobot_essay"
                                           class="form-control admin-bobot-input text-center"
                                           min="0" max="100" value="<?= old('admin_bobot_essay', 0) ?>"
                                           onchange="updateAdminBobot()">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-text mt-2">
                            <i class="bi bi-info-circle me-1"></i>
                            Total harus <strong>100%</strong>. Kolom yang tidak aktif (jenis soal tidak dipilih) otomatis diabaikan.
                        </div>
                    </div>
                </div>

                <div class="d-grid mt-3">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="bi bi-check-lg me-2"></i>Buat Event Asesmen
                    </button>
                </div>
            </div>

        </div>
    </form>

</div>

<script>
function toggleIsian(checked) {
    const options = document.getElementById('isian_options');
    if (options) {
        options.classList.toggle('d-none', !checked);
        options.querySelectorAll('input[name="isian_mode"]').forEach(radio => {
            radio.disabled = !checked;
        });
    }
    toggleIsianSoal();
    updateAdminBobot();
}

function toggleEssay(checked) {
    const options = document.getElementById('essay_options');
    if (options) {
        options.classList.toggle('d-none', !checked);
        options.querySelectorAll('input[name="essay_mode"]').forEach(radio => {
            radio.disabled = !checked;
        });
    }
    toggleEssaySoal();
    updateAdminBobot();
}

function toggleIsianSoal() {
    const hasIsian = document.getElementById('has_isian')?.checked;
    const isPerNomor = document.getElementById('isian_per_nomor')?.checked;
    const wrap = document.getElementById('isian_total_soal_wrap');
    const input = wrap?.querySelector('input[name="isian_total_soal"]');
    
    if (wrap) {
        const shouldShow = hasIsian && isPerNomor;
        wrap.classList.toggle('d-none', !shouldShow);
        if (input) {
            input.disabled = !shouldShow;
        }
    }
}

function toggleEssaySoal() {
    const hasEssay = document.getElementById('has_essay')?.checked;
    const isPerNomor = document.getElementById('essay_per_nomor')?.checked;
    const wrap = document.getElementById('essay_total_soal_wrap');
    const input = wrap?.querySelector('input[name="essay_total_soal"]');
    
    if (wrap) {
        const shouldShow = hasEssay && isPerNomor;
        wrap.classList.toggle('d-none', !shouldShow);
        if (input) {
            input.disabled = !shouldShow;
        }
    }
}

function toggleBobotAdmin(checked) {
    const section = document.getElementById('admin_bobot_section');
    if (section) {
        section.classList.toggle('d-none', !checked);
    }
    updateAdminBobot();
}

function updateAdminBobot() {
    const hasPg    = document.getElementById('has_pg')?.checked;
    const hasBs    = document.getElementById('has_bs')?.checked;
    const hasIsian = document.getElementById('has_isian')?.checked;
    const hasEssay = document.getElementById('has_essay')?.checked;
    const bobotByAdmin = document.getElementById('bobot_by_admin')?.checked;

    const wrapPg = document.getElementById('admin_bobot_pg_wrap');
    const wrapBs = document.getElementById('admin_bobot_bs_wrap');
    const wrapIsian = document.getElementById('admin_bobot_isian_wrap');
    const wrapEssay = document.getElementById('admin_bobot_essay_wrap');

    if (wrapPg) {
        wrapPg.style.display = hasPg ? '' : 'none';
        const input = wrapPg.querySelector('input');
        if (input) input.disabled = !bobotByAdmin || !hasPg;
    }
    if (wrapBs) {
        wrapBs.style.display = hasBs ? '' : 'none';
        const input = wrapBs.querySelector('input');
        if (input) input.disabled = !bobotByAdmin || !hasBs;
    }
    if (wrapIsian) {
        wrapIsian.style.display = hasIsian ? '' : 'none';
        const input = wrapIsian.querySelector('input');
        if (input) input.disabled = !bobotByAdmin || !hasIsian;
    }
    if (wrapEssay) {
        wrapEssay.style.display = hasEssay ? '' : 'none';
        const input = wrapEssay.querySelector('input');
        if (input) input.disabled = !bobotByAdmin || !hasEssay;
    }

    let total = 0;
    if (hasPg && bobotByAdmin)    total += parseInt(document.getElementById('admin_bobot_pg')?.value    || 0);
    if (hasBs && bobotByAdmin)    total += parseInt(document.getElementById('admin_bobot_bs')?.value    || 0);
    if (hasIsian && bobotByAdmin) total += parseInt(document.getElementById('admin_bobot_isian')?.value || 0);
    if (hasEssay && bobotByAdmin) total += parseInt(document.getElementById('admin_bobot_essay')?.value || 0);

    const badge = document.getElementById('admin_total_bobot_badge');
    if (badge) {
        badge.textContent = 'Total: ' + total + '%';
        badge.className = 'badge ms-2 ' + (total === 100 ? 'bg-success' : 'bg-danger');
    }
}

document.addEventListener('DOMContentLoaded', function () {
    // Add event listeners for changes
    ['has_pg','has_bs','has_isian','has_essay'].forEach(id => {
        document.getElementById(id)?.addEventListener('change', updateAdminBobot);
    });

    document.querySelectorAll('input[name="isian_mode"]').forEach(r => {
        r.addEventListener('change', toggleIsianSoal);
    });
    document.querySelectorAll('input[name="essay_mode"]').forEach(r => {
        r.addEventListener('change', toggleEssaySoal);
    });

    // Run initial toggles to setup correct disabled states on page load
    const hasIsian = document.getElementById('has_isian')?.checked;
    toggleIsian(hasIsian);
    
    const hasEssay = document.getElementById('has_essay')?.checked;
    toggleEssay(hasEssay);

    const bobotByAdmin = document.getElementById('bobot_by_admin')?.checked;
    toggleBobotAdmin(bobotByAdmin);
});
</script>

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