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

<?= $this->section('content') ?>

<style>
/* Highlight hari Minggu dengan warna merah */
.fc .fc-col-header-cell.fc-day-sun .fc-col-header-cell-cushion {
    color: #dc3545 !important;
}
.fc .fc-daygrid-day.fc-day-sun .fc-daygrid-day-number {
    color: #dc3545 !important;
    font-weight: bold;
}
.fc .fc-daygrid-day.fc-day-sun {
    background-color: rgba(220, 53, 69, 0.03) !important;
}
[data-bs-theme="dark"] .fc .fc-daygrid-day.fc-day-sun {
    background-color: rgba(220, 53, 69, 0.08) !important;
}
</style>

<div class="row g-3 mb-3">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <form method="get" class="row g-2 align-items-end">
                    <div class="col-auto">
                        <label class="form-label mb-1 small text-muted">Tahun Ajaran</label>
                        <select name="academic_year_id" class="form-select form-select-sm" onchange="this.form.submit()">
                            <?php foreach ($years as $y): ?>
                                <option value="<?= $y['id'] ?>" <?= ((int)$selectedYearId === (int)$y['id']) ? 'selected' : '' ?>>
                                    <?= esc($y['name']) ?> <?= $y['is_active'] ? '(Aktif)' : '' ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-auto ms-auto d-flex gap-2">
                        <a href="/academic-calendar/settings" class="btn btn-sm btn-outline-secondary" title="Pengaturan Sumber Acuan">
                            <i class="bi bi-gear"></i>
                        </a>
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#categoryModal">
                            <i class="bi bi-palette"></i> Kelola Kategori
                        </button>
                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#eventModal" onclick="resetEventForm()">
                            <i class="bi bi-plus-lg"></i> Tambah Kegiatan
                        </button>
                        <?php if ($selectedYearId): ?>
                            <a href="/academic-calendar/import-holidays/<?= $selectedYearId ?>"
                               class="btn btn-sm btn-outline-primary btn-import-holidays"
                               data-confirm="Impor seluruh Hari Libur Nasional & Cuti Bersama untuk Tahun Ajaran <?= esc($selectedYear['name'] ?? '') ?>?">
                                <i class="bi bi-cloud-arrow-down"></i> Impor Libur Nasional
                            </a>
                        <?php endif; ?>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-success dropdown-toggle" type="button" data-bs-toggle="dropdown" <?= $selectedYearId ? '' : 'disabled' ?>>
                                <i class="bi bi-printer"></i> Cetak / Export
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><h6 class="dropdown-header"><i class="bi bi-eye me-1"></i>Preview Dulu</h6></li>
                                <li>
                                    <a class="dropdown-item" target="_blank"
                                       href="/academic-calendar/preview-report/<?= $selectedYearId ?>">
                                        <i class="bi bi-file-earmark-text me-2 text-secondary"></i>Preview Laporan (List Kegiatan)
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" target="_blank"
                                       href="/academic-calendar/preview-grid/<?= $selectedYearId ?>/landscape">
                                        <i class="bi bi-grid-3x3 me-2 text-secondary"></i>Preview Grid Landscape
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" target="_blank"
                                       href="/academic-calendar/preview-grid/<?= $selectedYearId ?>/portrait">
                                        <i class="bi bi-grid-3x2-gap me-2 text-secondary"></i>Preview Grid Portrait
                                    </a>
                                </li>
                                <li><hr class="dropdown-divider"></li>
                                <li><h6 class="dropdown-header"><i class="bi bi-file-pdf me-1"></i>Langsung ke PDF</h6></li>
                                <li>
                                    <a class="dropdown-item" target="_blank"
                                       href="/academic-calendar/print-report/<?= $selectedYearId ?>">
                                        <i class="bi bi-file-earmark-pdf me-2 text-danger"></i>PDF Laporan (List Kegiatan)
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" target="_blank"
                                       href="/academic-calendar/print-grid/<?= $selectedYearId ?>/landscape">
                                        <i class="bi bi-file-earmark-pdf me-2 text-danger"></i>PDF Grid Landscape
                                    </a>
                                </li>
                                <li>
                                    <a class="dropdown-item" target="_blank"
                                       href="/academic-calendar/print-grid/<?= $selectedYearId ?>/portrait">
                                        <i class="bi bi-file-earmark-pdf me-2 text-danger"></i>PDF Grid Portrait
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <!-- KALENDER VISUAL -->
    <div class="col-lg-8">
        <div class="card">
            <div class="card-body">
                <div id="calendar"></div>
            </div>
        </div>
    </div>

    <!-- LEGENDA KATEGORI -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header bg-white fw-semibold">
                <i class="bi bi-info-circle me-1"></i> Keterangan Kategori
            </div>
            <div class="card-body p-2">
                <table class="table table-sm mb-0">
                    <tbody>
                    <?php foreach ($categories as $c): ?>
                        <tr>
                            <td style="width:28px;">
                                <span class="d-inline-block rounded" style="width:20px;height:20px;background:<?= esc($c['color']) ?>"></span>
                            </td>
                            <td style="width:50px;" class="fw-bold"><?= esc($c['code']) ?></td>
                            <td><?= esc($c['name']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- TABEL DAFTAR KEGIATAN -->
<div class="row g-3 mt-1">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-white fw-semibold">
                <i class="bi bi-list-ul me-1"></i> Daftar Kegiatan Tahun Ajaran <?= esc($selectedYear['name'] ?? '-') ?>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-hover align-middle" id="tblEvents">
                        <thead class="table-light">
                            <tr>
                                <th style="width:40px;">No</th>
                                <th>Kegiatan</th>
                                <th style="width:160px;">Kategori</th>
                                <th style="width:110px;">Mulai</th>
                                <th style="width:110px;">Selesai</th>
                                <th style="width:90px;">Jml Hari</th>
                                <th style="width:90px;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php $no = 1; foreach ($events as $e): ?>
                            <?php
                                $jmlHari = (strtotime($e['end_date']) - strtotime($e['start_date'])) / 86400 + 1;
                            ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><?= esc($e['title']) ?></td>
                                <td>
                                    <span class="badge" style="background:<?= esc($e['color']) ?>">
                                        <?= esc($e['category_name']) ?>
                                    </span>
                                </td>
                                <td><?= date('d-m-Y', strtotime($e['start_date'])) ?></td>
                                <td><?= date('d-m-Y', strtotime($e['end_date'])) ?></td>
                                <td><?= $jmlHari ?> hari</td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-primary"
                                        onclick='editEvent(<?= json_encode($e) ?>)'>
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <a href="/academic-calendar/delete/<?= $e['id'] ?>"
                                       class="btn btn-sm btn-outline-danger btn-delete"
                                       data-confirm="Hapus kegiatan ini?">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($events)): ?>
                            <tr><td colspan="7" class="text-center text-muted">Belum ada kegiatan untuk tahun ajaran ini.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ============================ -->
<!-- MODAL: TAMBAH / EDIT KEGIATAN -->
<!-- ============================ -->
<div class="modal fade" id="eventModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="eventForm" action="/academic-calendar/store">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <h5 class="modal-title" id="eventModalTitle">Tambah Kegiatan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="academic_year_id" value="<?= $selectedYearId ?>">

                    <div class="mb-3">
                        <label class="form-label">Kategori</label>
                        <select name="category_id" id="ev_category_id" class="form-select" required>
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= $c['id'] ?>" data-color="<?= esc($c['color']) ?>">
                                    <?= esc($c['code']) ?> - <?= esc($c['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Periode / Semester (opsional)</label>
                        <select name="academic_period_id" id="ev_period_id" class="form-select">
                            <option value="">-- Tidak terikat semester --</option>
                            <?php foreach ($periods as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= esc($p['semester']) ?> <?= esc($p['year_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Nama Kegiatan</label>
                        <input type="text" name="title" id="ev_title" class="form-control" required maxlength="200">
                    </div>

                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="form-label">Tanggal Mulai</label>
                            <input type="date" name="start_date" id="ev_start_date" class="form-control" required>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="form-label">Tanggal Selesai</label>
                            <input type="date" name="end_date" id="ev_end_date" class="form-control" required>
                        </div>
                    </div>

                    <div class="mb-1">
                        <label class="form-label">Keterangan (opsional)</label>
                        <textarea name="description" id="ev_description" class="form-control" rows="2"></textarea>
                    </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">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ============================ -->
<!-- MODAL: KELOLA KATEGORI -->
<!-- ============================ -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Kelola Kategori Kegiatan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive mb-3">
                    <table class="table table-sm align-middle">
                        <thead class="table-light">
                            <tr>
                                <th style="width:60px;">Warna</th>
                                <th style="width:90px;">Kode</th>
                                <th>Nama Kategori</th>
                                <th style="width:90px;">Libur?</th>
                                <th style="width:120px;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($categories as $c): ?>
                            <tr>
                                <td><span class="d-inline-block rounded" style="width:24px;height:24px;background:<?= esc($c['color']) ?>"></span></td>
                                <td><?= esc($c['code']) ?></td>
                                <td><?= esc($c['name']) ?></td>
                                <td><?= $c['is_libur'] ? '<span class="badge bg-danger">Libur</span>' : '<span class="badge bg-secondary">Bukan</span>' ?></td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-primary"
                                        onclick='editCategory(<?= json_encode($c) ?>)'>
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <a href="/academic-calendar/category/delete/<?= $c['id'] ?>"
                                       class="btn btn-sm btn-outline-danger btn-delete"
                                       data-confirm="Hapus kategori ini?">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <hr>
                <h6 id="categoryFormTitle">Tambah Kategori Baru</h6>
                <form method="post" id="categoryForm" action="/academic-calendar/category/store">
                    <?= csrf_field() ?>
                    <div class="row g-2">
                        <div class="col-md-2">
                            <label class="form-label small">Warna</label>
                            <input type="color" name="color" id="cat_color" class="form-control form-control-color w-100" value="#0d6efd">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label small">Kode</label>
                            <input type="text" name="code" id="cat_code" class="form-control" maxlength="10" required>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label small">Nama Kategori</label>
                            <input type="text" name="name" id="cat_name" class="form-control" maxlength="100" required>
                        </div>
                        <div class="col-md-1">
                            <label class="form-label small">Urutan</label>
                            <input type="number" name="sort_order" id="cat_sort_order" class="form-control" value="0">
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_libur" id="cat_is_libur" value="1">
                                <label class="form-check-label small" for="cat_is_libur">Hitung Libur</label>
                            </div>
                        </div>
                    </div>
                    <div class="mt-2 text-end">
                        <button type="button" class="btn btn-sm btn-secondary" id="btnCancelCategoryEdit" style="display:none" onclick="resetCategoryForm()">Batal Edit</button>
                        <button type="submit" class="btn btn-sm btn-primary" id="btnSubmitCategory">Simpan Kategori</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const calendarEl = document.getElementById('calendar');

    const calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        locale: 'id',
        height: 'auto',
        firstDay: 0, // Minggu
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,listYear'
        },
        buttonText: {
            today: 'Hari Ini',
            month: 'Bulan',
            list: 'Daftar'
        },
        events: '/academic-calendar/get-events?academic_year_id=<?= $selectedYearId ?>',
        eventClick: function (info) {
            const p = info.event.extendedProps;
            editEvent({
                id: info.event.id,
                title: info.event.title,
                category_id: p.category_id,
                academic_period_id: p.academic_period_id,
                start_date: p.start_date,
                end_date: p.end_date,
                description: p.description
            });
        }
    });

    calendar.render();
});

// Auto-pilih warna kategori saat dipilih (informatif saja)
document.getElementById('ev_category_id').addEventListener('change', function () {
    // tidak mengubah apa pun secara visual, hanya placeholder jika diperlukan ke depan
});

function resetEventForm() {
    document.getElementById('eventForm').reset();
    document.getElementById('eventForm').action = '/academic-calendar/store';
    document.getElementById('eventModalTitle').innerText = 'Tambah Kegiatan';

    // hapus method override jika ada
    const old = document.getElementById('eventMethodOverride');
    if (old) old.remove();
}

function editEvent(ev) {
    const modalEl = document.getElementById('eventModal');
    const modal = bootstrap.Modal.getOrCreateInstance(modalEl);

    document.getElementById('eventModalTitle').innerText = 'Edit Kegiatan';
    document.getElementById('eventForm').action = '/academic-calendar/update/' + ev.id;

    document.getElementById('ev_category_id').value = ev.category_id || '';
    document.getElementById('ev_period_id').value = ev.academic_period_id || '';
    document.getElementById('ev_title').value = ev.title || '';
    document.getElementById('ev_start_date').value = ev.start_date || '';
    document.getElementById('ev_end_date').value = ev.end_date || '';
    document.getElementById('ev_description').value = ev.description || '';

    modal.show();
}

// ===== Kategori =====
function editCategory(cat) {
    document.getElementById('categoryFormTitle').innerText = 'Edit Kategori: ' + cat.name;
    document.getElementById('categoryForm').action = '/academic-calendar/category/update/' + cat.id;
    document.getElementById('cat_color').value = cat.color;
    document.getElementById('cat_code').value = cat.code;
    document.getElementById('cat_name').value = cat.name;
    document.getElementById('cat_sort_order').value = cat.sort_order;
    document.getElementById('cat_is_libur').checked = (parseInt(cat.is_libur) === 1);
    document.getElementById('btnCancelCategoryEdit').style.display = 'inline-block';
    document.getElementById('btnSubmitCategory').innerText = 'Update Kategori';
}

function resetCategoryForm() {
    document.getElementById('categoryFormTitle').innerText = 'Tambah Kategori Baru';
    document.getElementById('categoryForm').action = '/academic-calendar/category/store';
    document.getElementById('categoryForm').reset();
    document.getElementById('cat_color').value = '#0d6efd';
    document.getElementById('btnCancelCategoryEdit').style.display = 'none';
    document.getElementById('btnSubmitCategory').innerText = 'Simpan Kategori';
}

// Konfirmasi hapus
document.querySelectorAll('.btn-delete').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
        e.preventDefault();
        const url = this.getAttribute('href');
        const msg = this.getAttribute('data-confirm') || 'Yakin ingin menghapus data ini?';

        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Konfirmasi',
                text: msg,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, hapus',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) window.location.href = url;
            });
        } else if (confirm(msg)) {
            window.location.href = url;
        }
    });
});

// Konfirmasi impor
document.querySelectorAll('.btn-import-holidays').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
        e.preventDefault();
        const url = this.getAttribute('href');
        const msg = this.getAttribute('data-confirm') || 'Yakin ingin mengimpor data ini?';

        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Impor Libur Nasional',
                text: msg,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Ya, Impor',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Memproses...',
                        text: 'Sedang menarik data libur resmi pemerintah',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    window.location.href = url;
                }
            });
        } else if (confirm(msg)) {
            window.location.href = url;
        }
    });
});
</script>
<?= $this->endSection() ?>