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

<?php
$elementsData = [];
if (isset($cp) && !empty($cp['elements'])) {
    $elementsData = json_decode($cp['elements'], true);
}
if (!is_array($elementsData)) {
    $elementsData = [];
}
?>

<div class="row justify-content-center">
    <div class="col-12 col-lg-10 col-xl-8">
        <div class="card border-0 shadow-sm" style="border-radius: 12px;">
            <div class="card-header bg-white border-bottom-0 pt-4 px-4 pb-0">
                <div class="d-flex align-items-center gap-2">
                    <a href="/cp-management" class="btn btn-outline-secondary btn-sm p-2 rounded-circle" style="width: 36px; height: 36px; display: flex; align-items: center; justify-content: center;" title="Kembali ke Daftar">
                        <i class="bi bi-arrow-left"></i>
                    </a>
                    <div>
                        <h5 class="fw-bold mb-0 text-dark"><?= isset($cp) ? 'Edit' : 'Tambah' ?> Capaian Pembelajaran</h5>
                        <small class="text-muted">Masukkan data Capaian Pembelajaran (CP) resmi sesuai BSKAP Kemendikbudristek.</small>
                    </div>
                </div>
            </div>
            
            <div class="card-body p-4">
                <?php if (session()->getFlashdata('errors')): ?>
                <div class="alert alert-danger border-0 small" role="alert" style="background-color: #f8d7da; color: #842029; border-radius: 8px;">
                    <ul class="mb-0 ps-3">
                        <?php foreach (session()->getFlashdata('errors') as $error): ?>
                            <li><?= esc($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form action="<?= isset($cp) ? '/cp-management/update/' . $cp['id'] : '/cp-management/store' ?>" method="post">
                    <?= csrf_field() ?>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="academic_year_id" class="form-label fw-semibold text-dark">Tahun Ajaran <span class="text-danger">*</span></label>
                            <select name="academic_year_id" id="academic_year_id" class="form-select" required style="border-radius: 8px;">
                                <option value="">-- Pilih Tahun Ajaran --</option>
                                <?php foreach ($academic_years as $ay): ?>
                                    <option value="<?= $ay['id'] ?>" <?= (isset($cp) && $cp['academic_year_id'] == $ay['id']) || old('academic_year_id') == $ay['id'] ? 'selected' : '' ?>>
                                        <?= esc($ay['name']) ?> <?= $ay['is_active'] ? '(Aktif)' : '' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="phase" class="form-label fw-semibold text-dark">Fase Kurikulum <span class="text-danger">*</span></label>
                            <select name="phase" id="phase" class="form-select" required style="border-radius: 8px;">
                                <option value="">-- Pilih Fase --</option>
                                <option value="A" <?= old('phase', $cp['phase'] ?? '') === 'A' ? 'selected' : '' ?>>Fase A (Kelas 1 - 2 SD/MI)</option>
                                <option value="B" <?= old('phase', $cp['phase'] ?? '') === 'B' ? 'selected' : '' ?>>Fase B (Kelas 3 - 4 SD/MI)</option>
                                <option value="C" <?= old('phase', $cp['phase'] ?? '') === 'C' ? 'selected' : '' ?>>Fase C (Kelas 5 - 6 SD/MI)</option>
                                <option value="D" <?= old('phase', $cp['phase'] ?? '') === 'D' ? 'selected' : '' ?>>Fase D (Kelas 7 - 9 SMP/MTs)</option>
                                <option value="E" <?= old('phase', $cp['phase'] ?? '') === 'E' ? 'selected' : '' ?>>Fase E (Kelas 10 SMA/MA)</option>
                                <option value="F" <?= old('phase', $cp['phase'] ?? '') === 'F' ? 'selected' : '' ?>>Fase F (Kelas 11 - 12 SMA/MA)</option>
                            </select>
                        </div>
                    </div>

                    <!-- Pilihan Hubungan ke Mata Pelajaran Master -->
                    <div class="mb-3">
                        <label for="subject_id" class="form-label fw-semibold text-dark">Hubungkan ke Mata Pelajaran Master</label>
                        <select name="subject_id" id="subject_id" class="form-select" style="border-radius: 8px;">
                            <option value="">-- Hubungkan dengan Mapel Master (Opsional) --</option>
                            <?php foreach ($subjects as $s): ?>
                                <option value="<?= $s['id'] ?>" <?= (isset($cp) && $cp['subject_id'] == $s['id']) || old('subject_id') == $s['id'] ? 'selected' : '' ?> data-name="<?= esc($s['name']) ?>">
                                    <?= esc($s['name']) ?> (<?= esc($s['level']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text small">Jika terhubung dengan mapel master, nama mapel otomatis disamakan dengan master tersebut.</div>
                    </div>

                    <!-- Nama Mata Pelajaran -->
                    <div class="mb-3">
                        <label for="subject_name" class="form-label fw-semibold text-dark">Nama Mata Pelajaran <span class="text-danger">*</span></label>
                        <input type="text" name="subject_name" id="subject_name" class="form-control" placeholder="Contoh: Pendidikan Pancasila / Informatika" value="<?= old('subject_name', $cp['subject_name'] ?? '') ?>" required style="border-radius: 8px;">
                        <div class="form-text small">Jika tidak dihubungkan ke mapel master, isi nama mapel secara manual di sini.</div>
                    </div>



                    <!-- Elemen CP -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold text-dark mb-3">Elemen Capaian Pembelajaran</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">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">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>

                    <!-- Tombol Aksi -->
                    <div class="d-flex justify-content-end gap-2 border-top pt-4">
                        <a href="/cp-management" class="btn btn-light px-4 py-2" style="border-radius: 8px;">Batal</a>
                        <button type="submit" class="btn btn-primary px-4 py-2 fw-semibold" style="border-radius: 8px; background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%);">
                            <i class="bi bi-save me-1"></i> Simpan Data CP
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // Fungsi untuk mensinkronkan nama mapel jika pilihan master diubah
    function syncSubjectName() {
        const selectedOption = $('#subject_id option:selected');
        const masterId = selectedOption.val();
        
        if (masterId !== "") {
            const masterName = selectedOption.data('name');
            $('#subject_name').val(masterName);
            $('#subject_name').attr('readonly', true);
        } else {
            $('#subject_name').attr('readonly', false);
        }
    }

    // Jalankan saat load pertama kali
    syncSubjectName();

    // Trigger saat pilihan berubah
    $('#subject_id').on('change', function() {
        syncSubjectName();
    });

    // 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">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() {
        // Sisakan minimal 1 elemen
        if ($('.element-row').length > 1) {
            $(this).closest('.element-row').remove();
        } else {
            alert('Minimal harus ada 1 elemen CP.');
        }
    });
});
</script>
<?= $this->endSection() ?>
