<?php
/**
 * Backup & Restore Manager
 * Koperasi Management System
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/backup_util.php';

requireAdmin();
$db = getDB();
$backupUtil = new BackupUtil($db);

$pageTitle = 'Backup & Restore Sistem';
$pageSubtitle = 'Manajemen cadangan data dan pembaruan aplikasi';

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        try {
            $zipName = $backupUtil->createBackup();
            setFlash('success', "Backup berhasil dibuat: $zipName");
        } catch (Exception $e) {
            setFlash('danger', "Gagal membuat backup: " . $e->getMessage());
        }
    }

    if ($action === 'direct_restore') {
        if (isset($_FILES['backup_file']) && $_FILES['backup_file']['error'] === UPLOAD_ERR_OK) {
            $filename = $_FILES['backup_file']['name'];
            if (pathinfo($filename, PATHINFO_EXTENSION) === 'zip') {
                $backupsDir = __DIR__ . '/../backups/';
                if (!is_dir($backupsDir)) mkdir($backupsDir, 0777, true);
                $target = $backupsDir . 'update_' . time() . '.zip';
                if (move_uploaded_file($_FILES['backup_file']['tmp_name'], $target)) {
                    try {
                        $backupUtil->restoreBackup($target);
                        unlink($target); // Cleanup
                        setFlash('success', "Sistem berhasil diperbarui/dipulihkan secara langsung.");
                    } catch (Exception $e) {
                        setFlash('danger', "Gagal memperbarui sistem: " . $e->getMessage());
                    }
                } else {
                    setFlash('danger', "Gagal memproses file pembaruan.");
                }
            } else {
                setFlash('danger', "Hanya file .zip yang diperbolehkan.");
            }
        }
    }

    if ($action === 'delete') {
        $filename = basename($_POST['filename']); // basename untuk keamanan
        $path = __DIR__ . '/../backups/' . $filename;
        if (file_exists($path) && strpos($filename, '..') === false) {
            unlink($path);
            setFlash('success', "Backup $filename berhasil dihapus.");
        } else {
            setFlash('danger', "File backup tidak ditemukan: $filename");
        }
    }

    if ($action === 'restore_full') {
        $filename = basename($_POST['filename']);
        $path = __DIR__ . '/../backups/' . $filename;
        try {
            $backupUtil->restoreBackup($path);
            setFlash('success', "Sistem berhasil dipulihkan secara penuh dari $filename.");
        } catch (Exception $e) {
            setFlash('danger', "Gagal memulihkan sistem: " . $e->getMessage());
        }
    }

    if ($action === 'restore_partial') {
        $filename = basename($_POST['filename']);
        $files = $_POST['files_to_restore'] ?? [];
        $path = __DIR__ . '/../backups/' . $filename;
        if (empty($files)) {
            setFlash('warning', "Pilih setidaknya satu file untuk dipulihkan.");
        } else {
            try {
                $backupUtil->restoreBackup($path, $files);
                setFlash('success', "Berhasil memulihkan " . count($files) . " elemen terpilih.");
            } catch (Exception $e) {
                setFlash('danger', "Gagal memulihkan elemen: " . $e->getMessage());
            }
        }
    }

    header('Location: backup_restore.php');
    exit;
}

$backups = $backupUtil->listBackups();

// For partial restore modal
$allZipFiles = [];
$activeZip = '';
if (isset($_GET['view_zip'])) {
    $activeZip = $_GET['view_zip'];
    $allZipFiles = $backupUtil->getZipFiles($activeZip);
}

include __DIR__ . '/header.php';
?>

<div class="row">
    <div class="col-md-4">
        <div class="card" style="height: 100%;">
            <div class="card-header">
                <h3><i class="fas fa-cogs" style="color: var(--primary-500);"></i> Operasi Sistem</h3>
            </div>
            <div class="card-body" style="display: flex; flex-direction: column; gap: 20px;">
                <!-- Backup Module -->
                <div style="padding: 20px; border-radius: 12px; background: var(--primary-50); border: 1px dashed var(--primary-200);">
                    <div class="d-flex align-items-center" style="gap: 10px; margin-bottom: 8px;">
                        <div style="width: 36px; height: 36px; background: var(--primary-100); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-download" style="color: var(--primary-600);"></i>
                        </div>
                        <h4 style="margin: 0; color: var(--primary-800); font-size: 0.95rem;">Buat Cadangan</h4>
                    </div>
                    <p style="font-size: 0.82rem; color: var(--primary-600); margin-bottom: 12px;">
                        Amankan seluruh data sistem (database &amp; file) ke dalam satu paket ZIP.
                    </p>
                    <form method="POST">
                        <input type="hidden" name="action" value="create">
                        <button type="submit" class="btn btn-primary" style="width: 100%; font-size: 0.85rem;">
                            <i class="fas fa-hdd"></i> Download Backup Baru
                        </button>
                    </form>
                </div>

                <!-- Restore from Upload Module -->
                <div style="padding: 20px; border-radius: 12px; background: #fff7ed; border: 1px dashed #f97316;">
                    <div class="d-flex align-items-center" style="gap: 10px; margin-bottom: 8px;">
                        <div style="width: 36px; height: 36px; background: #ffedd5; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-cloud-upload-alt" style="color: #ea580c;"></i>
                        </div>
                        <h4 style="margin: 0; color: #9a3412; font-size: 0.95rem;">Restore dari File</h4>
                    </div>
                    <p style="font-size: 0.82rem; color: #c2410c; margin-bottom: 12px;">
                        Pulihkan sistem dari file backup <code>.zip</code> yang Anda miliki di komputer.
                    </p>
                    <form method="POST" enctype="multipart/form-data" id="restoreUploadForm" onsubmit="return confirmRestore(this)">
                        <input type="hidden" name="action" value="direct_restore">
                        <div style="margin-bottom: 10px;">
                            <label id="restoreFileLabel" for="restoreFileInput"
                                   style="display: block; border: 2px dashed #f97316; border-radius: 10px; padding: 14px; text-align: center; cursor: pointer; background: #fff; font-size: 0.82rem; color: #9a3412; transition: background 0.2s;">
                                <i class="fas fa-file-archive" style="font-size: 1.4rem; display: block; margin-bottom: 4px; opacity: 0.7;"></i>
                                <span id="restoreFileName">Klik pilih file .zip backup...</span>
                            </label>
                            <input type="file" name="backup_file" id="restoreFileInput" accept=".zip" required 
                                   style="display:none;" onchange="showRestoreFileName(this)">
                        </div>
                        <button type="submit" class="btn" id="restoreSubmitBtn"
                                style="width: 100%; background: linear-gradient(135deg, #ea580c, #dc2626); color: white; font-weight: 700; font-size: 0.85rem; border: none; border-radius: 8px; padding: 10px;">
                            <i class="fas fa-history"></i> Eksekusi Restore
                        </button>
                    </form>
                </div>

                <!-- Update/Patch Module -->
                <div style="padding: 20px; border-radius: 12px; background: var(--success-50); border: 1px dashed var(--success-200);">
                    <div class="d-flex align-items-center" style="gap: 10px; margin-bottom: 8px;">
                        <div style="width: 36px; height: 36px; background: var(--success-100); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-box-open" style="color: var(--success-600);"></i>
                        </div>
                        <h4 style="margin: 0; color: var(--success-800); font-size: 0.95rem;">Install Update / Patch</h4>
                    </div>
                    <p style="font-size: 0.82rem; color: var(--success-600); margin-bottom: 12px;">
                        Unggah paket sistem baru untuk memperbarui aplikasi atau memasang patch perbaikan.
                    </p>
                    <a href="<?= APP_URL ?>/migration/update.php" class="btn btn-success" style="width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 0.85rem;">
                        <i class="fas fa-cloud-upload-alt"></i> Ke Halaman Install Update
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-history" style="color: var(--warning-500);"></i> Riwayat Backup Lokal</h3>
                <span class="text-muted" style="font-size: 0.82rem;"><?= count($backups) ?> file tersimpan</span>
            </div>
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Nama File</th>
                            <th class="text-center">Ukuran</th>
                            <th class="text-center">Tanggal</th>
                            <th class="text-center" width="130">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($backups)): ?>
                            <tr>
                                <td colspan="4" class="text-center" style="padding: 50px; color: var(--gray-400);">
                                    <i class="fas fa-folder-open" style="font-size: 3rem; opacity: 0.2; display: block; margin-bottom: 15px;"></i>
                                    Belum ada riwayat cadangan lokal.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($backups as $b): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center" style="gap: 10px;">
                                            <div style="width: 34px; height: 34px; background: #fef3c7; border-radius: 8px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                                                <i class="fas fa-file-archive" style="color: #d97706; font-size: 0.9rem;"></i>
                                            </div>
                                            <div style="font-weight: 600; font-size: 0.85rem; color: var(--gray-700);"><?= $b['name'] ?></div>
                                        </div>
                                    </td>
                                    <td class="text-center" style="font-size: 0.85rem; color: var(--gray-500);">
                                        <?= round($b['size'] / 1024 / 1024, 2) ?> MB
                                    </td>
                                    <td class="text-center" style="font-size: 0.8rem; color: var(--gray-500);">
                                        <?= date('d M Y', $b['date']) ?><br>
                                        <span style="font-size: 0.72rem;"><?= date('H:i', $b['date']) ?></span>
                                    </td>
                                    <td class="text-center">
                                        <div class="d-flex justify-content-center" style="gap: 5px;">
                                            <!-- Download -->
                                            <a href="<?= APP_URL ?>/backups/<?= $b['name'] ?>" class="btn btn-icon btn-outline-success" title="Download" download>
                                                <i class="fas fa-download"></i>
                                            </a>
                                            <!-- Restore Full -->
                                            <form method="POST" style="display:inline;" 
                                                  onsubmit="return confirm('⚠️ PERINGATAN!\n\nSeluruh database dan file akan DIGANTIKAN dengan data dari backup ini.\n\nPastikan Anda sudah membuat backup terbaru sebelum melanjutkan.\n\nLanjutkan restore dari:\n<?= $b['name'] ?>?');">
                                                <input type="hidden" name="action" value="restore_full">
                                                <input type="hidden" name="filename" value="<?= $b['name'] ?>">
                                                <button type="submit" class="btn btn-icon" 
                                                        style="background: #fff7ed; border: 1px solid #fed7aa; color: #ea580c;" 
                                                        title="Restore Penuh">
                                                    <i class="fas fa-undo"></i>
                                                </button>
                                            </form>
                                            <!-- Delete -->
                                            <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus file backup ini permanen?');">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="filename" value="<?= $b['name'] ?>">
                                                <button type="submit" class="btn btn-icon btn-outline-danger" title="Hapus">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Info Card -->
        <div class="card mt-3" style="background: #f0f9ff; border: 1px solid #bae6fd;">
            <div class="card-body" style="padding: 16px 20px;">
                <h5 style="color: #0369a1; margin-bottom: 8px; font-size: 0.9rem;"><i class="fas fa-info-circle"></i> Panduan Restore</h5>
                <ul style="margin: 0; padding-left: 20px; color: #0c4a6e; font-size: 0.82rem; line-height: 1.7;">
                    <li>Gunakan <strong>tombol <i class="fas fa-undo"></i> kuning</strong> untuk restore langsung dari backup lokal yang tersimpan di server.</li>
                    <li>Gunakan panel <strong>"Restore dari File"</strong> di kiri untuk upload dan restore dari backup yang ada di komputer Anda.</li>
                    <li>Selalu <strong>buat backup terbaru terlebih dahulu</strong> sebelum melakukan proses restore apapun.</li>
                    <li>Proses restore akan menggantikan <strong>seluruh database dan file</strong> yang ada saat ini.</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
function showRestoreFileName(input) {
    const label = document.getElementById('restoreFileName');
    if (input.files && input.files[0]) {
        const f = input.files[0];
        label.textContent = f.name + ' (' + (f.size / 1024 / 1024).toFixed(2) + ' MB)';
        document.getElementById('restoreFileLabel').style.background = '#fff7ed';
    }
}

function confirmRestore(form) {
    const fileInput = form.querySelector('input[type="file"]');
    if (!fileInput.files || !fileInput.files[0]) {
        alert('Pilih file backup .zip terlebih dahulu.');
        return false;
    }
    const fileName = fileInput.files[0].name;
    const confirmed = confirm(
        '⚠️ PERINGATAN RESTORE!\n\n' +
        'File: ' + fileName + '\n\n' +
        'Seluruh DATABASE dan FILE aplikasi akan DIGANTIKAN.\n' +
        'Proses ini tidak dapat dibatalkan!\n\n' +
        'Pastikan Anda sudah membuat backup terbaru.\n\n' +
        'Lanjutkan restore?'
    );
    if (confirmed) {
        const btn = document.getElementById('restoreSubmitBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Memproses Restore...';
    }
    return confirmed;
}
</script>


<?php if ($activeZip): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('partialRestoreModal'));</script>
<div class="modal modal-lg" id="partialRestoreModal">
    <div class="modal-header">
        <h3>Pilih File untuk Dipulihkan</h3>
        <button class="modal-close" onclick="window.location='backup_restore.php'"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="restore_partial">
        <input type="hidden" name="filename" value="<?= $activeZip ?>">
        <div class="modal-body">
            <div style="max-height: 400px; overflow-y: auto;">
                <?php foreach ($allZipFiles as $file): ?>
                    <label style="display: block; padding: 8px; border-bottom: 1px solid #eee;">
                        <input type="checkbox" name="files_to_restore[]" value="<?= $file ?>"> <?= $file ?>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Pulihkan Terpilih</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php 
// Show alert if update flash exists
$flash = getFlash();
if ($flash && (strpos($flash['message'], 'berhasil diperbarui') !== false || strpos($flash['message'], 'Gagal memperbarui') !== false)): ?>
<script>
    window.onload = function() {
        alert("<?= addslashes($flash['message']) ?>");
    };
</script>
<?php endif; ?>

<?php include __DIR__ . '/footer.php'; ?>
