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

<?php
$elementsData = [];
if (!empty($device['cp_elements'])) {
    $elementsData = json_decode($device['cp_elements'], true);
}
if (!is_array($elementsData)) {
    $elementsData = [];
}
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-1 text-gray-800 fw-bold">Elemen Capaian Pembelajaran (CP)</h1>
            <p class="text-muted mb-0 small">Tinjau dan sesuaikan Elemen CP untuk kelas Anda berdasarkan data resmi admin.</p>
        </div>
        <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> Kembali ke Dashboard
        </a>
    </div>

    <?php if (session()->getFlashdata('error')) : ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" role="alert" style="border-radius: 8px;">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                <div><?= session()->getFlashdata('error') ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Main Form Column -->
        <div class="col-lg-8">
            <div class="card shadow-sm border-0 rounded-3 mb-4">
                <div class="card-header bg-white border-0 pt-4 pb-0 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-file-earmark-text text-primary fs-4"></i> Edit Elemen CP
                    </h5>
                    <?php if (!empty($masterCpElements) && $masterCpElements !== '[]'): ?>
                        <button type="button" class="btn btn-sm btn-outline-warning fw-bold" id="btnResetDefault">
                            <i class="bi bi-arrow-counterclockwise"></i> Reset ke Master Admin
                        </button>
                    <?php endif; ?>
                </div>
                <div class="card-body p-4">
                    <form action="/guru/learning-devices/cp/save/<?= $device['id'] ?>" method="post">
                        <?= csrf_field() ?>

                        <div class="mb-4">
                            <label class="form-label fw-semibold text-dark mb-3">Daftar Elemen dan Deskripsinya</label>
                            <div id="elements-container">
                                <?php if (!empty($elementsData)): ?>
                                    <?php foreach ($elementsData as $index => $element): ?>
                                        <div class="card bg-light border-0 mb-3 element-row" style="border-radius: 8px;">
                                            <div class="card-body p-3">
                                                <div class="d-flex justify-content-between mb-2">
                                                    <h6 class="mb-0 fw-semibold text-primary">Elemen</h6>
                                                    <button type="button" class="btn btn-sm btn-outline-danger remove-element-btn" style="border-radius: 6px;"><i class="bi bi-trash"></i> Hapus</button>
                                                </div>
                                                <div class="mb-2">
                                                    <input type="text" name="elements[name][]" class="form-control form-control-sm" placeholder="Nama Elemen (Contoh: Pemahaman Sains)" value="<?= esc($element['name']) ?>" required>
                                                </div>
                                                <div>
                                                    <textarea name="elements[description][]" class="form-control form-control-sm" rows="3" placeholder="Deskripsi Capaian Elemen" required><?= esc($element['description']) ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="card bg-light border-0 mb-3 element-row" style="border-radius: 8px;">
                                        <div class="card-body p-3">
                                            <div class="d-flex justify-content-between mb-2">
                                                <h6 class="mb-0 fw-semibold text-primary">Elemen Baru</h6>
                                                <button type="button" class="btn btn-sm btn-outline-danger remove-element-btn" style="border-radius: 6px;"><i class="bi bi-trash"></i> Hapus</button>
                                            </div>
                                            <div class="mb-2">
                                                <input type="text" name="elements[name][]" class="form-control form-control-sm" placeholder="Nama Elemen (Contoh: Pemahaman Sains)" required>
                                            </div>
                                            <div>
                                                <textarea name="elements[description][]" class="form-control form-control-sm" rows="3" placeholder="Deskripsi Capaian Elemen" required></textarea>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <button type="button" class="btn btn-outline-primary btn-sm mt-2" id="add-element-btn" style="border-radius: 8px;">
                                <i class="bi bi-plus-lg me-1"></i> Tambah Elemen
                            </button>
                            <div class="form-text text-muted small mt-3">
                                <i class="bi bi-info-circle me-1"></i> Elemen-elemen ini akan menjadi referensi utama bagi AI saat menurunkan draf Tujuan Pembelajaran (TP) dan Modul Ajar (RPM).
                            </div>
                        </div>

                        <div class="d-flex justify-content-end gap-2 pt-3 border-top">
                            <a href="/guru/learning-devices?device_id=<?= $device['id'] ?>" class="btn btn-light px-4" style="border-radius: 8px;">
                                Batal
                            </a>
                            <button type="submit" class="btn btn-primary px-4 fw-bold shadow-sm" style="border-radius: 8px;">
                                <i class="bi bi-save me-1"></i> Simpan Elemen
                            </button>
                        </div>
                    </form>
                </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">
                        Setiap Mata Pelajaran pada Kurikulum Merdeka dibagi menjadi beberapa <strong>Elemen</strong> dengan penjabaran kompetensinya masing-masing. 
                        <br><br>
                        Apabila admin belum memasukkan data Elemen resmi untuk mata pelajaran ini, Anda dipersilakan untuk menambahkan secara mandiri dan menyimpannya.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Hidden raw master CP elements for javascript reset action -->
<div id="rawMasterCp" style="display: none;"><?= esc($masterCpElements ?? '[]') ?></div>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // Fitur Tambah/Hapus Elemen CP
    $('#add-element-btn').on('click', function() {
        const html = `
            <div class="card bg-light border-0 mb-3 element-row" style="border-radius: 8px;">
                <div class="card-body p-3">
                    <div class="d-flex justify-content-between mb-2">
                        <h6 class="mb-0 fw-semibold text-primary">Elemen Baru</h6>
                        <button type="button" class="btn btn-sm btn-outline-danger remove-element-btn" style="border-radius: 6px;"><i class="bi bi-trash"></i> Hapus</button>
                    </div>
                    <div class="mb-2">
                        <input type="text" name="elements[name][]" class="form-control form-control-sm" placeholder="Nama Elemen (Contoh: Pemahaman Sains)" required>
                    </div>
                    <div>
                        <textarea name="elements[description][]" class="form-control form-control-sm" rows="3" placeholder="Deskripsi Capaian Elemen" required></textarea>
                    </div>
                </div>
            </div>
        `;
        $('#elements-container').append(html);
    });

    // Menghapus elemen
    $(document).on('click', '.remove-element-btn', function() {
        if ($('.element-row').length > 1) {
            $(this).closest('.element-row').remove();
        } else {
            alert('Minimal harus ada 1 elemen CP.');
        }
    });

    $('#btnResetDefault').on('click', function() {
        const rawContent = $('#rawMasterCp').text();
        if (rawContent.trim() === '' || rawContent.trim() === '[]') {
            Swal.fire({
                icon: 'info',
                title: 'Master CP Kosong',
                text: 'Elemen master dari admin belum tersedia di database lokal.',
                confirmButtonColor: '#4f46e5'
            });
            return;
        }

        Swal.fire({
            title: 'Reset ke Master Admin?',
            text: "Perubahan elemen yang telah Anda edit secara mandiri akan digantikan dengan elemen resmi default dari admin.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ffc107',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Reset Default',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                try {
                    const elements = JSON.parse(rawContent);
                    $('#elements-container').empty();
                    
                    if (Array.isArray(elements) && elements.length > 0) {
                        elements.forEach(function(el) {
                            const html = `
                                <div class="card bg-light border-0 mb-3 element-row" style="border-radius: 8px;">
                                    <div class="card-body p-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <h6 class="mb-0 fw-semibold text-primary">Elemen</h6>
                                            <button type="button" class="btn btn-sm btn-outline-danger remove-element-btn" style="border-radius: 6px;"><i class="bi bi-trash"></i> Hapus</button>
                                        </div>
                                        <div class="mb-2">
                                            <input type="text" name="elements[name][]" class="form-control form-control-sm" placeholder="Nama Elemen (Contoh: Pemahaman Sains)" value="${el.name.replace(/"/g, '&quot;')}" required>
                                        </div>
                                        <div>
                                            <textarea name="elements[description][]" class="form-control form-control-sm" rows="3" placeholder="Deskripsi Capaian Elemen" required>${el.description}</textarea>
                                        </div>
                                    </div>
                                </div>
                            `;
                            $('#elements-container').append(html);
                        });
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil di-Reset',
                        text: 'Elemen telah disesuaikan kembali dengan master dari admin.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                } catch (e) {
                    console.error('Error parsing master CP elements', e);
                }
            }
        });
    });
});
</script>
<?= $this->endSection() ?>
