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

<div class="row mb-3">
    <div class="col">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h5 class="fw-semibold mb-1">
                    <i class="bi bi-calendar3 text-primary me-2"></i>Import Jadwal aSc Timetables
                </h5>
                <p class="text-muted small mb-0">
                    Kelola versi jadwal yang diimport dari aSc Timetables
                </p>
            </div>
            <a href="/asc-import/create" class="btn btn-primary">
                <i class="bi bi-upload me-2"></i>Upload Jadwal Baru
            </a>
        </div>
    </div>
</div>

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

<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th width="4%">#</th>
                        <th>Nama Jadwal</th>
                        <th width="12%">Tahun Ajaran</th>
                        <th width="8%">Semester</th>
                        <th width="10%">Total Slot</th>
                        <th width="10%">Status</th>
                        <th width="12%">Diimport</th>
                        <th width="22%">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($imports)): ?>
                    <tr>
                        <td colspan="8" class="text-center text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                            Belum ada jadwal yang diimport.<br>
                            <a href="/asc-import/create" class="text-primary">Upload sekarang</a>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($imports as $i => $import): ?>
                    <tr>
                        <td class="text-muted"><?= $i + 1 ?></td>
                        <td>
                            <div class="fw-semibold"><?= esc($import['name']) ?></div>
                            <?php if ($import['notes']): ?>
                            <div class="text-muted small"><?= esc($import['notes']) ?></div>
                            <?php endif; ?>
                        </td>
                        <td><?= esc($import['academic_year']) ?></td>
                        <td>
                            <span class="badge <?= $import['semester'] === 'Ganjil' ? 'bg-primary' : 'bg-success' ?>">
                                <?= $import['semester'] ?>
                            </span>
                        </td>
                        <td class="text-center">
                            <span class="badge bg-secondary">
                                <?= number_format($import['total_schedules']) ?> slot
                            </span>
                        </td>
                        <td class="text-center">
                            <?php if ($import['is_active']): ?>
                            <span class="badge bg-success">
                                <i class="bi bi-check-circle me-1"></i>Aktif
                            </span>
                            <?php else: ?>
                            <span class="badge bg-light text-muted border">Nonaktif</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-muted small">
                            <?= date('d/m/Y H:i', strtotime($import['created_at'])) ?>
                        </td>
                        <td>
                            <div class="d-flex gap-1 flex-wrap">

                                <?php if (!$import['is_active']): ?>
                                <!-- Tombol aktifkan -->
                                <a href="/asc-import/set-active/<?= $import['id'] ?>"
                                    class="btn btn-sm btn-outline-success"
                                    title="Jadikan aktif"
                                    onclick="return confirm('Jadikan jadwal ini sebagai jadwal aktif?')">
                                    <i class="bi bi-check-lg"></i>
                                </a>
                                <?php else: ?>
                                <!-- Tombol nonaktifkan (hanya muncul saat aktif) -->
                                <a href="/asc-import/set-inactive/<?= $import['id'] ?>"
                                    class="btn btn-sm btn-warning"
                                    title="Nonaktifkan jadwal ini"
                                    onclick="return confirm('Nonaktifkan jadwal ini?\nTidak ada jadwal yang aktif sampai Anda mengaktifkan jadwal lain.')">
                                    <i class="bi bi-pause-circle me-1"></i>Nonaktifkan
                                </a>
                                <?php endif; ?>

                                <!-- Lihat jadwal -->
                                <a href="/asc-schedule?import_id=<?= $import['id'] ?>"
                                    class="btn btn-sm btn-outline-primary"
                                    title="Lihat jadwal">
                                    <i class="bi bi-eye"></i>
                                </a>

                                <a href="/asc-import/edit-periods/<?= $import['id'] ?>" 
                                    class="btn btn-sm btn-outline-primary" 
                                    title="Edit Jam Pelajaran">
                                        <i class="bi bi-clock"></i>
                                </a>

                                <!-- Detail import -->
                                <button class="btn btn-sm btn-outline-secondary"
                                    title="Detail import"
                                    onclick="showDetail(<?= $import['id'] ?>)">
                                    <i class="bi bi-info-circle"></i>
                                </button>

                                <!-- Edit Metadata -->
                                <button class="btn btn-sm btn-outline-warning"
                                    title="Edit Metadata Jadwal"
                                    onclick="showEditMetadata(<?= esc(json_encode($import)) ?>)">
                                    <i class="bi bi-pencil"></i>
                                </button>

                                <!-- Hapus (hanya saat nonaktif) -->
                                <?php if (!$import['is_active']): ?>
                                <a href="/asc-import/delete/<?= $import['id'] ?>"
                                    class="btn btn-sm btn-outline-danger"
                                    title="Hapus"
                                    onclick="return confirm('Hapus import ini? Semua data jadwal akan ikut terhapus!')">
                                    <i class="bi bi-trash"></i>
                                </a>
                                <?php endif; ?>

                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Info box jadwal aktif -->
<?php if ($active): ?>
<div class="alert alert-info mt-3 d-flex align-items-center gap-2 py-2">
    <i class="bi bi-info-circle-fill fs-5"></i>
    <div>
        Jadwal aktif saat ini: <strong><?= esc($active['name']) ?></strong>
        (<?= $active['academic_year'] ?> — <?= $active['semester'] ?>)
        &nbsp;·&nbsp;
        <a href="/asc-schedule" class="fw-semibold">Lihat Jadwal &rarr;</a>
    </div>
</div>
<?php endif; ?>

<!-- Modal Detail -->
<div class="modal fade" id="detailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title fw-semibold">
                    <i class="bi bi-info-circle me-2"></i>Detail Import
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="detailContent">
                <div class="text-center py-4">
                    <div class="spinner-border spinner-border-sm text-primary"></div>
                    <span class="ms-2 text-muted">Memuat data...</span>
                </div>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
function showDetail(importId) {
    const modal   = new bootstrap.Modal(document.getElementById('detailModal'));
    const content = document.getElementById('detailContent');

    content.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border spinner-border-sm text-primary"></div>
            <span class="ms-2 text-muted">Memuat data...</span>
        </div>`;

    modal.show();

    fetch(`/asc-import/detail/${importId}`)
        .then(r => r.json())
        .then(data => {
            content.innerHTML = buildDetailHtml(data);
        })
        .catch(() => {
            content.innerHTML = `<div class="alert alert-danger">Gagal memuat data.</div>`;
        });
}

function buildDetailHtml(data) {
    let html = `
        <div class="row g-3 mb-4">
            <div class="col-6 col-md-3">
                <div class="border rounded p-3 text-center">
                    <div class="fs-4 fw-bold text-primary">${data.teachers.length}</div>
                    <div class="small text-muted">Guru</div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="border rounded p-3 text-center">
                    <div class="fs-4 fw-bold text-success">${data.classes.length}</div>
                    <div class="small text-muted">Kelas</div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="border rounded p-3 text-center">
                    <div class="fs-4 fw-bold text-warning">${data.subjects.length}</div>
                    <div class="small text-muted">Mapel</div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="border rounded p-3 text-center">
                    <div class="fs-4 fw-bold text-info">${data.periods.length}</div>
                    <div class="small text-muted">Jam/Periode</div>
                </div>
            </div>
        </div>`;

    html += `<h6 class="fw-semibold mb-2">Daftar Guru</h6>
        <div class="d-flex flex-wrap gap-2 mb-4">`;
    data.teachers.forEach(t => {
        html += `<span class="badge rounded-pill px-3 py-2"
            style="background-color:${t.color}; color:${getTextColor(t.color)}">
            [${t.short_code}] ${t.name}
        </span>`;
    });
    html += `</div>`;

    html += `<h6 class="fw-semibold mb-2">Daftar Kelas</h6>
        <div class="d-flex flex-wrap gap-2 mb-4">`;
    data.classes.forEach(c => {
        html += `<span class="badge bg-light text-dark border px-3 py-2">${c.name}</span>`;
    });
    html += `</div>`;

    html += `<h6 class="fw-semibold mb-2">Daftar Mata Pelajaran</h6>
        <div class="d-flex flex-wrap gap-2">`;
    data.subjects.forEach(s => {
        html += `<span class="badge bg-primary bg-opacity-10 text-primary border border-primary px-3 py-2">
            ${s.short_code} — ${s.name}
        </span>`;
    });
    html += `</div>`;

    return html;
}

function getTextColor(hex) {
    hex = hex.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? '#000000' : '#FFFFFF';
}

function showEditMetadata(importData) {
    const modal = new bootstrap.Modal(document.getElementById('editMetadataModal'));
    document.getElementById('editMetadataForm').action = `/asc-import/update-metadata/${importData.id}`;
    document.getElementById('editName').value = importData.name;
    document.getElementById('editYear').value = importData.academic_year;
    document.getElementById('editSemester').value = importData.semester;
    document.getElementById('editNotes').value = importData.notes || '';
    modal.show();
}
</script>

<!-- Modal Edit Metadata -->
<div class="modal fade" id="editMetadataModal" 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 Metadata Jadwal
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editMetadataForm" method="post" action="">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Jadwal <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label fw-semibold">Tahun Ajaran <span class="text-danger">*</span></label>
                            <input type="text" name="academic_year" id="editYear" class="form-control" placeholder="Contoh: 2025/2026" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-semibold">Semester <span class="text-danger">*</span></label>
                            <select name="semester" id="editSemester" class="form-select" required>
                                <option value="Ganjil">Ganjil</option>
                                <option value="Genap">Genap</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Catatan <span class="text-muted small">(opsional)</span></label>
                        <textarea name="notes" id="editNotes" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-sm btn-primary">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

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