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

<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-book text-primary"></i>
            <span class="fw-semibold">Setting Mapel Sekolah</span>
            <span class="badge bg-secondary"><?= count($subjects ?? []) ?></span>
        </div>
        <div class="d-flex gap-2">
            <input type="text" id="searchInput" class="form-control form-control-sm" placeholder="Cari mapel..." style="width: 200px;">
            <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#modalImport">
                <i class="bi bi-download me-1"></i>Ambil dari Master
            </button>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalAdd">
                <i class="bi bi-plus-circle me-1"></i>Tambah Manual
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="alert alert-info py-2 small">
            <i class="bi bi-info-circle me-1"></i>
            Jenjang Sekolah: <strong><?= esc($school_level ?? 'Belum diatur') ?></strong><br>
            Gunakan tombol <strong>↑ Turun</strong> dan <strong>↓ Naik</strong> untuk mengatur urutan mapel.
        </div>

        <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show py-2 small" role="alert">
            <i class="bi bi-check-circle me-1"></i><?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show py-2 small" role="alert">
            <i class="bi bi-exclamation-circle me-1"></i><?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <div class="table-responsive">
            <table class="table table-hover table-sm">
                <thead class="table-light">
                    <tr>
                        <th width="50">#</th>
                        <th>Kode</th>
                        <th>Nama Mata Pelajaran</th>
                        <th width="100">Tipe</th>
                        <th width="80">Status</th>
                        <th width="120">Urutan</th>
                        <th width="100">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($subjects)): ?>
                    <tr class="text-center">
                        <td colspan="7" class="text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
                            <small>Belum ada mapel. Klik "Ambil dari Master" untuk memulai.</small>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php $no = 1; $total = count($subjects); foreach ($subjects as $index => $s): ?>
                        <tr id="row-<?= $s['id'] ?>">
                            <td class="text-center"><?= $no++ ?></td>
                            <td><?= esc($s['code'] ?? '—') ?></td>
                            <td>
                                <?= esc($s['name']) ?>
                                <?php if ($s['subject_id'] === null): ?>
                                    <span class="badge bg-warning text-dark ms-1" style="font-size:9px">Lokal</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($s['subject_id'] === null): ?>
                                    <span class="badge bg-info">Lokal</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Dari Master</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input toggle-status" type="checkbox" 
                                        data-id="<?= $s['id'] ?>"
                                        <?= $s['is_active'] ? 'checked' : '' ?>>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex gap-1">
                                    <?php if ($index > 0): ?>
                                    <button class="btn btn-sm btn-outline-secondary move-up" data-id="<?= $s['id'] ?>">
                                        <i class="bi bi-arrow-up"></i>
                                    </button>
                                    <?php endif; ?>
                                    <?php if ($index < $total - 1): ?>
                                    <button class="btn btn-sm btn-outline-secondary move-down" data-id="<?= $s['id'] ?>">
                                        <i class="bi bi-arrow-down"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex gap-1">
                                    <button class="btn btn-sm btn-outline-primary edit-btn" 
                                        data-id="<?= $s['id'] ?>"
                                        data-code="<?= esc($s['code'] ?? '') ?>"
                                        data-name="<?= esc($s['name']) ?>"
                                        data-is-active="<?= $s['is_active'] ?>"
                                        data-bs-toggle="modal" data-bs-target="#modalEdit">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <a href="/school-subject/delete/<?= $s['id'] ?>" 
                                        class="btn btn-sm btn-outline-danger"
                                        onclick="return confirm('Hapus mapel <?= esc($s['name']) ?>?')">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal Import dari Master (sama seperti sebelumnya) -->
<div class="modal fade" id="modalImport" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form action="/school-subject/import-from-master" method="post">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <h6 class="modal-title fw-semibold">
                        <i class="bi bi-download me-2 text-success"></i>Ambil Mapel dari Master
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="small text-muted mb-3">
                        Pilih mapel yang akan ditambahkan ke sekolah ini (jenjang: <strong><?= esc($school_level ?? '-') ?></strong>)
                    </p>
                    <div id="masterSubjectsList" class="border rounded p-3" style="max-height:400px;overflow-y:auto">
                        <div class="text-center py-3">
                            <div class="spinner-border spinner-border-sm text-primary"></div>
                            <span class="ms-2 small">Memuat data...</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-success btn-sm">Import Terpilih</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Add Manual -->
<div class="modal fade" id="modalAdd" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="/school-subject/store" method="post">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <h6 class="modal-title fw-semibold">
                        <i class="bi bi-plus-circle me-2 text-primary"></i>Tambah Mapel Lokal
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Kode</label>
                        <input type="text" name="code" class="form-control" placeholder="Contoh: MULOK">
                        <div class="form-text">Opsional</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nama Mata Pelajaran <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required>
                        <div class="form-text">Contoh: Bahasa Daerah, Prakarya, dll</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-sm">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="" method="post" id="editForm">
                <?= csrf_field() ?>
                <!--<input type="hidden" name="_method" value="PUT">-->
                <div class="modal-header">
                    <h6 class="modal-title fw-semibold">
                        <i class="bi bi-pencil-square me-2 text-warning"></i>Edit Mapel
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Kode</label>
                        <input type="text" name="code" id="editCode" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nama Mata Pelajaran <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" id="editIsActive" value="1">
                            <label class="form-check-label" for="editIsActive">Aktif</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning btn-sm">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // ========== MOVE UP / MOVE DOWN ==========
    function updateOrderAfterMove() {
        var items = [];
        $("tbody tr").each(function() {
            var id = $(this).find('.move-up, .move-down').first().data('id');
            if (id) {
                items.push(id);
            }
        });
        
        $.ajax({
            url: '/school-subject/update-order',
            method: 'POST',
            data: {
                items: items,
                '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(data) {
                if (data.success) {
                    location.reload();
                } else {
                    showToast(data.message || 'Gagal menyimpan urutan', 'danger');
                }
            },
            error: function() {
                showToast('Terjadi kesalahan', 'danger');
            }
        });
    }
    
    // Move Up
    $(document).on('click', '.move-up', function() {
        var currentRow = $(this).closest('tr');
        var prevRow = currentRow.prev();
        
        if (prevRow.length) {
            currentRow.insertBefore(prevRow);
            updateOrderAfterMove();
        }
    });
    
    // Move Down
    $(document).on('click', '.move-down', function() {
        var currentRow = $(this).closest('tr');
        var nextRow = currentRow.next();
        
        if (nextRow.length) {
            currentRow.insertAfter(nextRow);
            updateOrderAfterMove();
        }
    });
    
    // ========== SEARCH FILTER ==========
    $('#searchInput').on('keyup', function() {
        var value = $(this).val().toLowerCase();
        $('tbody tr').each(function() {
            var text = $(this).find('td:eq(2)').text().toLowerCase();
            $(this).toggle(text.indexOf(value) > -1);
        });
    });
    
    // ========== LOAD MASTER SUBJECTS ==========
    $('#modalImport').on('show.bs.modal', function() {
        $('#masterSubjectsList').html('<div class="text-center py-3"><div class="spinner-border spinner-border-sm text-primary"></div><span class="ms-2 small">Memuat data...</span></div>');
        
        $.ajax({
            url: '/school-subject/get-master-subjects',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                if (data.length > 0) {
                    let html = '<div class="list-group list-group-flush">';
                    $.each(data, function(i, subject) {
                        const checked = subject.is_already_added ? 'checked disabled' : '';
                        html += `
                            <div class="list-group-item">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="subject_ids[]" 
                                        value="${subject.id}" id="sub_${subject.id}" ${checked}>
                                    <label class="form-check-label" for="sub_${subject.id}">
                                        <strong>${escapeHtml(subject.name)}</strong>
                                        ${subject.code ? `<small class="text-muted"> (${escapeHtml(subject.code)})</small>` : ''}
                                        ${subject.is_already_added ? '<span class="badge bg-secondary ms-2">Sudah ada</span>' : ''}
                                    </label>
                                </div>
                            </div>
                        `;
                    });
                    html += '</div>';
                    $('#masterSubjectsList').html(html);
                } else {
                    $('#masterSubjectsList').html('<div class="text-center py-3 text-muted">Tidak ada mapel yang tersedia</div>');
                }
            },
            error: function() {
                $('#masterSubjectsList').html('<div class="text-center py-3 text-danger">Gagal memuat data</div>');
            }
        });
    });
    
    // ========== TOGGLE STATUS ==========
    $(document).on('change', '.toggle-status', function() {
        const id = $(this).data('id');
        const isChecked = $(this).is(':checked');
        const $switch = $(this);
        
        $.ajax({
            url: `/school-subject/toggle-active/${id}`,
            method: 'POST',
            data: {
                '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
            },
            dataType: 'json',
            success: function(data) {
                if (!data.success) {
                    $switch.prop('checked', !isChecked);
                    showToast('Gagal mengubah status', 'danger');
                } else {
                    showToast('Status berhasil diubah', 'success');
                }
            },
            error: function() {
                $switch.prop('checked', !isChecked);
                showToast('Terjadi kesalahan', 'danger');
            }
        });
    });
    
    // ========== EDIT BUTTON ==========
    $(document).on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        const code = $(this).data('code');
        const name = $(this).data('name');
        const isActive = $(this).data('is-active');
        
        $('#editForm').attr('action', '/school-subject/update/' + id);
        $('#editCode').val(code);
        $('#editName').val(name);
        $('#editIsActive').prop('checked', isActive == 1);
    });
    
    // ========== HELPERS ==========
    function showToast(msg, type) {
        const toast = $(`
            <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 9999">
                <div class="toast align-items-center text-white bg-${type} border-0 show" role="alert">
                    <div class="d-flex">
                        <div class="toast-body small">${msg}</div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            </div>
        `);
        $('body').append(toast);
        setTimeout(() => toast.remove(), 2000);
    }
    
    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }
});
</script>
<?= $this->endSection() ?>