<?php
/**
 * Install Update / Patch Sistem
 * Koperasi Management System
 */

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

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

$pageTitle = 'Install Update';
$pageSubtitle = 'Unggah dan instal update sistem atau patch perbaikan bug';

// Handle Update Action
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['update_file']) && $_FILES['update_file']['error'] === UPLOAD_ERR_OK) {
        $filename = $_FILES['update_file']['name'];
        if (pathinfo($filename, PATHINFO_EXTENSION) === 'zip') {
            $target = __DIR__ . '/backups/update_' . time() . '.zip';
            if (move_uploaded_file($_FILES['update_file']['tmp_name'], $target)) {
                try {
                    $backupUtil->restoreBackup($target);
                    unlink($target); // Cleanup
                    setFlash('success', "✓ Sistem berhasil diperbarui/dipulihkan dari file: $filename");
                } 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.");
        }
    } else {
        setFlash('danger', "✗ Silakan pilih file terlebih dahulu.");
    }

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

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

<style>
    .update-container {
        max-width: 700px;
        margin: 0 auto;
    }

    .update-header {
        background: linear-gradient(135deg, var(--success-500), var(--success-600));
        color: white;
        padding: 20px 24px;
        border-radius: 8px 8px 0 0;
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 0;
    }

    .update-header i {
        font-size: 1.8rem;
        opacity: 0.9;
    }

    .update-header h2 {
        margin: 0;
        font-size: 1.5rem;
        font-weight: 600;
    }

    .file-input-wrapper {
        position: relative;
        display: inline-block;
        width: 100%;
    }

    .file-input-label {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 40px 20px;
        border: 2px dashed var(--primary-300);
        border-radius: 8px;
        background: var(--primary-50);
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .file-input-label:hover {
        border-color: var(--primary-500);
        background: var(--primary-100);
    }

    .file-input-label i {
        font-size: 2rem;
        color: var(--primary-500);
        margin-right: 15px;
    }

    .file-input-label span {
        text-align: left;
    }

    .file-input-label .label-title {
        display: block;
        font-weight: 600;
        color: var(--primary-800);
        margin-bottom: 5px;
    }

    .file-input-label .label-subtitle {
        display: block;
        font-size: 0.85rem;
        color: var(--primary-600);
    }

    #update_file {
        display: none;
    }

    .file-info {
        margin-top: 20px;
        padding: 15px;
        background: var(--gray-50);
        border-radius: 6px;
        display: none;
    }

    .file-info.show {
        display: block;
    }

    .file-info-name {
        font-weight: 600;
        color: var(--gray-800);
        margin-bottom: 5px;
        word-break: break-all;
    }

    .file-info-size {
        font-size: 0.85rem;
        color: var(--gray-600);
    }

    .info-text {
        font-size: 0.85rem;
        color: var(--gray-600);
        line-height: 1.6;
        margin: 15px 0;
    }

    .info-text code {
        background: var(--gray-100);
        padding: 2px 6px;
        border-radius: 3px;
        font-family: monospace;
        color: var(--primary-600);
    }

    .alert-info-text {
        background: var(--info-50);
        border-left: 4px solid var(--info-500);
        padding: 12px 15px;
        border-radius: 4px;
        color: var(--info-700);
        font-size: 0.9rem;
        margin: 15px 0;
    }

    .alert-info-text strong {
        display: block;
        margin-bottom: 5px;
    }

    .action-buttons {
        display: flex;
        gap: 12px;
        justify-content: flex-end;
        margin-top: 20px;
    }

    .footer-links {
        text-align: center;
        padding: 15px;
        border-top: 1px solid var(--gray-200);
        background: var(--gray-50);
        border-radius: 0 0 8px 8px;
    }

    .footer-links a {
        color: var(--primary-600);
        text-decoration: none;
        font-size: 0.9rem;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
    }

    .footer-links a:hover {
        color: var(--primary-700);
        text-decoration: underline;
    }

    .btn-update {
        background: linear-gradient(135deg, var(--success-500), var(--success-600));
        color: white;
        border: none;
        padding: 12px 32px;
        border-radius: 6px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        gap: 8px;
        width: 100%;
        justify-content: center;
        margin-top: 20px;
    }

    .btn-update:hover {
        background: linear-gradient(135deg, var(--success-600), var(--success-700));
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
    }

    .btn-update:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
    }
</style>

<div class="update-container">
    <div class="card" style="margin-bottom: 0; border: none; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
        <!-- Header -->
        <div class="update-header">
            <i class="fas fa-cloud-upload"></i>
            <div>
                <h2>Install Update</h2>
            </div>
        </div>

        <!-- Content -->
        <div class="card-body" style="padding: 30px;">
            <h3 style="margin-top: 0; margin-bottom: 20px; font-size: 1.1rem; color: var(--gray-800);">
                Upload File Update / Patch (.zip)
            </h3>

            <p class="info-text">
                Unggah file .zip yang berisi update sistem atau patch perbaikan bug.
            </p>

            <div class="alert-info-text">
                <strong>⚠ Catatan Penting:</strong>
                Pastikan struktur folder dalam ZIP sesuai dengan root aplikasi (contoh: <code>modules/siswa/index.php</code>).
            </div>

            <!-- File Upload Form -->
            <form method="POST" enctype="multipart/form-data" id="updateForm" onsubmit="return validateAndConfirm();">
                <div class="file-input-wrapper">
                    <label for="update_file" class="file-input-label" id="fileLabel">
                        <div style="width: 100%; text-align: center;">
                            <i class="fas fa-file-upload"></i>
                            <div>
                                <span class="label-title">Pilih File</span>
                                <span class="label-subtitle">Tidak ada file yang dipilih</span>
                            </div>
                        </div>
                    </label>
                    <input 
                        type="file" 
                        id="update_file" 
                        name="update_file" 
                        accept=".zip" 
                        onchange="handleFileSelect(event)"
                    >
                </div>

                <!-- File Info Display -->
                <div id="fileInfo" class="file-info">
                    <div class="file-info-name" id="fileName"></div>
                    <div class="file-info-size" id="fileSize"></div>
                </div>

                <!-- Action Buttons -->
                <button type="submit" class="btn-update" id="submitBtn" disabled>
                    <i class="fas fa-play-circle"></i>
                    Mulai Update / Patch Sistem
                </button>
            </form>
        </div>

        <!-- Footer -->
        <div class="footer-links">
            <a href="<?= APP_URL ?>/backup_restore.php">
                <i class="fas fa-arrow-left"></i>
                Ke Halaman Backup
            </a>
        </div>
    </div>
</div>

<script>
function handleFileSelect(event) {
    const file = event.target.files[0];
    const fileLabel = document.getElementById('fileLabel');
    const fileInfo = document.getElementById('fileInfo');
    const fileName = document.getElementById('fileName');
    const fileSize = document.getElementById('fileSize');
    const submitBtn = document.getElementById('submitBtn');

    if (file) {
        // Update label
        fileLabel.innerHTML = `
            <div style="width: 100%; text-align: center;">
                <i class="fas fa-check-circle" style="color: var(--success-500);"></i>
                <div>
                    <span class="label-title">File Dipilih</span>
                    <span class="label-subtitle">${file.name}</span>
                </div>
            </div>
        `;

        // Show file info
        fileName.textContent = file.name;
        fileSize.textContent = 'Ukuran: ' + (file.size / 1024 / 1024).toFixed(2) + ' MB';
        fileInfo.classList.add('show');

        // Enable submit button
        submitBtn.disabled = false;
    } else {
        // Reset
        fileLabel.innerHTML = `
            <div style="width: 100%; text-align: center;">
                <i class="fas fa-file-upload"></i>
                <div>
                    <span class="label-title">Pilih File</span>
                    <span class="label-subtitle">Tidak ada file yang dipilih</span>
                </div>
            </div>
        `;
        fileInfo.classList.remove('show');
        submitBtn.disabled = true;
    }
}

function validateAndConfirm() {
    const file = document.getElementById('update_file').files[0];
    if (!file) {
        alert('Silakan pilih file terlebih dahulu.');
        return false;
    }

    if (file.type !== 'application/zip' && !file.name.endsWith('.zip')) {
        alert('Hanya file .zip yang diperbolehkan.');
        return false;
    }

    return confirm('⚠ PERINGATAN: Sistem akan diperbarui. Pastikan Anda telah membuat backup terlebih dahulu.\n\nLanjutkan update?');
}

// Drag and drop support
const fileLabel = document.getElementById('fileLabel');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    fileLabel.addEventListener(eventName, preventDefaults, false);
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

['dragenter', 'dragover'].forEach(eventName => {
    fileLabel.addEventListener(eventName, () => {
        fileLabel.style.borderColor = 'var(--success-500)';
        fileLabel.style.background = 'var(--success-50)';
    }, false);
});

['dragleave', 'drop'].forEach(eventName => {
    fileLabel.addEventListener(eventName, () => {
        fileLabel.style.borderColor = 'var(--primary-300)';
        fileLabel.style.background = 'var(--primary-50)';
    }, false);
});

fileLabel.addEventListener('drop', (e) => {
    const dt = e.dataTransfer;
    const files = dt.files;
    document.getElementById('update_file').files = files;
    const event = new Event('change', { bubbles: true });
    document.getElementById('update_file').dispatchEvent(event);
}, false);
</script>

<?php 
// Show alert if update flash exists
$flash = getFlash();
if ($flash): 
    $isSuccess = strpos($flash['type'], 'success') !== false;
    $message = addslashes($flash['message']);
?>
<script>
    window.addEventListener('load', function() {
        <?php if ($isSuccess): ?>
            alert('✓ Berhasil!\n\n<?= $message ?>');
            // Optional: Reload halaman setelah update sukses
            // location.reload();
        <?php else: ?>
            alert('✗ Gagal!\n\n<?= $message ?>');
        <?php endif; ?>
    });
</script>
<?php endif; ?>

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