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

<div class="row mb-3">
    <div class="col">
        <div class="d-flex align-items-center gap-2">
            <a href="/asc-import" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-arrow-left"></i>
            </a>
            <div>
                <h5 class="fw-semibold mb-0">
                    <i class="bi bi-upload text-primary me-2"></i>Upload Jadwal XML
                </h5>
                <p class="text-muted small mb-0">Import file XML dari aSc Timetables</p>
            </div>
        </div>
    </div>
</div>

<?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-danger alert-dismissible fade show py-2">
    <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; ?>

<?php if (session()->getFlashdata('errors')): ?>
<div class="alert alert-danger alert-dismissible fade show py-2">
    <ul class="mb-0 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; ?>

<div class="row justify-content-center">
    <div class="col-md-7">
        <div class="card">
            <div class="card-body">
                <form action="/asc-import/store" method="post" enctype="multipart/form-data" id="uploadForm">
                    <?= csrf_field() ?>

                    <!-- Nama Jadwal -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">
                            Nama Jadwal <span class="text-danger">*</span>
                        </label>
                        <input type="text" name="name" class="form-control"
                            placeholder="Contoh: Jadwal Ganjil 2024/2025"
                            value="<?= old('name') ?>" required>
                        <div class="form-text">Nama ini untuk membedakan antar versi jadwal</div>
                    </div>

                    <!-- Tahun Ajaran & Semester -->
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                Tahun Ajaran <span class="text-danger">*</span>
                            </label>
                            <input type="text" name="academic_year" class="form-control"
                                placeholder="Contoh: 2024/2025"
                                value="<?= old('academic_year') ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                Semester <span class="text-danger">*</span>
                            </label>
                            <select name="semester" class="form-select" required>
                                <option value="">-- Pilih --</option>
                                <option value="Ganjil" <?= old('semester') === 'Ganjil' ? 'selected' : '' ?>>
                                    Ganjil
                                </option>
                                <option value="Genap" <?= old('semester') === 'Genap' ? 'selected' : '' ?>>
                                    Genap
                                </option>
                            </select>
                        </div>
                    </div>

                    <!-- Upload File -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold">
                            File XML aSc <span class="text-danger">*</span>
                        </label>

                        <!-- Drop Zone -->
                        <div class="drop-zone border-2 border-dashed rounded p-4 text-center"
                            id="dropZone"
                            style="border: 2px dashed #dee2e6; cursor: pointer; transition: all .2s">
                            <i class="bi bi-file-earmark-code fs-2 text-muted d-block mb-2"></i>
                            <div class="fw-semibold text-muted mb-1">
                                Drag & drop file XML di sini
                            </div>
                            <div class="text-muted small mb-3">atau klik untuk pilih file</div>
                            <input type="file" name="xml_file" id="xmlFile"
                                accept=".xml" class="d-none" required>
                            <button type="button" class="btn btn-sm btn-outline-primary"
                                onclick="document.getElementById('xmlFile').click()">
                                <i class="bi bi-folder2-open me-1"></i>Pilih File
                            </button>
                        </div>

                        <!-- Preview nama file terpilih -->
                        <div id="filePreview" class="d-none mt-2">
                            <div class="d-flex align-items-center gap-2 p-2 bg-light rounded">
                                <i class="bi bi-file-earmark-code text-success fs-5"></i>
                                <div class="flex-grow-1">
                                    <div class="fw-semibold small" id="fileName"></div>
                                    <div class="text-muted small" id="fileSize"></div>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-danger"
                                    onclick="clearFile()">
                                    <i class="bi bi-x"></i>
                                </button>
                            </div>
                        </div>

                        <div class="form-text">
                            Format: <code>.xml</code> hasil export dari aSc Timetables · Maks 5 MB
                        </div>
                    </div>

                    <!-- Catatan -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold">Catatan <span class="text-muted small">(opsional)</span></label>
                        <textarea name="notes" class="form-control" rows="2"
                            placeholder="Misal: Berlaku mulai 15 Juli 2024"><?= old('notes') ?></textarea>
                    </div>

                    <!-- Submit -->
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary" id="btnSubmit">
                            <i class="bi bi-upload me-2"></i>Proses Import
                        </button>
                        <a href="/asc-import" class="btn btn-outline-secondary">Batal</a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Panduan -->
        <div class="card mt-3">
            <div class="card-header d-flex align-items-center gap-2 py-2">
                <i class="bi bi-question-circle text-info"></i>
                <span class="fw-semibold small">Cara Export dari aSc Timetables</span>
            </div>
            <div class="card-body py-3">
                <ol class="mb-0 small text-muted ps-3">
                    <li class="mb-1">Buka aSc Timetables, pilih jadwal yang ingin diexport</li>
                    <li class="mb-1">Klik menu <strong>File → Export → XML</strong></li>
                    <li class="mb-1">Pilih opsi <strong>"Database"</strong> sebagai tipe export</li>
                    <li class="mb-1">Simpan file <code>.xml</code> ke komputer</li>
                    <li>Upload file tersebut di form ini</li>
                </ol>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const dropZone = document.getElementById('dropZone');
const xmlFile  = document.getElementById('xmlFile');
const preview  = document.getElementById('filePreview');

// ── Drag & Drop ──────────────────────────────────────────────────────────
dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.style.borderColor  = '#0d6efd';
    dropZone.style.background   = '#f0f7ff';
});

dropZone.addEventListener('dragleave', () => {
    dropZone.style.borderColor  = '#dee2e6';
    dropZone.style.background   = '';
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.style.borderColor  = '#dee2e6';
    dropZone.style.background   = '';

    const file = e.dataTransfer.files[0];
    if (file) setFile(file);
});

dropZone.addEventListener('click', (e) => {
    if (e.target.tagName !== 'BUTTON') {
        xmlFile.click();
    }
});

// ── File Input Change ────────────────────────────────────────────────────
xmlFile.addEventListener('change', () => {
    if (xmlFile.files[0]) setFile(xmlFile.files[0]);
});

function setFile(file) {
    // Validasi ekstensi
    if (!file.name.toLowerCase().endsWith('.xml')) {
        alert('File harus berformat .xml!');
        return;
    }

    // Tampilkan preview
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('fileSize').textContent = formatSize(file.size);
    preview.classList.remove('d-none');
    dropZone.style.borderColor = '#198754';

    // Set file ke input jika dari drag drop
    const dt = new DataTransfer();
    dt.items.add(file);
    xmlFile.files = dt.files;
}

function clearFile() {
    xmlFile.value = '';
    preview.classList.add('d-none');
    dropZone.style.borderColor = '#dee2e6';
}

function formatSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

// ── Loading saat submit ──────────────────────────────────────────────────
document.getElementById('uploadForm').addEventListener('submit', function () {
    const btn = document.getElementById('btnSubmit');
    btn.disabled  = true;
    btn.innerHTML = `<span class="spinner-border spinner-border-sm me-2"></span>Memproses...`;
});
</script>
<?= $this->endSection() ?>