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

<div class="card border-0 shadow-sm" style="border-radius: 12px;">
    <div class="card-header bg-white border-bottom-0 d-flex align-items-center justify-content-between flex-wrap gap-2 pt-4 px-4 pb-0">
        <div class="d-flex align-items-center gap-2">
            <div class="bg-primary bg-opacity-10 text-primary rounded p-2" style="width: 40px; height: 40px; display: flex; align-items: center; justify-content: center;">
                <i class="bi bi-journal-check fs-5"></i>
            </div>
            <div>
                <h5 class="fw-bold mb-0 text-dark">Master Capaian Pembelajaran (CP)</h5>
                <small class="text-muted">Kelola data resmi CP lokal untuk referensi AI penyusunan perangkat mengajar guru.</small>
            </div>
        </div>
        <a href="/cp-management/create" class="btn btn-primary btn-sm py-2 px-3 fw-semibold" style="border-radius: 8px;">
            <i class="bi bi-plus-circle me-1"></i> Tambah CP Baru
        </a>
    </div>
    <div class="card-body p-4">
        <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm py-2 small" role="alert" style="background-color: #d1e7dd; color: #0f5132; border-radius: 8px;">
            <i class="bi bi-check-circle-fill me-2"></i><?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>

        <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm py-2 small" role="alert" style="background-color: #f8d7da; color: #842029; border-radius: 8px;">
            <i class="bi bi-exclamation-triangle-fill me-2"></i><?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>

        <div class="table-responsive mt-3">
            <table class="table table-hover align-middle table-sm" id="cpTable">
                <thead class="table-light">
                    <tr>
                        <th width="40" class="text-center py-3">#</th>
                        <th width="150">Tahun & Pemilik</th>
                        <th width="80">Fase</th>
                        <th width="200">Mata Pelajaran</th>
                        <th>Elemen Capaian Pembelajaran (CP)</th>
                        <th width="120" class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($cps)): ?>
                    <tr>
                        <td colspan="6" class="text-center text-muted py-5">
                            <i class="bi bi-journal-x fs-1 d-block mb-3 opacity-25"></i>
                            <span class="d-block fw-semibold text-secondary">Belum Ada Data Master CP</span>
                            <small class="text-muted">Klik tombol "Tambah CP Baru" untuk memasukkan teks Capaian Pembelajaran.</small>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($cps as $index => $cp): ?>
                        <tr>
                            <td class="text-center fw-medium text-secondary"><?= $index + 1 ?></td>
                            <td>
                                <div class="fw-semibold text-dark mb-1" style="font-size: 0.85rem;">
                                    <i class="bi bi-calendar-range me-1 text-muted"></i> <?= esc($cp['academic_year_name'] ?? 'Semua Tahun') ?>
                                </div>
                                <div class="small text-muted">
                                    <i class="bi bi-person me-1"></i> 
                                    <?php if (!empty($cp['user_name'])): ?>
                                        <?= esc($cp['user_name']) ?>
                                    <?php else: ?>
                                        <span class="badge bg-secondary opacity-75">Sistem / Admin</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-indigo-subtle text-indigo px-3 py-2" style="font-size: 0.85rem; border-radius: 6px; color: #4f46e5; background-color: #eef2ff;">
                                    Fase <?= esc($cp['phase']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="fw-bold text-dark"><?= esc($cp['subject_name']) ?></div>
                                <?php if (!empty($cp['master_subject_name'])): ?>
                                    <small class="text-muted"><i class="bi bi-link-45deg"></i> Terkait Master: <?= esc($cp['master_subject_name']) ?></small>
                                <?php else: ?>
                                    <span class="badge bg-light text-secondary border border-light-subtle" style="font-size: 0.75rem;">Mapel Kustom</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                    $elements = !empty($cp['elements']) ? json_decode($cp['elements'], true) : [];
                                    $elementsCount = is_array($elements) ? count($elements) : 0;
                                ?>
                                <?php if ($elementsCount > 0): ?>
                                    <ul class="mb-1 ps-3 small text-muted">
                                    <?php 
                                        $limit = 2;
                                        foreach (array_slice($elements, 0, $limit) as $el) {
                                            echo '<li>' . esc($el['name']) . '</li>';
                                        }
                                        if ($elementsCount > $limit) {
                                            echo '<li><span class="fst-italic text-secondary">... +'.($elementsCount - $limit).' elemen lain</span></li>';
                                        }
                                    ?>
                                    </ul>
                                <?php else: ?>
                                    <span class="text-muted small fst-italic">Belum ada elemen</span>
                                <?php endif; ?>

                                <div class="mt-1 d-flex gap-2 align-items-center">
                                    <button type="button" class="btn btn-link p-0 small text-primary fw-semibold btn-view-full" style="font-size: 0.8rem; text-decoration: none;" data-subject="<?= esc($cp['subject_name']) ?>" data-phase="<?= esc($cp['phase']) ?>" data-elements="<?= esc($cp['elements'] ?? '[]') ?>" data-bs-toggle="modal" data-bs-target="#modalViewContent">
                                        Lihat Rincian Deskripsi
                                    </button>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="d-inline-flex gap-2">
                                    <?php if (session()->get('user_role') !== 'guru' || session()->get('user_id') == $cp['user_id']): ?>
                                        <a href="/cp-management/edit/<?= $cp['id'] ?>" class="btn btn-sm btn-outline-primary" title="Edit CP" style="border-radius: 6px;">
                                            <i class="bi bi-pencil-square"></i>
                                        </a>
                                        <form action="/cp-management/delete/<?= $cp['id'] ?>" method="post" onsubmit="return confirm('Apakah Anda yakin ingin menghapus data master CP ini?')">
                                            <?= csrf_field() ?>
                                            <button type="submit" class="btn btn-sm btn-outline-danger" title="Hapus CP" style="border-radius: 6px;">
                                                <i class="bi bi-trash3"></i>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <span class="badge bg-light text-muted border" title="Hanya pemilik atau Admin yang dapat mengubah CP ini"><i class="bi bi-lock-fill"></i> Read Only</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal View Content -->
<div class="modal fade" id="modalViewContent" tabindex="-1" aria-labelledby="modalViewContentLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content border-0 shadow" style="border-radius: 14px;">
            <div class="modal-header border-bottom-0 pb-0 pt-4 px-4">
                <div>
                    <h6 class="modal-title fw-bold text-dark" id="modalViewContentLabel">Elemen Capaian Pembelajaran (CP)</h6>
                    <small class="text-muted" id="modalViewContentSubtitle">-</small>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div id="modalElementsBody">
                    <!-- Elemen akan di-render di sini -->
                </div>
            </div>
            <div class="modal-footer border-top-0 pt-0 pb-4 px-4">
                <button type="button" class="btn btn-secondary btn-sm py-2 px-4" style="border-radius: 8px;" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // Hanya init DataTable jika ada data (kolom lengkap)
    var hasData = $('#cpTable tbody tr').length > 0 && $('#cpTable tbody tr:first td').length >= 6;
    if (!hasData) {
        $('#cpTable').addClass('table');
        return;
    }
    $('#cpTable').DataTable({
        language: {
            processing: "Sedang memproses...",
            search: "Cari:",
            lengthMenu: "Tampilkan _MENU_ data",
            info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
            infoEmpty: "Tidak ada data",
            infoFiltered: "(disaring dari _MAX_ data keseluruhan)",
            loadingRecords: "Sedang memuat...",
            zeroRecords: "Tidak ada data yang ditemukan",
            emptyTable: "Tidak ada data",
            paginate: {
                first: "Pertama",
                previous: "Sebelumnya",
                next: "Selanjutnya",
                last: "Terakhir"
            }
        },
        pageLength: 10,
        order: [[2, 'asc'], [1, 'asc']]
    });

    // Handle view detail modal
    $('.btn-view-full').on('click', function() {
        const subject = $(this).data('subject');
        const phase = $(this).data('phase');
        const elementsRaw = $(this).data('elements');

        $('#modalViewContentLabel').text('Capaian Pembelajaran (CP) - ' + subject);
        $('#modalViewContentSubtitle').text('Fase ' + phase);

        let elementsHtml = '';
        try {
            const elements = typeof elementsRaw === 'string' ? JSON.parse(elementsRaw) : elementsRaw;
            if (Array.isArray(elements) && elements.length > 0) {
                elements.forEach(function(el, idx) {
                    elementsHtml += `
                        <div class="mb-3">
                            <div class="fw-semibold text-dark" style="font-size: 0.9rem;">${idx + 1}. ${el.name}</div>
                            <div class="bg-light p-3 rounded mt-2 text-muted" style="font-size: 0.85rem; line-height: 1.5; white-space: pre-wrap;">${el.description}</div>
                        </div>
                    `;
                });
            } else {
                elementsHtml = '<div class="text-muted small fst-italic">Belum ada data elemen untuk CP ini.</div>';
            }
        } catch (e) {
            elementsHtml = '<div class="text-muted small fst-italic">Gagal memuat elemen.</div>';
        }
        $('#modalElementsBody').html(elementsHtml);
    });
});
</script>
<?= $this->endSection() ?>
