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

<?= $this->section('content') ?>

<div class="container-fluid px-4 py-4">
    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h4 class="fw-bold text-dark mb-1 d-flex align-items-center gap-2">
                <i class="bi bi-patch-check-fill text-indigo"></i> Perencanaan Penilaian
            </h4>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 small">
                    <li class="breadcrumb-item"><a href="/dashboard" class="text-decoration-none text-muted">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="/guru/learning-devices" class="text-decoration-none text-muted">Perangkat Pembelajaran</a></li>
                    <li class="breadcrumb-item active text-dark fw-medium" aria-current="page">Perencanaan Penilaian</li>
                </ol>
            </nav>
        </div>
        <a href="/guru/learning-devices" class="btn btn-light border-0 shadow-sm text-muted hover-bg-light transition-all rounded-pill px-3">
            <i class="bi bi-arrow-left me-1"></i> Kembali
        </a>
    </div>

    <!-- Alert Messages -->
    <div id="alert-container"></div>

    <div class="row g-4">
        <div class="col-lg-8">
            <form id="penilaianForm">
                <div class="card shadow-sm border-0 rounded-3 mb-4">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="fw-bold mb-0 text-dark">Jadwal Pelaksanaan Evaluasi</h5>
                            <button type="button" class="btn btn-indigo text-white px-3 shadow-sm btn-generate-ai" style="background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%); border: none;">
                                <i class="bi bi-robot me-1"></i> Generate AI
                            </button>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover align-middle" id="tableJadwal">
                                <thead class="table-light">
                                    <tr>
                                        <th>TP</th>
                                        <th>Materi Pokok</th>
                                        <th>Jenis Asesmen</th>
                                        <th>Waktu Pelaksanaan</th>
                                        <th>Keterangan</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($penilaianData['jadwal_evaluasi'])): ?>
                                        <?php foreach ($penilaianData['jadwal_evaluasi'] as $index => $row): ?>
                                        <tr>
                                            <td><input type="text" name="jadwal_evaluasi[<?= $index ?>][tp_index]" class="form-control form-control-sm" value="<?= esc($row['tp_index'] ?? '') ?>"></td>
                                            <td><input type="text" name="jadwal_evaluasi[<?= $index ?>][materi]" class="form-control form-control-sm" value="<?= esc($row['materi'] ?? '') ?>"></td>
                                            <td><input type="text" name="jadwal_evaluasi[<?= $index ?>][jenis]" class="form-control form-control-sm" value="<?= esc($row['jenis'] ?? '') ?>"></td>
                                            <td><input type="text" name="jadwal_evaluasi[<?= $index ?>][waktu_pelaksanaan]" class="form-control form-control-sm" value="<?= esc($row['waktu_pelaksanaan'] ?? '') ?>"></td>
                                            <td><input type="text" name="jadwal_evaluasi[<?= $index ?>][keterangan]" class="form-control form-control-sm" value="<?= esc($row['keterangan'] ?? '') ?>"></td>
                                            <td><button type="button" class="btn btn-sm text-danger btn-delete-row"><i class="bi bi-trash"></i></button></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr class="empty-state"><td colspan="6" class="text-center text-muted py-4">Belum ada data perencanaan penilaian. Silakan klik Generate AI.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                            <button type="button" class="btn btn-sm btn-light border-0 shadow-sm add-row-jadwal"><i class="bi bi-plus-circle me-1"></i> Tambah Baris</button>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm border-0 rounded-3 mb-4">
                    <div class="card-body p-4">
                        <h5 class="fw-bold mb-4 text-dark">Teknik dan Bentuk Asesmen</h5>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover align-middle" id="tableTeknik">
                                <thead class="table-light">
                                    <tr>
                                        <th>TP</th>
                                        <th>Teknik Asesmen</th>
                                        <th>Bentuk Instrumen</th>
                                        <th>Waktu Pelaksanaan</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($penilaianData['teknik_asesmen'])): ?>
                                        <?php foreach ($penilaianData['teknik_asesmen'] as $index => $row): ?>
                                        <tr>
                                            <td><input type="text" name="teknik_asesmen[<?= $index ?>][tp_index]" class="form-control form-control-sm" value="<?= esc($row['tp_index'] ?? '') ?>"></td>
                                            <td><input type="text" name="teknik_asesmen[<?= $index ?>][teknik]" class="form-control form-control-sm" value="<?= esc($row['teknik'] ?? '') ?>"></td>
                                            <td><input type="text" name="teknik_asesmen[<?= $index ?>][bentuk]" class="form-control form-control-sm" value="<?= esc($row['bentuk'] ?? '') ?>"></td>
                                            <td><input type="text" name="teknik_asesmen[<?= $index ?>][waktu]" class="form-control form-control-sm" value="<?= esc($row['waktu'] ?? '') ?>"></td>
                                            <td><button type="button" class="btn btn-sm text-danger btn-delete-row"><i class="bi bi-trash"></i></button></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr class="empty-state"><td colspan="5" class="text-center text-muted py-4">Belum ada data teknik asesmen. Silakan klik Generate AI.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                            <button type="button" class="btn btn-sm btn-light border-0 shadow-sm add-row-teknik"><i class="bi bi-plus-circle me-1"></i> Tambah Baris</button>
                        </div>

                        <div class="mt-4 pt-3 border-top text-end">
                            <button type="button" class="btn btn-primary px-4 shadow-sm btn-save-penilaian" id="btnSave" style="background: linear-gradient(135deg, #4f46e5 0%, #3b82f6 100%); border: none;">
                                <i class="bi bi-save me-1"></i> Simpan Perencanaan Penilaian
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="col-lg-4">
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-dark mb-3"><i class="bi bi-book-half text-secondary me-2"></i> Identitas Perangkat</h6>
                    <table class="table table-sm table-borderless mb-0">
                        <tr>
                            <td class="text-muted" width="120">Fase</td>
                            <td width="10">:</td>
                            <td class="fw-bold text-dark py-1"><?= esc($device['phase']) ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted">Mata Pelajaran</td>
                            <td>:</td>
                            <td class="fw-bold text-dark py-1"><?= esc($device['subject_name']) ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted">Kelas</td>
                            <td>:</td>
                            <td class="fw-bold text-dark py-1">Kelas <?= esc($device['grade_name']) ?></td>
                        </tr>
                    </table>
                </div>
            </div>

            <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;">
                        Perencanaan Penilaian (Asesmen) adalah pemetaan jadwal asesmen awal (diagnostik), formatif, dan sumatif.<br><br>
                        <strong>Syarat AI:</strong> Pastikan Anda telah menyusun PROMES. AI akan membaca alokasi minggu dari Promes untuk menyusun jadwal penilaian secara otomatis agar sinkron dan selaras.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

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

    // Tambah Baris Manual
    $('.add-row-jadwal').on('click', function() {
        $('#tableJadwal .empty-state').remove();
        const idx = $('#tableJadwal tbody tr').length;
        $('#tableJadwal tbody').append(`
            <tr>
                <td><input type="text" name="jadwal_evaluasi[${idx}][tp_index]" class="form-control form-control-sm"></td>
                <td><input type="text" name="jadwal_evaluasi[${idx}][materi]" class="form-control form-control-sm"></td>
                <td><input type="text" name="jadwal_evaluasi[${idx}][jenis]" class="form-control form-control-sm"></td>
                <td><input type="text" name="jadwal_evaluasi[${idx}][waktu_pelaksanaan]" class="form-control form-control-sm"></td>
                <td><input type="text" name="jadwal_evaluasi[${idx}][keterangan]" class="form-control form-control-sm"></td>
                <td><button type="button" class="btn btn-sm text-danger btn-delete-row"><i class="bi bi-trash"></i></button></td>
            </tr>
        `);
    });

    $('.add-row-teknik').on('click', function() {
        $('#tableTeknik .empty-state').remove();
        const idx = $('#tableTeknik tbody tr').length;
        $('#tableTeknik tbody').append(`
            <tr>
                <td><input type="text" name="teknik_asesmen[${idx}][tp_index]" class="form-control form-control-sm"></td>
                <td><input type="text" name="teknik_asesmen[${idx}][teknik]" class="form-control form-control-sm"></td>
                <td><input type="text" name="teknik_asesmen[${idx}][bentuk]" class="form-control form-control-sm"></td>
                <td><input type="text" name="teknik_asesmen[${idx}][waktu]" class="form-control form-control-sm"></td>
                <td><button type="button" class="btn btn-sm text-danger btn-delete-row"><i class="bi bi-trash"></i></button></td>
            </tr>
        `);
    });

    $(document).on('click', '.btn-delete-row', function() {
        $(this).closest('tr').remove();
    });

    // Generate AI
    $('.btn-generate-ai').on('click', function() {
        const btn = $(this);
        const originalText = btn.html();
        
        Swal.fire({
            title: 'Generate Perencanaan Penilaian?',
            text: "AI akan menyusun draf teknik asesmen dan jadwal pelaksanaan berdasarkan alokasi waktu pada Promes.",
            icon: 'info',
            showCancelButton: true,
            confirmButtonColor: '#4f46e5',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Generate!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                btn.html('<span class="spinner-border spinner-border-sm"></span> Menghitung...').prop('disabled', true);
                
                $.ajax({
                    url: '/guru/learning-devices/penilaian/generate/' + deviceId,
                    type: 'POST',
                    data: { <?= csrf_token() ?>: '<?= csrf_hash() ?>' },
                    dataType: 'json',
                    success: function(res) {
                        if (res.status === 'success') {
                            Swal.fire('Berhasil!', 'Perencanaan Penilaian berhasil dirumuskan oleh AI.', 'success').then(() => {
                                window.location.reload();
                            });
                        } else {
                            Swal.fire('Gagal', res.message || 'Gagal memproses data.', 'error');
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error', 'Gagal terhubung ke server.', 'error');
                    },
                    complete: function() {
                        btn.html(originalText).prop('disabled', false);
                    }
                });
            }
        });
    });

    // Custom Serialize object helper for nested arrays
    function serializeFormJSON(form) {
        var unindexed_array = form.serializeArray();
        var indexed_array = {};
        $.map(unindexed_array, function(n, i){
            var keys = n['name'].split('[');
            var currentObj = indexed_array;
            for (var j = 0; j < keys.length; j++) {
                var key = keys[j].replace(']', '');
                if (j === keys.length - 1) {
                    currentObj[key] = n['value'];
                } else {
                    if (!currentObj[key]) currentObj[key] = {};
                    currentObj = currentObj[key];
                }
            }
        });
        // Convert pseudo-arrays to actual arrays
        function fixArrays(obj) {
            if (typeof obj !== 'object' || obj === null) return obj;
            const keys = Object.keys(obj);
            if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k)))) {
                const arr = [];
                for(let k in obj) {
                    arr[parseInt(k)] = fixArrays(obj[k]);
                }
                return arr;
            }
            for (let k in obj) {
                obj[k] = fixArrays(obj[k]);
            }
            return obj;
        }
        return fixArrays(indexed_array);
    }

    // Save Data
    $('#btnSave').on('click', function() {
        const btn = $(this);
        const originalText = btn.html();
        btn.html('<span class="spinner-border spinner-border-sm"></span> Menyimpan...').prop('disabled', true);

        const payload = serializeFormJSON($('#penilaianForm'));
        
        $.ajax({
            url: '/guru/learning-devices/penilaian/save/' + deviceId,
            type: 'POST',
            contentType: 'application/json',
            headers: {
                'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
            },
            data: JSON.stringify(payload),
            success: function(res) {
                if (res.status === 'success') {
                    Swal.fire({
                        toast: true,
                        position: 'top-end',
                        icon: 'success',
                        title: 'Perencanaan Penilaian Berhasil Disimpan',
                        showConfirmButton: false,
                        timer: 3000
                    });
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Gagal menyimpan data.', 'error');
            },
            complete: function() {
                btn.html(originalText).prop('disabled', false);
            }
        });
    });
});
</script>
<?= $this->endSection() ?>
