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

<!-- Alert Errors terpadu -->
<?php if (session()->getFlashdata('errors')): ?>
<div class="alert alert-danger alert-dismissible fade show mb-3" role="alert">
    <i class="bi bi-exclamation-triangle-fill me-2"></i><strong>Ada kesalahan input:</strong>
    <ul class="mb-0 mt-1 ps-3 small">
        <?php foreach (session()->getFlashdata('errors') as $error): ?>
        <li><?= esc($error) ?></li>
        <?php endforeach; ?>
    </ul>
    <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 mb-3" role="alert">
    <i class="bi bi-exclamation-triangle-fill me-2"></i><?= session()->getFlashdata('error') ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Baris Info Status Aktif Terpadu -->
<div class="row g-3 mb-4">
    <!-- Tahun Ajaran Aktif -->
    <div class="col-md-6">
        <div class="card border-success h-100 bg-success bg-opacity-10">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="rounded-circle bg-success text-white p-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                    <i class="bi bi-calendar-check fs-4"></i>
                </div>
                <div>
                    <div class="text-success small fw-semibold">Tahun Ajaran Aktif</div>
                    <?php if ($activeYear): ?>
                    <div class="h5 fw-bold text-success mb-0"><?= esc($activeYear['name']) ?></div>
                    <small class="text-success small opacity-75">
                        <?= date('d M Y', strtotime($activeYear['start_date'])) ?> —
                        <?= date('d M Y', strtotime($activeYear['end_date'])) ?>
                    </small>
                    <?php else: ?>
                    <p class="text-muted small mb-0">Belum ada tahun ajaran aktif</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <!-- Periode Akademik Aktif -->
    <div class="col-md-6">
        <div class="card border-primary h-100 bg-primary bg-opacity-10">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="rounded-circle bg-primary text-white p-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                    <i class="bi bi-calendar3-range fs-4"></i>
                </div>
                <div>
                    <div class="text-primary small fw-semibold">Periode Akademik Aktif</div>
                    <?php if ($active): ?>
                    <div class="h5 fw-bold text-primary mb-0">
                        <?= esc($active['year_name']) ?> — <span class="badge bg-primary fs-7"><?= esc($active['semester']) ?></span>
                    </div>
                    <small class="text-primary small opacity-75">
                        <?= date('d M Y', strtotime($active['start_date'])) ?> —
                        <?= date('d M Y', strtotime($active['end_date'])) ?>
                    </small>
                    <?php else: ?>
                    <p class="text-muted small mb-0">Belum ada periode aktif</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.year-row {
    transition: background-color 0.15s ease-in-out;
}
.year-row:hover {
    background-color: rgba(var(--bs-primary-rgb), 0.05) !important;
}
.year-row.table-primary {
    background-color: rgba(var(--bs-primary-rgb), 0.1) !important;
    font-weight: 500;
}
</style>

<div class="row g-4">
    <!-- KOLOM KIRI: TAHUN AJARAN -->
    <div class="col-lg-6">
        <!-- Tabel Daftar Tahun Ajaran -->
        <div class="card border-light shadow-sm">
            <div class="card-header bg-white py-3 d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center gap-2">
                    <i class="bi bi-table text-primary fs-5"></i>
                    <div>
                        <span class="fw-bold text-dark d-block">Daftar Tahun Ajaran</span>
                        <small class="text-muted small">Klik baris tahun ajaran untuk memfilter periode</small>
                    </div>
                </div>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addYearModal">
                    <i class="bi bi-plus-circle me-1"></i>Tambah
                </button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%" class="ps-3">#</th>
                                <th>Nama</th>
                                <th>Rentang Periode</th>
                                <th width="15%">Status</th>
                                <th width="25%" class="text-end pe-3">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($years)): ?>
                            <tr>
                                <td colspan="5" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox fs-3 d-block mb-2"></i>
                                    Belum ada data Tahun Ajaran
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($years as $i => $year): ?>
                            <tr class="year-row <?= $year['is_active'] ? 'table-success active-year-row' : '' ?>" 
                                data-year-id="<?= $year['id'] ?>" 
                                data-year-name="<?= esc($year['name']) ?>" 
                                style="cursor: pointer;">
                                <td class="ps-3"><?= $i + 1 ?></td>
                                <td class="fw-bold text-dark"><?= esc($year['name']) ?></td>
                                <td class="small text-muted">
                                    <?= date('d M Y', strtotime($year['start_date'])) ?> —
                                    <?= date('d M Y', strtotime($year['end_date'])) ?>
                                </td>
                                <td>
                                    <?php if ($year['is_active']): ?>
                                    <span class="badge bg-success">Aktif</span>
                                    <?php else: ?>
                                    <span class="badge bg-secondary">Nonaktif</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end pe-3">
                                    <div class="d-inline-flex gap-1">
                                        <?php if (!$year['is_active']): ?>
                                        <a href="/academic-year/set-active/<?= $year['id'] ?>"
                                            class="btn btn-sm btn-outline-success"
                                            title="Aktifkan Tahun Ajaran"
                                            onclick="return confirm('Aktifkan tahun ajaran ini?')">
                                            <i class="bi bi-check-circle"></i>
                                        </a>
                                        <?php endif; ?>
                                        <button class="btn btn-sm btn-outline-primary"
                                            title="Edit Tahun Ajaran"
                                            onclick="editYear(<?= $year['id'] ?>, '<?= esc($year['name']) ?>', '<?= $year['start_date'] ?>', '<?= $year['end_date'] ?>')">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <?php if (!$year['is_active']): ?>
                                        <a href="/academic-year/delete/<?= $year['id'] ?>"
                                            class="btn btn-sm btn-outline-danger"
                                            title="Hapus Tahun Ajaran"
                                            onclick="return confirm('Hapus tahun ajaran ini?')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- KOLOM KANAN: PERIODE AKADEMIK -->
    <div class="col-lg-6">
        <!-- Tabel Daftar Periode Akademik -->
        <div class="card border-light shadow-sm">
            <div class="card-header bg-white py-3 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-table text-primary fs-5"></i>
                    <div>
                        <span class="fw-bold text-dark d-block">Daftar Periode Akademik</span>
                        <small class="text-muted small" id="selected-year-indicator">Menampilkan semua tahun ajaran</small>
                    </div>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-sm btn-outline-secondary" id="btn-reset-filter" style="display: none;" onclick="resetYearFilter()">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>Semua
                    </button>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addPeriodModal">
                        <i class="bi bi-plus-circle me-1"></i>Tambah
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="5%" class="ps-3">#</th>
                                <th>Tahun Ajaran</th>
                                <th>Semester</th>
                                <th>Rentang Periode</th>
                                <th width="15%">Status</th>
                                <th width="25%" class="text-end pe-3">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($periods)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox fs-3 d-block mb-2"></i>
                                    Belum ada data Periode Akademik
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($periods as $i => $period): ?>
                            <tr class="period-row <?= $period['is_active'] ? 'table-success table-opacity-10' : '' ?>" data-year-id="<?= $period['academic_year_id'] ?>">
                                <td class="ps-3 row-number"><?= $i + 1 ?></td>
                                <td class="fw-semibold text-dark"><?= esc($period['year_name']) ?></td>
                                <td>
                                    <span class="badge <?= $period['semester'] == 'Ganjil' ? 'bg-primary' : 'bg-info text-dark' ?>">
                                        <?= esc($period['semester']) ?>
                                    </span>
                                </td>
                                <td class="small text-muted">
                                    <?= date('d M Y', strtotime($period['start_date'])) ?> —
                                    <?= date('d M Y', strtotime($period['end_date'])) ?>
                                </td>
                                <td>
                                    <?php if ($period['is_active']): ?>
                                    <span class="badge bg-success">Aktif</span>
                                    <?php else: ?>
                                    <span class="badge bg-secondary">Nonaktif</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end pe-3">
                                    <div class="d-inline-flex gap-1">
                                        <?php if (!$period['is_active']): ?>
                                        <a href="/academic-period/set-active/<?= $period['id'] ?>"
                                            class="btn btn-sm btn-outline-success"
                                            title="Aktifkan Periode Akademik"
                                            onclick="return confirm('Aktifkan periode ini?')">
                                            <i class="bi bi-check-circle"></i>
                                        </a>
                                        <?php endif; ?>
                                        <button class="btn btn-sm btn-outline-primary"
                                            title="Edit Periode"
                                            onclick="editPeriod(<?= $period['id'] ?>, '<?= $period['start_date'] ?>', '<?= $period['end_date'] ?>')">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <?php if (!$period['is_active']): ?>
                                        <a href="/academic-period/delete/<?= $period['id'] ?>"
                                            class="btn btn-sm btn-outline-danger"
                                            title="Hapus Periode"
                                            onclick="return confirm('Hapus periode ini?')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <tr id="no-periods-row" style="display: none;">
                                <td colspan="6" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox fs-3 d-block mb-2"></i>
                                    Tidak ada data Periode Akademik untuk tahun ajaran ini
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Tambah Tahun Ajaran -->
<div class="modal fade" id="addYearModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-bold text-dark">
                    <i class="bi bi-plus-circle-fill me-2 text-primary"></i>Tambah Tahun Ajaran
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="/academic-year/store" method="post">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold small text-muted">Nama Tahun Ajaran <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control"
                            placeholder="Contoh: 2025/2026"
                            value="<?= old('name') ?>" required>
                        <div class="form-text small text-muted">Format: YYYY/YYYY</div>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Mulai <span class="text-danger">*</span></label>
                            <input type="date" name="start_date" class="form-control"
                                value="<?= old('start_date') ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Selesai <span class="text-danger">*</span></label>
                            <input type="date" name="end_date" class="form-control"
                                value="<?= old('end_date') ?>" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i>Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Edit Tahun Ajaran -->
<div class="modal fade" id="editYearModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-bold text-dark">
                    <i class="bi bi-pencil me-2 text-primary"></i>Edit Tahun Ajaran
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editYearForm" method="post">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold small text-muted">Nama Tahun Ajaran</label>
                        <input type="text" name="name" id="editYearName" class="form-control" required>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Mulai</label>
                            <input type="date" name="start_date" id="editYearStartDate" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Selesai</label>
                            <input type="date" name="end_date" id="editYearEndDate" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" 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 Tambah Periode Akademik -->
<div class="modal fade" id="addPeriodModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-bold text-dark">
                    <i class="bi bi-plus-circle-fill me-2 text-primary"></i>Tambah Periode Akademik
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="/academic-period/store" method="post">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="row g-2 mb-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold small text-muted">Tahun Ajaran <span class="text-danger">*</span></label>
                            <select name="academic_year_id" class="form-select" required>
                                <option value="">-- Pilih Tahun --</option>
                                <?php foreach ($years as $year): ?>
                                <option value="<?= $year['id'] ?>"
                                    <?= (old('academic_year_id') == $year['id'] || ($activeYear && $activeYear['id'] == $year['id'])) ? 'selected' : '' ?>>
                                    <?= esc($year['name']) ?>
                                    <?php if ($year['is_active']): ?>★<?php endif; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold small text-muted">Semester <span class="text-danger">*</span></label>
                            <select name="semester" class="form-select" required>
                                <option value="">-- Pilih Semester --</option>
                                <option value="Ganjil" <?= (old('semester') == 'Ganjil') ? 'selected' : '' ?>>Ganjil</option>
                                <option value="Genap" <?= (old('semester') == 'Genap') ? 'selected' : '' ?>>Genap</option>
                            </select>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Mulai <span class="text-danger">*</span></label>
                            <input type="date" name="start_date" class="form-control"
                                value="<?= old('start_date') ?>" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Selesai <span class="text-danger">*</span></label>
                            <input type="date" name="end_date" class="form-control"
                                value="<?= old('end_date') ?>" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i>Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Edit Periode Akademik -->
<div class="modal fade" id="editPeriodModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-bold text-dark">
                    <i class="bi bi-pencil me-2 text-primary"></i>Edit Periode Akademik
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editPeriodForm" method="post">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="row g-2">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Mulai</label>
                            <input type="date" name="start_date" id="editPeriodStartDate" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold small text-muted">Tanggal Selesai</label>
                            <input type="date" name="end_date" id="editPeriodEndDate" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" 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>

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

<?= $this->section('scripts') ?>
<script>
function editYear(id, name, startDate, endDate) {
    document.getElementById('editYearName').value      = name;
    document.getElementById('editYearStartDate').value = startDate;
    document.getElementById('editYearEndDate').value   = endDate;
    document.getElementById('editYearForm').action     = '/academic-year/update/' + id;
    new bootstrap.Modal(document.getElementById('editYearModal')).show();
}

function editPeriod(id, startDate, endDate) {
    document.getElementById('editPeriodStartDate').value = startDate;
    document.getElementById('editPeriodEndDate').value   = endDate;
    document.getElementById('editPeriodForm').action     = '/academic-period/update/' + id;
    new bootstrap.Modal(document.getElementById('editPeriodModal')).show();
}

document.addEventListener('DOMContentLoaded', function() {
    const yearRows = document.querySelectorAll('.year-row');
    const periodRows = document.querySelectorAll('.period-row');
    const selectedYearIndicator = document.getElementById('selected-year-indicator');
    const btnResetFilter = document.getElementById('btn-reset-filter');
    const noPeriodsRow = document.getElementById('no-periods-row');
    let activeFilterId = null;

    function filterPeriods(yearId, yearName) {
        activeFilterId = yearId;
        
        // Update selection highlights on year rows
        yearRows.forEach(row => {
            row.classList.remove('table-primary');
            if (row.getAttribute('data-year-id') === String(yearId)) {
                row.classList.add('table-primary');
            }
        });

        // Show/Hide period rows
        let visibleCount = 0;
        periodRows.forEach((row) => {
            const rowYearId = row.getAttribute('data-year-id');
            if (rowYearId === String(yearId)) {
                row.style.display = '';
                visibleCount++;
                const noCell = row.querySelector('.row-number');
                if (noCell) noCell.textContent = visibleCount;
            } else {
                row.style.display = 'none';
            }
        });

        // Show "no data" row if empty
        if (visibleCount === 0) {
            if (noPeriodsRow) noPeriodsRow.style.display = '';
        } else {
            if (noPeriodsRow) noPeriodsRow.style.display = 'none';
        }

        // Update indicator and reset button
        if (selectedYearIndicator) {
            selectedYearIndicator.innerHTML = `Tahun Ajaran: <strong class="text-primary">${yearName}</strong>`;
        }
        if (btnResetFilter) {
            btnResetFilter.style.display = 'inline-block';
        }
    }

    window.resetYearFilter = function() {
        activeFilterId = null;
        yearRows.forEach(row => {
            row.classList.remove('table-primary');
        });

        periodRows.forEach((row, index) => {
            row.style.display = '';
            const noCell = row.querySelector('.row-number');
            if (noCell) noCell.textContent = index + 1;
        });

        if (noPeriodsRow) noPeriodsRow.style.display = 'none';
        if (selectedYearIndicator) {
            selectedYearIndicator.textContent = 'Menampilkan semua tahun ajaran';
        }
        if (btnResetFilter) {
            btnResetFilter.style.display = 'none';
        }
    };

    // Add click event listener to each year row
    yearRows.forEach(row => {
        row.addEventListener('click', function(e) {
            // Prevent filter trigger if clicking on action buttons/links
            if (e.target.closest('a') || e.target.closest('button')) {
                return;
            }
            const yearId = this.getAttribute('data-year-id');
            const yearName = this.getAttribute('data-year-name');
            filterPeriods(yearId, yearName);
        });
    });

    // Auto-select the active academic year on page load
    const activeYearRow = document.querySelector('.active-year-row');
    if (activeYearRow) {
        const yearId = activeYearRow.getAttribute('data-year-id');
        const yearName = activeYearRow.getAttribute('data-year-name');
        filterPeriods(yearId, yearName);
    }
});
</script>
<?= $this->endSection() ?>