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

<div class="container-fluid px-4 py-3">

    <div class="d-flex align-items-center mb-4">
        <a href="/leger-import" class="btn btn-sm btn-outline-secondary me-3"><i class="bi bi-arrow-left"></i></a>
        <div>
            <h5 class="fw-bold mb-0">Preview Import Leger</h5>
            <small class="text-muted">Periksa data, pilih kelas & periode, lalu konfirmasi</small>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <!-- Info dari file -->
        <div class="col-md-5">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <h6 class="fw-semibold text-muted mb-3">
                        <i class="bi bi-file-earmark-spreadsheet me-2 text-success"></i>Info dari File Leger
                    </h6>
                    <table class="table table-sm table-borderless mb-3">
                        <tr><td class="text-muted" width="130">File</td><td><strong><?= esc($fileName) ?></strong></td></tr>
                        <tr><td class="text-muted">Kelas (di file)</td><td><strong><?= esc($parsed['meta']['class_name']) ?></strong></td></tr>
                        <tr><td class="text-muted">Semester</td><td><strong><?= esc($parsed['meta']['semester']) ?></strong></td></tr>
                        <tr><td class="text-muted">Tahun Ajaran</td><td><strong><?= esc($parsed['meta']['year']) ?></strong></td></tr>
                        <tr><td class="text-muted">Madrasah</td><td><?= esc($parsed['meta']['school']) ?></td></tr>
                        <tr><td class="text-muted">Jumlah Siswa</td><td><span class="badge bg-primary"><?= count($parsed['rows']) ?> siswa</span></td></tr>
                        <tr><td class="text-muted">Jumlah Mapel</td><td><span class="badge bg-secondary"><?= count($parsed['subject_codes']) ?> mapel</span></td></tr>
                    </table>

                    <!-- Status mapping mapel -->
                    <h6 class="fw-semibold text-muted mb-2">
                        <i class="bi bi-list-check me-1"></i>Status Mapel
                    </h6>
                    <div class="d-flex flex-wrap gap-1">
                        <?php foreach ($parsed['subject_codes'] as $code): ?>
                            <?php $found = isset($subjectLookup[$code]); ?>
                            <span class="badge <?= $found ? 'bg-success' : 'bg-danger' ?> px-2 py-1"
                                  title="<?= $found ? esc($subjectLookup[$code]['name']) : 'Tidak ada di Master Mapel!' ?>">
                                <?= esc($code) ?>
                                <i class="bi bi-<?= $found ? 'check' : 'x' ?>-circle ms-1"></i>
                            </span>
                        <?php endforeach; ?>
                    </div>
                    <?php $notFound = array_diff($parsed['subject_codes'], array_keys($subjectLookup)); ?>
                    <?php if (!empty($notFound)): ?>
                        <div class="alert alert-danger mt-2 py-2 mb-0">
                            <small><i class="bi bi-exclamation-triangle me-1"></i>
                            Kode <strong><?= esc(implode(', ', $notFound)) ?></strong> tidak ada di Master Mapel.
                            Mapel tersebut akan dilewati saat import.
                            <a href="/school-subject" target="_blank">Tambah di sini →</a></small>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-success mt-2 py-2 mb-0">
                            <small><i class="bi bi-check-circle me-1"></i>Semua mapel ditemukan di Master Mapel.</small>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Form konfirmasi -->
        <div class="col-md-7">
            <div class="card border-warning border-2 shadow-sm h-100">
                <div class="card-body">
                    <h6 class="fw-semibold text-warning mb-3">
                        <i class="bi bi-gear me-2"></i>Pilih Kelas & Periode di SIMAK
                    </h6>
                    <form action="/leger-import/confirm" method="post" id="formConfirm">
                        <?= csrf_field() ?>
                        <input type="hidden" name="parsed_data" value="<?= esc(json_encode($parsed)) ?>">
                        <input type="hidden" name="file_name" value="<?= esc($fileName) ?>">

                        <!-- Filter: Tahun Ajaran -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Tahun Ajaran <span class="text-danger">*</span></label>
                            <select id="selYear" class="form-select form-select-sm">
                                <option value="">-- Pilih Tahun Ajaran --</option>
                                <?php foreach ($allYears as $y): ?>
                                    <option value="<?= $y['id'] ?>"
                                        <?= ($suggestedPeriod && $suggestedPeriod['academic_year_id'] == $y['id']) ? 'selected' : '' ?>>
                                        <?= esc($y['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <!-- Semester -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Semester <span class="text-danger">*</span></label>
                            <select name="period_id" id="selPeriod" class="form-select form-select-sm" required>
                                <option value="">-- Pilih Tahun Ajaran dulu --</option>
                                <?php foreach ($allPeriods as $p): ?>
                                    <option value="<?= $p['id'] ?>"
                                        <?= ($suggestedPeriod && $suggestedPeriod['id'] == $p['id']) ? 'selected' : '' ?>>
                                        <?= esc($p['semester']) ?>
                                        <?php if ($p['is_active']): ?> (Aktif)<?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if ($suggestedPeriod): ?>
                                <div class="form-text text-success">
                                    <i class="bi bi-check-circle me-1"></i>
                                    Auto-match: <?= esc($suggestedPeriod['semester'] . ' ' . $parsed['meta']['year']) ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Kelas -->
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Kelas <span class="text-danger">*</span></label>
                            <select name="classroom_id" class="form-select form-select-sm" required>
                                <option value="">-- Pilih Kelas --</option>
                                <?php foreach ($classrooms as $c): ?>
                                    <option value="<?= $c['id'] ?>"
                                        <?= ($suggestedClassroom && $suggestedClassroom['id'] == $c['id']) ? 'selected' : '' ?>>
                                        <?= esc($c['grade_name'] . ' — ' . $c['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if ($suggestedClassroom): ?>
                                <div class="form-text text-success">
                                    <i class="bi bi-check-circle me-1"></i>Auto-match: <?= esc($suggestedClassroom['name']) ?>
                                </div>
                            <?php else: ?>
                                <div class="form-text text-warning">
                                    <i class="bi bi-exclamation-triangle me-1"></i>
                                    Tidak ada kelas yang cocok otomatis — pilih manual
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" name="overwrite" value="1" id="chkOverwrite">
                            <label class="form-check-label text-danger fw-semibold" for="chkOverwrite">
                                Timpa data lama (jika nilai untuk kelas & periode ini sudah ada)
                            </label>
                        </div>

                        <button type="submit" class="btn btn-success w-100">
                            <i class="bi bi-check-circle me-2"></i>Konfirmasi Import
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabel preview data siswa -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-bottom py-2 d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-semibold">
                <i class="bi bi-people me-2 text-primary"></i>
                Preview Data (<?= count($parsed['rows']) ?> siswa × <?= count($parsed['subject_codes']) ?> mapel)
            </h6>
            <small class="text-muted">Scroll kanan untuk semua kolom →</small>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover table-bordered align-middle mb-0" style="font-size:.8rem;">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>NIS</th>
                            <th style="min-width:170px;">Nama</th>
                            <th>JK</th>
                            <?php foreach ($parsed['subject_codes'] as $code): ?>
                                <?php $found = isset($subjectLookup[$code]); ?>
                                <th class="text-center <?= !$found ? 'table-danger' : '' ?>"
                                    style="min-width:48px;"
                                    title="<?= $found ? esc($subjectLookup[$code]['name']) : 'Tidak ada di Master Mapel!' ?>">
                                    <?= esc($code) ?>
                                    <?php if (!$found): ?><i class="bi bi-exclamation-triangle"></i><?php endif; ?>
                                </th>
                            <?php endforeach; ?>
                            <th class="text-center">Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($parsed['rows'] as $row): ?>
                        <?php $total = array_sum(array_filter($row['scores'])); ?>
                        <tr>
                            <td><?= $row['no'] ?></td>
                            <td><?= esc($row['nis']) ?></td>
                            <td><?= esc($row['nama']) ?></td>
                            <td class="text-center"><?= esc($row['jk']) ?></td>
                            <?php foreach ($parsed['subject_codes'] as $code): ?>
                                <?php $score = $row['scores'][$code] ?? null; ?>
                                <td class="text-center <?= ($score !== null && $score < 70) ? 'table-danger' : '' ?>">
                                    <?= $score !== null ? number_format($score, 0) : '<span class="text-muted">-</span>' ?>
                                </td>
                            <?php endforeach; ?>
                            <td class="text-center fw-bold"><?= number_format($total, 0) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer bg-white text-muted" style="font-size:.78rem;">
            <i class="bi bi-info-circle me-1"></i>
            Kolom <span class="badge bg-danger">merah</span> = kode mapel belum ada di Master Mapel (akan dilewati saat import).
            Data ini belum tersimpan. Klik <strong>Konfirmasi Import</strong> di atas untuk menyimpan.
        </div>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
// Dynamic: saat tahun ajaran dipilih, load periode
document.getElementById('selYear').addEventListener('change', function() {
    const yearId = this.value;
    const selPeriod = document.getElementById('selPeriod');
    selPeriod.innerHTML = '<option value="">Memuat...</option>';

    if (!yearId) {
        selPeriod.innerHTML = '<option value="">-- Pilih Tahun Ajaran dulu --</option>';
        return;
    }

    fetch('/leger-import/get-periods?year_id=' + yearId)
        .then(r => r.json())
        .then(data => {
            selPeriod.innerHTML = '<option value="">-- Pilih Semester --</option>';
            data.forEach(p => {
                selPeriod.innerHTML += `<option value="${p.id}">${p.semester}${p.is_active == 1 ? ' (Aktif)' : ''}</option>`;
            });
        });
});
</script>
<?= $this->endSection() ?>