<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="container-fluid py-4">
    <!-- Breadcrumb & Header -->
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="/guru/learning-devices" class="text-decoration-none"><i class="bi bi-house-door"></i> Perangkat</a></li>
                    <li class="breadcrumb-item active" aria-current="page">KKTP</li>
                </ol>
            </nav>
            <h1 class="h3 mb-1 text-gray-800 fw-bold">Kriteria Ketercapaian TP (KKTP)</h1>
            <p class="text-muted mb-0 small">Rumuskan Indikator dan Rubrik Penilaian untuk setiap Tujuan Pembelajaran.</p>
        </div>
        <div class="d-flex gap-2">

            <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-sm btn-outline-secondary py-2 px-3" style="border-radius: 8px;">
                <i class="bi bi-arrow-left"></i> Kembali
        </a>
    </div>

    <div class="row">
        <!-- Main Form Column -->
        <div class="col-lg-8">
            <!-- CARD CONFIGURATION: ATUR INTERVAL NILAI KKTP -->
            <div class="card shadow-sm border-0 rounded-3 mb-4" style="border-left: 4px solid #0dcaf0;">
                <div class="card-header bg-white border-0 pt-4 pb-0">
                    <h5 class="fw-bold text-dark d-flex align-items-center gap-2 mb-0">
                        <i class="bi bi-sliders text-info fs-4"></i> Konfigurasi Batas Interval Nilai
                    </h5>
                    <small class="text-muted">Tentukan batas maksimal masing-masing kriteria. Rentang kriteria lainnya akan menyesuaikan secara otomatis.</small>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label for="int_bimbingan" class="form-label fw-bold text-danger small">Batas Maks Perlu Bimbingan</label>
                            <input type="number" id="int_bimbingan" class="form-control interval-input shadow-sm" value="<?= $intervals['bimbingan'] ?>" min="10" max="95" required style="border-radius: 8px;">
                            <div class="form-text small">Rentang: 0 - <span class="lbl-bimbingan-max"><?= $intervals['bimbingan'] ?></span></div>
                        </div>
                        <div class="col-md-4">
                            <label for="int_cukup" class="form-label fw-bold text-warning small">Batas Maks Cukup</label>
                            <input type="number" id="int_cukup" class="form-control interval-input shadow-sm" value="<?= $intervals['cukup'] ?>" min="15" max="97" required style="border-radius: 8px;">
                            <div class="form-text small">Rentang: <span class="lbl-cukup-min"><?= $intervals['bimbingan'] + 1 ?></span> - <span class="lbl-cukup-max"><?= $intervals['cukup'] ?></span></div>
                        </div>
                        <div class="col-md-4">
                            <label for="int_baik" class="form-label fw-bold text-success small">Batas Maks Baik</label>
                            <input type="number" id="int_baik" class="form-control interval-input shadow-sm" value="<?= $intervals['baik'] ?>" min="20" max="99" required style="border-radius: 8px;">
                            <div class="form-text small">Rentang: <span class="lbl-baik-min"><?= $intervals['cukup'] + 1 ?></span> - <span class="lbl-baik-max"><?= $intervals['baik'] ?></span></div>
                        </div>
                    </div>
                    <div class="mt-3 p-3 bg-light rounded text-dark small d-flex align-items-center gap-2" style="border-radius: 8px; border-left: 4px solid #3b82f6;">
                        <i class="bi bi-info-circle-fill text-primary fs-5"></i>
                        <div><strong>Sangat Baik (Taraf Pengayaan):</strong> Rentang nilai <span class="lbl-sangat-baik-min"><?= $intervals['baik'] + 1 ?></span> sampai dengan 100.</div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <h5 class="fw-bold text-dark d-flex align-items-center gap-2 mb-0">
                        <i class="bi bi-ui-checks-grid text-primary fs-4"></i> Editor KKTP & Rubrik
                    </h5>
                    <div class="d-flex gap-2">
                        <button id="btnGenerateAll" class="btn btn-sm btn-purple shadow-sm d-flex align-items-center gap-2" style="background-color: #6f42c1; border-color: #6f42c1; color: white;">
                            <i class="bi bi-robot"></i> Generate Semua AI
                        </button>
                    </div>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($tps)): ?>
                        <div class="p-5 text-center text-muted">
                            <i class="bi bi-inbox fs-1 d-block mb-3"></i>
                            <h5>Belum Ada Tujuan Pembelajaran</h5>
                            <p>Silakan merumuskan TP terlebih dahulu di menu sebelumnya.</p>
                            <a href="/guru/learning-devices/tp/<?= $device['id'] ?>" class="btn btn-primary mt-2">Menuju Menu TP</a>
                        </div>
                    <?php else: ?>
                        <form id="formKktp">
                            <div class="accordion accordion-flush" id="accordionKktp">
                                <?php foreach ($tps as $index => $tp): ?>
                                    <?php 
                                        $kktp = $kktpMap[$tp['id']] ?? null;
                                        $hasData = !empty($kktp) && !empty(trim($kktp['indicators'] ?? ''));
                                    ?>
                                    <div class="accordion-item border-bottom tp-item" data-tp-id="<?= $tp['id'] ?>">
                                        <h2 class="accordion-header" id="heading-<?= $tp['id'] ?>">
                                            <button class="accordion-button <?= $index === 0 ? '' : 'collapsed' ?> bg-light" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-<?= $tp['id'] ?>" aria-expanded="<?= $index === 0 ? 'true' : 'false' ?>" aria-controls="collapse-<?= $tp['id'] ?>">
                                                <div class="d-flex align-items-center w-100 pe-3">
                                                    <span class="badge bg-secondary me-2"><?= esc($tp['code']) ?></span>
                                                    <span class="text-truncate" style="max-width: 200px; font-size: 0.9rem;"><?= esc($tp['description']) ?></span>
                                                    <span class="ms-auto status-badge">
                                                        <?php if ($hasData): ?>
                                                            <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25"><i class="bi bi-check-circle me-1"></i> Tersimpan</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25"><i class="bi bi-exclamation-circle me-1"></i> Kosong</span>
                                                        <?php endif; ?>
                                                    </span>
                                                </div>
                                            </button>
                                        </h2>
                                        <div id="collapse-<?= $tp['id'] ?>" class="accordion-collapse collapse <?= $index === 0 ? 'show' : '' ?>" aria-labelledby="heading-<?= $tp['id'] ?>" data-bs-parent="#accordionKktp">
                                            <div class="accordion-body p-4 bg-white">
                                                <div class="row">
                                                    <!-- Indikator -->
                                                    <div class="col-12 mb-3">
                                                        <label class="form-label fw-bold text-dark small">Indikator Ketercapaian</label>
                                                        <textarea name="kktp[<?= $tp['id'] ?>][indicators]" class="form-control" rows="4" placeholder="Misal:&#10;- Mampu melakukan operasi hitung...&#10;- Mampu mengidentifikasi pola..." style="font-size: 0.88rem;"><?= esc($kktp['indicators'] ?? '') ?></textarea>
                                                        <div class="form-text small">Pisahkan setiap indikator dengan baris baru (Enter).</div>
                                                    </div>

                                                    <!-- Rubrik 4 Level -->
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label fw-bold text-danger small">Perlu Bimbingan (0 - <span class="span-bimbingan-max"><?= $intervals['bimbingan'] ?></span>)</label>
                                                        <textarea name="kktp[<?= $tp['id'] ?>][rubric_bimbingan]" class="form-control border-danger border-opacity-50" rows="3" placeholder="Siswa belum mampu..." style="font-size: 0.88rem;"><?= esc($kktp['rubric_bimbingan'] ?? '') ?></textarea>
                                                    </div>
 
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label fw-bold text-warning small">Cukup (<span class="span-cukup-min"><?= $intervals['bimbingan'] + 1 ?></span> - <span class="span-cukup-max"><?= $intervals['cukup'] ?></span>)</label>
                                                        <textarea name="kktp[<?= $tp['id'] ?>][rubric_cukup]" class="form-control border-warning border-opacity-50" rows="3" placeholder="Siswa mulai mampu..." style="font-size: 0.88rem;"><?= esc($kktp['rubric_cukup'] ?? '') ?></textarea>
                                                    </div>
 
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label fw-bold text-success small">Baik (<span class="span-baik-min"><?= $intervals['cukup'] + 1 ?></span> - <span class="span-baik-max"><?= $intervals['baik'] ?></span>)</label>
                                                        <textarea name="kktp[<?= $tp['id'] ?>][rubric_baik]" class="form-control border-success border-opacity-50" rows="3" placeholder="Siswa mampu secara tepat..." style="font-size: 0.88rem;"><?= esc($kktp['rubric_baik'] ?? '') ?></textarea>
                                                    </div>
 
                                                    <div class="col-md-6 mb-3">
                                                        <label class="form-label fw-bold text-primary small">Sangat Baik (<span class="span-sangat-baik-min"><?= $intervals['baik'] + 1 ?></span> - 100)</label>
                                                        <textarea name="kktp[<?= $tp['id'] ?>][rubric_sangat_baik]" class="form-control border-primary border-opacity-50" rows="3" placeholder="Siswa mampu secara akurat dan konsisten..." style="font-size: 0.88rem;"><?= esc($kktp['rubric_sangat_baik'] ?? '') ?></textarea>
                                                    </div>
                                                </div>

                                                <div class="d-flex justify-content-end mt-3 border-top pt-3">
                                                    <button type="button" class="btn btn-sm btn-outline-purple btn-generate-single fw-bold" data-tp-id="<?= $tp['id'] ?>" style="border-radius: 6px;">
                                                        <i class="bi bi-stars"></i> Generate Rubrik via AI
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
                
                <div class="card-footer bg-white border-top p-4 d-flex justify-content-end gap-2 flex-wrap">
                    <!--<a href="/guru/learning-devices/export/<?= $device['id'] ?>/kktp-docx" class="btn btn-outline-primary px-3 fw-bold shadow-sm" style="border-radius: 8px;">
                        <i class="bi bi-file-earmark-word"></i> Ekspor Word (DOCX)
                    </a>
                    <a href="/guru/learning-devices/export/<?= $device['id'] ?>/kktp-pdf" class="btn btn-outline-danger px-3 fw-bold shadow-sm" style="border-radius: 8px;">
                        <i class="bi bi-file-earmark-pdf"></i> Ekspor PDF
                    </a>
                    <a href="/guru/learning-devices/kktp/download-kktp/<?= $device['id'] ?>"  class="btn btn-outline-secondary px-3 fw-bold shadow-sm" style="border-radius: 8px;">
                        <i class="bi bi-printer"></i> Cetak PDF
                    </a>-->
                    <button id="btnSaveAll" class="btn btn-primary px-4 fw-bold shadow-sm ms-auto" style="border-radius: 8px; background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%); border: none;">
                        <i class="bi bi-save me-1"></i> Simpan KKTP
                    </button>
                </div>
            </div>
        </div>

        <!-- Sidebar Info Column -->
        <div class="col-lg-4">
            <!-- Identity Info Card -->
            <div class="card shadow-sm border-0 rounded-3 mb-4 bg-light border-start border-primary border-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark mb-3">Informasi Perangkat</h6>
                    <table class="table table-sm table-borderless mb-0 small text-muted">
                        <tr>
                            <td class="ps-0 py-1" style="width: 100px;">Mata Pelajaran</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1"><?= esc($device['subject_name']) ?></td>
                        </tr>
                        <tr>
                            <td class="ps-0 py-1">Tingkat Kelas</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1">Kelas <?= esc($device['grade_name']) ?></td>
                        </tr>
                        <tr>
                            <td class="ps-0 py-1">Fase</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1">Fase <?= esc($device['phase']) ?></td>
                        </tr>
                        <tr>
                            <td class="ps-0 py-1">Jenis Sekolah</td>
                            <td class="py-1">:</td>
                            <td class="fw-bold text-dark py-1"><?= ($device['school_type'] === 'madrasah') ? 'Madrasah (KMA)' : 'Sekolah Umum (Kemdikbud)' ?></td>
                        </tr>
                    </table>
                </div>
            </div>

            <!-- Guidelines Card -->
            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark d-flex align-items-center gap-2 mb-3">
                        <i class="bi bi-info-circle-fill text-primary"></i> Panduan Guru
                    </h6>
                    <p class="text-muted small text-justify leading-relaxed mb-0" style="font-size: 0.85rem;">
                        KKTP digunakan untuk mengukur tingkat pemahaman siswa terhadap TP tertentu.
                        <br><br>
                        <strong>Tips:</strong> Anda bisa mengeklik tombol <strong class="text-purple">Generate Semua AI</strong> untuk merumuskan indikator dan rubrik (4 level) untuk seluruh TP secara massal. Setelah selesai, Anda dapat menyuntingnya jika dirasa perlu, lalu tekan <strong>Simpan KKTP</strong>.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    const deviceId = <?= $device['id'] ?>;

    // Helper untuk mengubah textarea secara smooth
    function updateTextarea(name, val) {
        const el = $(`textarea[name="${name}"]`);
        el.val(val).hide().fadeIn(300);
    }

    // Fungsi Kalkulasi dan Update Interval Nilai secara dinamis
    function updateIntervals() {
        let bimbingan = parseInt($('#int_bimbingan').val());
        let cukup = parseInt($('#int_cukup').val());
        let baik = parseInt($('#int_baik').val());

        // Validasi agar selalu berurutan naik
        if (isNaN(bimbingan)) bimbingan = 59;
        if (isNaN(cukup)) cukup = 69;
        if (isNaN(baik)) baik = 84;

        if (bimbingan >= cukup) {
            cukup = bimbingan + 1;
            $('#int_cukup').val(cukup);
        }
        if (cukup >= baik) {
            baik = cukup + 1;
            $('#int_baik').val(baik);
        }
        if (baik >= 100) {
            baik = 99;
            $('#int_baik').val(baik);
        }

        let cukupMin = bimbingan + 1;
        let baikMin = cukup + 1;
        let sangatBaikMin = baik + 1;

        // Update teks card info
        $('.lbl-bimbingan-max').text(bimbingan);
        $('.lbl-cukup-min').text(cukupMin);
        $('.lbl-cukup-max').text(cukup);
        $('.lbl-baik-min').text(baikMin);
        $('.lbl-baik-max').text(baik);
        $('.lbl-sangat-baik-min').text(sangatBaikMin);

        // Update label span di form accordion
        $('.span-bimbingan-max').text(bimbingan);
        $('.span-cukup-min').text(cukupMin);
        $('.span-cukup-max').text(cukup);
        $('.span-baik-min').text(baikMin);
        $('.span-baik-max').text(baik);
        $('.span-sangat-baik-min').text(sangatBaikMin);
    }

    // Event listener input interval
    $(document).on('input', '.interval-input', function() {
        updateIntervals();
    });

    // Fungsi Generate 1 TP
    function generateTp(tpId, btnElement) {
        return new Promise((resolve, reject) => {
            const originalText = btnElement.html();
            btnElement.html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Sedang berpikir...').prop('disabled', true);

            $.ajax({
                url: '/guru/learning-devices/kktp/generate/' + deviceId,
                type: 'POST',
                data: { tp_id: tpId, <?= csrf_token() ?>: '<?= csrf_hash() ?>' },
                dataType: 'json',
                success: function(res) {
                    if (res.status === 'success') {
                        updateTextarea(`kktp[${tpId}][indicators]`, res.data.indicators);
                        updateTextarea(`kktp[${tpId}][rubric_bimbingan]`, res.data.rubric_bimbingan);
                        updateTextarea(`kktp[${tpId}][rubric_cukup]`, res.data.rubric_cukup);
                        updateTextarea(`kktp[${tpId}][rubric_baik]`, res.data.rubric_baik);
                        updateTextarea(`kktp[${tpId}][rubric_sangat_baik]`, res.data.rubric_sangat_baik);
                        
                        // Update badge status
                        $(`.tp-item[data-tp-id="${tpId}"] .status-badge`).html('<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25"><i class="bi bi-check-circle me-1"></i> Tersimpan</span>');
                        
                        resolve();
                    } else {
                        reject(res.message);
                    }
                },
                error: function(xhr) {
                    reject('Gagal terhubung ke server.');
                },
                complete: function() {
                    btnElement.html(originalText).prop('disabled', false);
                }
            });
        });
    }

    // Event Klik Generate Single
    $('.btn-generate-single').on('click', function() {
        const tpId = $(this).data('tp-id');
        const btn = $(this);
        
        generateTp(tpId, btn).then(() => {
            Swal.fire({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                icon: 'success',
                title: 'AI berhasil merumuskan rubrik untuk TP ini.'
            });
        }).catch((err) => {
            let errorText = typeof err === 'object' ? (err.message || JSON.stringify(err)) : err;
            Swal.fire({
                title: 'Gagal',
                text: errorText,
                icon: 'error'
            });
        });
    });

    // Event Klik Generate Semua (Sequential)
    $('#btnGenerateAll').on('click', async function() {
        const tpItems = $('.tp-item');
        if (tpItems.length === 0) return;

        const confirm = await Swal.fire({
            title: 'Generate Semua KKTP?',
            text: "AI akan memproses semua TP secara berurutan. Proses ini membutuhkan waktu beberapa saat. Lanjutkan?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#6f42c1',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Generate Semua'
        });

        if (confirm.isConfirmed) {
            let successCount = 0;
            const btnAll = $(this);
            const originalBtnText = btnAll.html();
            
            btnAll.prop('disabled', true);

            Swal.fire({
                title: 'Memproses AI...',
                html: 'Tunggu sebentar, AI sedang merumuskan indikator dan rubrik...<br><br><div class="progress"><div id="ai-progress-bar" class="progress-bar progress-bar-striped progress-bar-animated bg-purple" role="progressbar" style="width: 0%"></div></div>',
                allowOutsideClick: false,
                showConfirmButton: false
            });

            for (let i = 0; i < tpItems.length; i++) {
                const tpId = $(tpItems[i]).data('tp-id');
                const btnSingle = $(tpItems[i]).find('.btn-generate-single');
                
                // Update progress text
                const percentage = Math.round((i / tpItems.length) * 100);
                $('#ai-progress-bar').css('width', percentage + '%').text(percentage + '%');

                // Buka Accordion yang sedang diproses agar kelihatan
                $(`#collapse-${tpId}`).collapse('show');

                try {
                    await generateTp(tpId, btnSingle);
                    successCount++;
                } catch (err) {
                    console.error('Error on TP ' + tpId, err);
                }
            }

            $('#ai-progress-bar').css('width', '100%').text('100%');
            btnAll.html(originalBtnText).prop('disabled', false);

            if (successCount === tpItems.length) {
                Swal.fire({
                    title: 'Selesai!',
                    text: 'Semua KKTP berhasil dirumuskan oleh AI.',
                    icon: 'success'
                });
            } else {
                Swal.fire({
                    title: 'Selesai dengan Catatan',
                    text: `Berhasil: ${successCount}, Gagal: ${tpItems.length - successCount}. Anda dapat mengklik tombol "Generate AI" secara manual pada TP yang gagal.`,
                    icon: 'warning'
                });
            }
        }
    });

    // Simpan Semua
    $('#btnSaveAll').on('click', function() {
        const btn = $(this);
        const originalText = btn.html();
        
        // Ambil data form
        const formDataArray = $('#formKktp').serializeArray();
        const dataPayload = {};

        // Parse ke format dataPayload[tp_id][field] = value
        formDataArray.forEach(item => {
            // Regex untuk match kktp[tpId][field]
            const match = item.name.match(/kktp\[(\d+)\]\[(\w+)\]/);
            if (match) {
                const tpId = match[1];
                const field = match[2];
                if (!dataPayload[tpId]) dataPayload[tpId] = {};
                dataPayload[tpId][field] = item.value;
            }
        });

        // Bungkus data dengan setting intervalnya
        const payload = {
            intervals: {
                bimbingan: parseInt($('#int_bimbingan').val()) || 59,
                cukup: parseInt($('#int_cukup').val()) || 69,
                baik: parseInt($('#int_baik').val()) || 84
            },
            kktp: dataPayload
        };

        btn.html('<span class="spinner-border spinner-border-sm"></span> Menyimpan...').prop('disabled', true);

        $.ajax({
            url: '/guru/learning-devices/kktp/save/' + deviceId,
            type: 'POST',
            data: JSON.stringify(payload),
            contentType: 'application/json',
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: res.message,
                        icon: 'success'
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    let errorText = typeof res.message === 'object' ? JSON.stringify(res.message) : res.message;
                    Swal.fire({
                        title: 'Gagal',
                        text: errorText,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Gagal',
                    text: 'Terjadi kesalahan sistem.',
                    icon: 'error'
                });
            },
            complete: function() {
                btn.html(originalText).prop('disabled', false);
            }
        });
    });
});
</script>
<style>
.bg-purple {
    background-color: #6f42c1 !important;
}
.text-purple {
    color: #6f42c1 !important;
}
.btn-outline-purple {
    color: #6f42c1;
    border-color: #6f42c1;
}
.btn-outline-purple:hover {
    background-color: #6f42c1;
    color: white;
}
textarea {
    resize: vertical;
}
</style>
<?= $this->endSection() ?>
