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

<?php
$badgeClass = ($total > 0) ? 'bg-success' : 'bg-warning text-dark';
$statusText = ($total > 0) ? 'Migration sudah dijalankan (' . $lastBatch . ' batch)' : 'Belum ada migration';
?>

<!-- Info Koneksi -->
<div class="row g-3 mb-4">
    <div class="col-md-6">
        <div class="card shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-white py-3 border-0">
                <h5 class="card-title fw-bold mb-0"><i class="bi bi-database me-2 text-primary"></i>Koneksi Database</h5>
            </div>
            <div class="card-body p-4">
                <table class="table table-sm table-borderless mb-0">
                    <tr>
                        <td class="text-muted" style="width:120px;">Status</td>
                        <td><span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Terhubung</span></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Database</td>
                        <td><code><?= esc($dbName) ?></code></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Server</td>
                        <td><?= esc($dbDriver) ?> &mdash; <?= esc($serverVer) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Host</td>
                        <td><code><?= esc($hostname) ?>:<?= $port ?></code></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Collation</td>
                        <td><code><?= esc($collation) ?></code></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-white py-3 border-0">
                <h5 class="card-title fw-bold mb-0"><i class="bi bi-boxes me-2 text-info"></i>Tabel</h5>
            </div>
            <div class="card-body p-4 d-flex flex-column align-items-center justify-content-center">
                <div class="fs-1 fw-bold text-info"><?= $tableCount ?></div>
                <div class="text-muted small">Jumlah Tabel</div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-white py-3 border-0">
                <h5 class="card-title fw-bold mb-0"><i class="bi bi-hdd-stack me-2 text-warning"></i>Ukuran</h5>
            </div>
            <div class="card-body p-4 d-flex flex-column align-items-center justify-content-center">
                <div class="fs-1 fw-bold text-warning"><?= number_format($dbSize, 1) ?></div>
                <div class="text-muted small">Megabyte (MB)</div>
            </div>
        </div>
    </div>
</div>

<!-- Migration & Tools -->
<div class="row g-3 mb-4">
    <div class="col-md-7">
        <div class="card shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-white py-3 border-0 d-flex align-items-center justify-content-between">
                <div>
                    <h5 class="card-title fw-bold mb-0"><i class="bi bi-arrow-up-circle me-2 text-success"></i>Migration</h5>
                    <p class="text-muted small mb-0">Status: <span class="badge <?= $badgeClass ?>"><?= $statusText ?></span></p>
                </div>
                <button class="btn btn-success btn-sm" id="btnRunMigration">
                    <i class="bi bi-play-fill me-1"></i>Jalankan Migrasi
                </button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height:300px;overflow-y:auto;">
                    <table class="table table-hover table-sm mb-0">
                        <thead class="table-light" style="position:sticky;top:0;">
                            <tr>
                                <th style="width:60px;">Batch</th>
                                <th>Migration</th>
                                <th style="width:160px;">Tanggal</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($migrations)): ?>
                            <tr><td colspan="3" class="text-center text-muted py-3">Belum ada migration yang dijalankan.</td></tr>
                            <?php else: ?>
                            <?php foreach ($migrations as $m): ?>
                            <tr>
                                <td><span class="badge bg-secondary"><?= $m['batch'] ?></span></td>
                                <td><code style="font-size:0.75rem;"><?= esc($m['version']) ?>_<?= esc(basename($m['class'])) ?></code></td>
                                <td style="font-size:0.8rem;"><?= date('Y-m-d H:i', $m['time']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div id="migrateReport" class="px-3 pb-3"></div>
        </div>
    </div>
    <div class="col-md-5">
        <div class="card shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-white py-3 border-0">
                <h5 class="card-title fw-bold mb-0"><i class="bi bi-tools me-2 text-secondary"></i>Tools</h5>
                <p class="text-muted small mb-0">Operasi database yang tersedia.</p>
            </div>
            <div class="card-body p-4 d-flex flex-column gap-3">
                <div class="d-flex align-items-center justify-content-between p-3 bg-light rounded-3">
                    <div>
                        <div class="fw-semibold small"><i class="bi bi-download me-1 text-primary"></i>Backup Database</div>
                        <div class="text-muted small" style="font-size:0.75rem;">Download file .sql (<?= number_format($dbSize, 1) ?> MB)</div>
                    </div>
                    <a href="/settings/database/backup" class="btn btn-primary btn-sm" id="btnBackup">
                        <i class="bi bi-download me-1"></i>Backup
                    </a>
                </div>

                <div class="d-flex align-items-center justify-content-between p-3 bg-primary bg-opacity-10 rounded-3 border border-primary">
                    <div>
                        <div class="fw-semibold small"><i class="bi bi-file-earmark-zip me-1 text-primary"></i>Backup Lengkap</div>
                        <div class="text-muted small" style="font-size:0.75rem;">SQL dan seluruh file upload. Maksimal 10 backup terakhir.</div>
                    </div>
                    <a href="/settings/database/backup/full" class="btn btn-primary btn-sm" id="btnFullBackup">
                        <i class="bi bi-box-arrow-down me-1"></i>Backup Lengkap
                    </a>
                </div>

                <?php
                // Hitung tabel yang mungkin perlu optimasi (yang punaya deleted_at)
                $optimizable = $db = db_connect();
                $tblList = $optimizable->query("SELECT TABLE_NAME, ROUND((data_length + index_length) / 1024 / 1024, 1) AS size_mb FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? ORDER BY size_mb DESC LIMIT 10", [$dbName])->getResultArray();
                ?>
                <div class="d-flex align-items-center justify-content-between p-3 bg-light rounded-3 opacity-50">
                    <div>
                        <div class="fw-semibold small"><i class="bi bi-stars me-1 text-warning"></i>Optimasi Tabel</div>
                        <div class="text-muted small" style="font-size:0.75rem;">Tabel terbesar: <?= !empty($tblList) ? esc($tblList[0]['TABLE_NAME']) . ' (' . $tblList[0]['size_mb'] . ' MB)' : '—' ?></div>
                    </div>
                    <button class="btn btn-outline-warning btn-sm" disabled title="Fitur akan datang">
                        <i class="bi bi-stars me-1"></i>Optimasi
                    </button>
                </div>

                <div class="d-flex align-items-center justify-content-between p-3 bg-danger bg-opacity-10 rounded-3 border border-danger">
                    <div>
                        <div class="fw-semibold small text-danger"><i class="bi bi-exclamation-triangle-fill me-1 text-danger"></i>Reset Database</div>
                        <div class="text-muted small" style="font-size:0.75rem;">Hapus semua data transaksi dan reset aplikasi seperti baru.</div>
                    </div>
                    <button class="btn btn-danger btn-sm" id="btnResetDatabase" data-bs-toggle="modal" data-bs-target="#resetDatabaseModal">
                        <i class="bi bi-trash3 me-1"></i>Reset
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Riwayat Backup Lengkap -->
<div class="card shadow-sm border-0 rounded-3 mb-4">
    <div class="card-header bg-white py-3 border-0 d-flex align-items-center justify-content-between">
        <div>
            <h5 class="card-title fw-bold mb-0"><i class="bi bi-clock-history me-2 text-primary"></i>Riwayat Backup Lengkap</h5>
            <p class="text-muted small mb-0">Backup tersimpan di server pada folder writable/backups.</p>
        </div>
        <span class="badge bg-secondary"><?= count($backups) ?>/10 file</span>
    </div>
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Nama File</th>
                    <th>Ukuran</th>
                    <th>Dibuat</th>
                    <th class="text-end">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($backups)): ?>
                <tr><td colspan="4" class="text-center text-muted py-4">Belum ada backup lengkap.</td></tr>
                <?php else: ?>
                <?php foreach ($backups as $backup): ?>
                <tr>
                    <td><code><?= esc($backup['name']) ?></code></td>
                    <td><?= number_format($backup['size'] / 1024 / 1024, 2) ?> MB</td>
                    <td><?= date('Y-m-d H:i:s', $backup['modified']) ?></td>
                    <td class="text-end text-nowrap">
                        <a class="btn btn-outline-primary btn-sm" href="/settings/database/backup/download/<?= esc($backup['name']) ?>">
                            <i class="bi bi-download"></i> Download
                        </a>
                        <button type="button" class="btn btn-outline-danger btn-sm btn-delete-backup" data-filename="<?= esc($backup['name']) ?>">
                            <i class="bi bi-trash"></i> Hapus
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Reset Database -->
<div class="modal fade" id="resetDatabaseModal" tabindex="-1" aria-labelledby="resetDatabaseModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="resetDatabaseModalLabel"><i class="bi bi-exclamation-triangle-fill me-2"></i>Reset Total Database</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Tutup"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <strong>Perhatian!</strong> Tindakan ini akan menghapus seluruh data aplikasi kecuali akun admin utama.
                </div>
                <p class="mb-3">Data yang akan dihapus:</p>
                <ul class="small text-muted mb-3">
                    <li>Semua data siswa dan riwayat akademik</li>
                    <li>Semua transaksi tabungan</li>
                    <li>Semua data absensi, nilai, jurnal, dan pelanggaran</li>
                    <li>Semua pengguna kecuali <strong>adminsimak@admin.com</strong></li>
                </ul>
                <p class="mb-3">Sistem akan otomatis membackup database sebelum reset.</p>
                <div class="mb-3">
                    <label for="resetPassword" class="form-label">Masukkan Password Admin untuk Konfirmasi</label>
                    <input type="password" class="form-control" id="resetPassword" placeholder="Password admin" autocomplete="current-password">
                </div>
                <div id="resetReport"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-danger" id="btnConfirmReset">
                    <i class="bi bi-trash3 me-1"></i>Ya, Reset Database
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    // ── Jalankan Migrasi ────────────────────────────────────────
    document.getElementById('btnRunMigration')?.addEventListener('click', function() {
        const btn = this;
        const report = document.getElementById('migrateReport');
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menjalankan...';
        report.innerHTML = '';

        fetch('/settings/database/migrate')
            .then(r => r.json())
            .then(data => {
                const cls = data.status === 'success' ? 'alert-success' : 'alert-danger';
                report.innerHTML = `<div class="alert ${cls} mt-3 mb-0 py-2 small">${data.message}</div>`;
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-play-fill me-1"></i>Jalankan Migrasi';

                if (data.status === 'success') {
                    setTimeout(() => location.reload(), 2000);
                }
            })
            .catch(() => {
                report.innerHTML = `<div class="alert alert-danger mt-3 mb-0 py-2 small">Gagal terhubung ke server.</div>`;
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-play-fill me-1"></i>Jalankan Migrasi';
            });
    });

    // ── Backup ──────────────────────────────────────────────────
    document.getElementById('btnBackup')?.addEventListener('click', function(e) {
        // Konfirmasi dulu untuk backup yang besar
        const size = <?= $dbSize ?>;
        if (size > 10) {
            const ok = confirm('Ukuran database ' + size + ' MB. Proses backup mungkin memakan waktu. Lanjutkan?');
            if (!ok) {
                e.preventDefault();
                return;
            }
        }

        // Tampilkan loading
        this.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memproses...';
    });

    document.getElementById('btnFullBackup')?.addEventListener('click', function() {
        this.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memproses...';
        this.classList.add('disabled');
    });

    document.querySelectorAll('.btn-delete-backup').forEach(function(button) {
        button.addEventListener('click', function() {
            const filename = this.dataset.filename;
            if (!confirm('Hapus backup ' + filename + '?')) return;

            const params = new URLSearchParams();
            params.append('filename', filename);
            params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
            this.disabled = true;

            fetch('/settings/database/backup/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: params
            })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert(data.message || 'Backup gagal dihapus.');
                        this.disabled = false;
                    }
                })
                .catch(() => {
                    alert('Gagal menghubungi server.');
                    this.disabled = false;
                });
        });
    });

    // ── Reset Database ──────────────────────────────────────────
    const btnConfirmReset = document.getElementById('btnConfirmReset');
    const resetPasswordInput = document.getElementById('resetPassword');
    const resetReport = document.getElementById('resetReport');
    const resetDatabaseModal = document.getElementById('resetDatabaseModal');
    const resetDatabaseTrigger = document.getElementById('btnResetDatabase');

    resetDatabaseModal?.addEventListener('hide.bs.modal', function() {
        const activeElement = document.activeElement;
        if (activeElement && resetDatabaseModal.contains(activeElement)) {
            activeElement.blur();
        }
    });

    resetDatabaseModal?.addEventListener('hidden.bs.modal', function() {
        resetDatabaseTrigger?.focus();
    });

    btnConfirmReset?.addEventListener('click', function() {
        const password = resetPasswordInput.value.trim();
        if (!password) {
            resetReport.innerHTML = '<div class="alert alert-danger py-2 small mb-0">Password admin wajib diisi.</div>';
            return;
        }

        Swal.fire({
            title: 'Yakin Reset Database?',
            html: 'Semua data transaksi dan pengguna (kecuali admin utama) akan dihapus.<br><strong>Tindakan ini tidak bisa dibatalkan!</strong>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ya, Reset Sekarang',
            cancelButtonText: 'Batal',
            confirmButtonColor: '#dc3545',
            reverseButtons: true,
        }).then((result) => {
            if (!result.isConfirmed) {
                return;
            }

            const btn = btnConfirmReset;
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Memproses...';
            resetReport.innerHTML = '<div class="alert alert-info py-2 small mb-0">Backup dan reset sedang berlangsung, mohon tunggu...</div>';

            const params = new URLSearchParams();
            params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
            params.append('password', password);

            fetch('/settings/database/reset', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
                body: params,
            })
            .then(async (r) => {
                const text = await r.text();
                try {
                    return JSON.parse(text);
                } catch (e) {
                    throw new Error('Response server bukan JSON: ' + text.substring(0, 200));
                }
            })
            .then(data => {
                if (data.status === 'success') {
                    resetReport.innerHTML = `<div class="alert alert-success py-2 small mb-0">${data.message}</div>`;
                    Swal.fire({
                        title: 'Berhasil',
                        text: data.message,
                        icon: 'success',
                        confirmButtonText: 'OK',
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    resetReport.innerHTML = `<div class="alert alert-danger py-2 small mb-0">${data.message}</div>`;
                    Swal.fire('Gagal', data.message, 'error');
                    btn.disabled = false;
                    btn.innerHTML = '<i class="bi bi-trash3 me-1"></i>Ya, Reset Database';
                }
            })
            .catch(err => {
                console.error('Reset error:', err);
                resetReport.innerHTML = '<div class="alert alert-danger py-2 small mb-0">Terjadi kesalahan koneksi.</div>';
                Swal.fire('Error', err.message || 'Terjadi kesalahan koneksi.', 'error');
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-trash3 me-1"></i>Ya, Reset Database';
            });
        });
    });
</script>

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