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

<?php
$activeYearName = $activeYear['name'] ?? 'Tidak ada TA aktif';
$isViewingActive = $activeYear && ((int)$filterYearId === (int)($activeYear['id'] ?? 0));
?>

<!-- Filter Tahun Ajaran + Tombol Copy -->
<div class="row mb-3">
    <div class="col-md-12">
        <div class="card border-0 shadow-sm">
            <div class="card-body py-2">
                <div class="d-flex align-items-center gap-3 flex-wrap">
                    <div class="d-flex align-items-center gap-2">
                        <i class="bi bi-calendar-range text-primary"></i>
                        <span class="fw-semibold small">Tahun Ajaran:</span>
                    </div>
                    <form method="get" action="/classroom" class="d-flex align-items-center gap-2 mb-0">
                        <select name="year_id" class="form-select form-select-sm" style="min-width:180px" onchange="this.form.submit()">
                            <?php foreach ($allYears as $year): ?>
                            <option value="<?= $year['id'] ?>" <?= ((int)$filterYearId === (int)$year['id']) ? 'selected' : '' ?>>
                                <?= esc($year['name']) ?><?= ($activeYear && $year['id'] == $activeYear['id']) ? ' (Aktif)' : '' ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </form>

                    <button class="btn btn-sm btn-outline-secondary ms-auto" data-bs-toggle="modal" data-bs-target="#copyModal">
                        <i class="bi bi-copy me-1"></i>Copy Kelas dari TA Lain
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-plus-circle text-primary"></i>
                <span class="fw-semibold">Tambah Kelas</span>
                <span class="badge <?= $isViewingActive ? 'bg-success' : 'bg-secondary' ?> ms-auto small"><?= esc($viewingYearName ?: $activeYearName) ?></span>
            </div>
            <div class="card-body">

                <?php if (session()->getFlashdata('errors')): ?>
                <div class="alert alert-danger py-2">
                    <ul class="mb-0 ps-3 small">
                        <?php foreach (session()->getFlashdata('errors') as $error): ?>
                        <li><?= esc($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <?php if (session()->getFlashdata('error')): ?>
                <div class="alert alert-danger py-2 small"><?= session()->getFlashdata('error') ?></div>
                <?php endif; ?>

                <?php if (session()->getFlashdata('success')): ?>
                <div class="alert alert-success py-2 small"><?= session()->getFlashdata('success') ?></div>
                <?php endif; ?>

                <form action="/classroom/store" method="post">
                    <?= csrf_field() ?>
                    <!-- Kirim year_id TA yang sedang dilihat -->
                    <input type="hidden" name="year_id" value="<?= esc($filterYearId) ?>">
                    <div class="mb-3">
                        <label class="form-label">Nama Kelas <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control"
                            placeholder="Contoh: VII A, VIII B"
                            value="<?= old('name') ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tingkat <span class="text-danger">*</span></label>
                        <select name="grade_id" class="form-select" required>
                            <option value="">-- Pilih Tingkat --</option>
                            <?php foreach ($grades as $grade): ?>
                            <option value="<?= $grade['id'] ?>"
                                <?= (old('grade_id') == $grade['id']) ? 'selected' : '' ?>>
                                <?= esc($grade['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Jurusan <span class="text-muted small">(opsional)</span></label>
                        <select name="major_id" class="form-select">
                            <option value="">-- Tanpa Jurusan --</option>
                            <?php foreach ($majors as $major): ?>
                            <option value="<?= $major['id'] ?>"
                                <?= (old('major_id') == $major['id']) ? 'selected' : '' ?>>
                                <?= esc($major['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kapasitas <span class="text-danger">*</span></label>
                        <input type="number" name="capacity" class="form-control"
                            placeholder="Jumlah siswa maksimal"
                            value="<?= old('capacity', 30) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ID Grup WhatsApp <span class="text-muted small">(opsional)</span></label>
                        <div class="input-group input-group-sm">
                            <input type="text" name="wa_group_id" class="form-control"
                                placeholder="120363xxxxx@g.us"
                                value="<?= old('wa_group_id') ?>">
                            <button type="button" class="btn btn-outline-success" onclick="fetchWaGroups('create')">
                                <i class="bi bi-whatsapp me-1"></i>Muat Grup
                            </button>
                        </div>
                        <small class="text-muted">ID grup WA untuk kirim rekap absensi. Klik tombol untuk memuat dari Sidobe.</small>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-save me-2"></i>Simpan
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex align-items-center gap-2">
                <i class="bi bi-table text-primary"></i>
                <span class="fw-semibold">Daftar Kelas</span>
                <?php
                // Cari nama TA yang sedang ditampilkan
                $viewingYearName = '';
                foreach ($allYears as $yr) {
                    if ((int)$yr['id'] === (int)$filterYearId) {
                        $viewingYearName = $yr['name'];
                        break;
                    }
                }
                ?>
                <?php if ($viewingYearName): ?>
                <span class="badge <?= $isViewingActive ? 'bg-success' : 'bg-secondary' ?> ms-auto small">
                    <?= esc($viewingYearName) ?><?= $isViewingActive ? ' (Aktif)' : '' ?>
                </span>
                <?php endif; ?>
                <span class="badge bg-light text-dark border ms-1"><?= count($classrooms) ?> kelas</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%">#</th>
                                <th>Nama Kelas</th>
                                <th>Tingkat</th>
                                <th>Jurusan</th>
                                <th width="10%">Kapasitas</th>
                                <?php if ($isViewingActive): ?>
                                <th width="20%">Aksi</th>
                                <?php endif; ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($classrooms)): ?>
                            <tr>
                                <td colspan="<?= $isViewingActive ? 6 : 5 ?>" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox fs-3 d-block mb-2"></i>
                                    Belum ada data kelas untuk tahun ajaran ini
                                    <?php if ($isViewingActive && count($allYears) > 1): ?>
                                    <div class="mt-2">
                                        <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#copyModal">
                                            <i class="bi bi-copy me-1"></i>Copy dari TA Sebelumnya
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($classrooms as $i => $classroom): ?>
                            <tr>
                                <td><?= $i + 1 ?></td>
                                <td class="fw-semibold"><?= esc($classroom['name']) ?></td>
                                <td>
                                    <span class="badge bg-primary">
                                        <?= esc($classroom['grade_name']) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($classroom['major_name']): ?>
                                    <span class="badge bg-info text-dark">
                                        <?= esc($classroom['major_name']) ?>
                                    </span>
                                    <?php else: ?>
                                    <span class="text-muted small">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center"><?= $classroom['capacity'] ?></td>
                                <?php if ($isViewingActive): ?>
                                <td>
                                    <div class="d-flex gap-1">
                                        <button class="btn btn-sm btn-outline-primary"
                                            onclick="editClassroom(
                                                <?= $classroom['id'] ?>,
                                                '<?= esc($classroom['name']) ?>',
                                                <?= $classroom['grade_id'] ?>,
                                                <?= $classroom['major_id'] ?? 'null' ?>,
                                                <?= $classroom['capacity'] ?>
                                            )">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <a href="/classroom/delete/<?= $classroom['id'] ?>"
                                            class="btn btn-sm btn-outline-danger"
                                            onclick="return confirm('Hapus kelas ini?')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    </div>
                                </td>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">
                    <i class="bi bi-pencil me-2"></i>Edit Kelas
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editForm" method="post">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Nama Kelas</label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tingkat</label>
                        <select name="grade_id" id="editGradeId" class="form-select" required>
                            <?php foreach ($grades as $grade): ?>
                            <option value="<?= $grade['id'] ?>"><?= esc($grade['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Jurusan</label>
                        <select name="major_id" id="editMajorId" class="form-select">
                            <option value="">-- Tanpa Jurusan --</option>
                            <?php foreach ($majors as $major): ?>
                            <option value="<?= $major['id'] ?>"><?= esc($major['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kapasitas</label>
                        <input type="number" name="capacity" id="editCapacity" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ID Grup WhatsApp</label>
                        <div class="input-group input-group-sm">
                            <input type="text" name="wa_group_id" id="editWaGroupId" class="form-control" placeholder="120363xxxxx@g.us">
                            <button type="button" class="btn btn-outline-success" onclick="fetchWaGroups('edit')">
                                <i class="bi bi-whatsapp me-1"></i>Muat Grup
                            </button>
                        </div>
                        <small class="text-muted">ID grup WA untuk kirim rekap absensi ke grup kelas ini.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i>Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Copy dari TA Lain -->
<div class="modal fade" id="copyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">
                    <i class="bi bi-copy me-2"></i>Copy Kelas dari Tahun Ajaran Lain
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="/classroom/copy-from-year" method="post">
                <?= csrf_field() ?>
                <!-- TA tujuan = TA yang sedang dilihat -->
                <input type="hidden" name="to_year_id" value="<?= esc($filterYearId) ?>">
                <div class="modal-body">
                    <div class="alert alert-info small">
                        <i class="bi bi-info-circle me-1"></i>
                        Kelas akan dicopy ke <strong><?= esc($viewingYearName ?: $activeYearName) ?></strong>.
                        Kelas yang sudah ada (nama + tingkat sama) tidak akan diduplikat.
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Pilih Tahun Ajaran Sumber</label>
                        <select name="from_year_id" class="form-select" required>
                            <option value="">-- Pilih TA Sumber --</option>
                            <?php foreach ($allYears as $year): ?>
                            <?php if ((int)$year['id'] !== (int)$filterYearId): ?>
                            <option value="<?= $year['id'] ?>"><?= esc($year['name']) ?></option>
                            <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-copy me-2"></i>Copy Kelas
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
function editClassroom(id, name, gradeId, majorId, capacity) {
    document.getElementById('editName').value     = name;
    document.getElementById('editGradeId').value  = gradeId;
    document.getElementById('editMajorId').value  = majorId ?? '';
    document.getElementById('editCapacity').value = capacity;
    document.getElementById('editForm').action    = '/classroom/update/' + id;

    fetch('/classroom/get-wa-group/' + id)
        .then(r => r.json())
        .then(data => {
            document.getElementById('editWaGroupId').value = data.wa_group_id || '';
        });

    new bootstrap.Modal(document.getElementById('editModal')).show();
}

function fetchWaGroups(target) {
    const input = document.getElementById(target === 'edit' ? 'editWaGroupId' : document.querySelector('input[name="wa_group_id"]'));
    if (!input) return;

    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memuat...';

    fetch('/admin/tahfidz/get-wa-groups')
        .then(r => r.json())
        .then(data => {
            if (data.success && data.data && data.data.length > 0) {
                const menu = document.createElement('select');
                menu.className = 'form-select form-select-sm';
                menu.innerHTML = '<option value="">-- Pilih Grup --</option>';
                data.data.forEach(g => {
                    menu.appendChild(new Option(g.name + ' (' + g.id + ')', g.id));
                });
                menu.onchange = function() { input.value = this.value; };
                input.parentElement.replaceChild(menu, input);
                menu.focus();
            } else {
                alert('Tidak ada grup WA ditemukan atau API key belum diatur.');
            }
        })
        .catch(() => alert('Gagal memuat daftar grup WA.'))
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-whatsapp me-1"></i>Muat Grup';
        });
}
</script>
<?= $this->endSection() ?>