<?php
/**
 * ============================================================================
 * admin/restore.php - Database Restoration Interface
 * Restore database from backups with preview and validation
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('manage_backups')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Backup Manager', 'url' => 'backup-manager.php'],
    ['title' => 'Restore', 'url' => '']
];

$backup_id = $_GET['backup_id'] ?? null;
$backup = null;

if ($backup_id) {
    try {
        $sql = "SELECT * FROM database_backups WHERE id = ? AND backup_status = 'completed'";
        $stmt = $db->prepare($sql);
        $stmt->execute([$backup_id]);
        $backup = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$backup) {
            setFlashMessage('Backup not found or invalid', 'error');
            header('Location: ' . APP_URL . '/admin/backup-manager.php');
            exit();
        }
    } catch (PDOException $e) {
        logError('Restore error: ' . $e->getMessage());
        setFlashMessage('Error loading backup', 'error');
        header('Location: ' . APP_URL . '/admin/backup-manager.php');
        exit();
    }
}

renderAdminHeader('Restore Database', $breadcrumbs);
?>

<style>
.restore-step {
    padding: 1.5rem;
    border-left: 4px solid #e5e7eb;
    margin-bottom: 1rem;
    transition: all 0.3s ease;
}
.restore-step.active {
    border-left-color: #059669;
    background-color: #f0fdf4;
}
.restore-step.completed {
    border-left-color: #10b981;
    opacity: 0.7;
}
.backup-preview {
    background-color: #f8fafc;
    border-radius: 8px;
    padding: 1rem;
}
</style>

<!-- Critical Warning -->
<div class="alert alert-danger border-0 shadow-sm mb-4">
    <div class="d-flex align-items-center">
        <i class="bi bi-exclamation-triangle-fill me-3" style="font-size: 2rem;"></i>
        <div>
            <h5 class="mb-1">Critical Operation Warning</h5>
            <p class="mb-0">Database restoration will <strong>REPLACE ALL CURRENT DATA</strong> with the backup data. This action cannot be undone. Ensure you have a recent backup before proceeding.</p>
        </div>
    </div>
</div>

<?php if ($backup): ?>
<!-- Restore Wizard -->
<div class="row">
    <div class="col-lg-8">
        <!-- Step 1: Backup Information -->
        <div class="restore-step active" id="step1">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <h5 class="fw-bold mb-1">
                        <span class="badge bg-primary me-2">1</span>
                        Backup Information
                    </h5>
                    <p class="text-muted mb-0">Review backup details before restoration</p>
                </div>
                <i class="bi bi-info-circle text-primary" style="font-size: 1.5rem;"></i>
            </div>
            
            <div class="backup-preview">
                <div class="row">
                    <div class="col-md-6 mb-2">
                        <small class="text-muted">Backup Name</small>
                        <p class="fw-semibold mb-0"><?php echo htmlspecialchars($backup['backup_name']); ?></p>
                    </div>
                    <div class="col-md-6 mb-2">
                        <small class="text-muted">Backup Type</small>
                        <p class="fw-semibold mb-0">
                            <span class="badge bg-<?php echo $backup['backup_type'] === 'full' ? 'primary' : 'secondary'; ?>">
                                <?php echo ucfirst($backup['backup_type']); ?>
                            </span>
                        </p>
                    </div>
                    <div class="col-md-6 mb-2">
                        <small class="text-muted">Backup Size</small>
                        <p class="fw-semibold mb-0"><?php echo number_format($backup['backup_size'] / 1024 / 1024, 2); ?> MB</p>
                    </div>
                    <div class="col-md-6 mb-2">
                        <small class="text-muted">Created</small>
                        <p class="fw-semibold mb-0"><?php echo date('Y-m-d H:i:s', strtotime($backup['started_at'])); ?></p>
                    </div>
                    <?php if ($backup['tables_included']): ?>
                    <div class="col-12 mb-2">
                        <small class="text-muted">Tables Included</small>
                        <p class="fw-semibold mb-0"><?php echo htmlspecialchars($backup['tables_included']); ?></p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="mt-3">
                <button class="btn btn-primary" onclick="nextStep(2)">
                    Continue <i class="bi bi-arrow-right ms-2"></i>
                </button>
                <a href="<?php echo APP_URL; ?>/admin/backup-manager.php" class="btn btn-outline-secondary">Cancel</a>
            </div>
        </div>
        
        <!-- Step 2: Pre-Restore Backup -->
        <div class="restore-step" id="step2">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <h5 class="fw-bold mb-1">
                        <span class="badge bg-secondary me-2">2</span>
                        Create Safety Backup
                    </h5>
                    <p class="text-muted mb-0">Create a backup of current data before restoration</p>
                </div>
                <i class="bi bi-shield-check text-warning" style="font-size: 1.5rem;"></i>
            </div>
            
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle me-2"></i>
                <strong>Recommended:</strong> Create a backup of your current database before proceeding with restoration.
            </div>
            
            <div id="safetyBackupStatus"></div>
            
            <div class="mt-3">
                <button class="btn btn-warning" onclick="createSafetyBackup()">
                    <i class="bi bi-shield-check me-2"></i>Create Safety Backup
                </button>
                <button class="btn btn-outline-primary" onclick="nextStep(3)">
                    Skip & Continue <i class="bi bi-arrow-right ms-2"></i>
                </button>
            </div>
        </div>
        
        <!-- Step 3: Restoration Options -->
        <div class="restore-step" id="step3">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <h5 class="fw-bold mb-1">
                        <span class="badge bg-secondary me-2">3</span>
                        Restoration Options
                    </h5>
                    <p class="text-muted mb-0">Configure restoration settings</p>
                </div>
                <i class="bi bi-gear text-info" style="font-size: 1.5rem;"></i>
            </div>
            
            <div class="mb-3">
                <label class="form-label fw-semibold">Restoration Mode</label>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="restoreMode" id="fullRestore" value="full" checked>
                    <label class="form-check-label" for="fullRestore">
                        <strong>Full Restoration</strong>
                        <p class="text-muted small mb-0">Replace entire database with backup data</p>
                    </label>
                </div>
                <div class="form-check mt-2">
                    <input class="form-check-input" type="radio" name="restoreMode" id="tableRestore" value="tables">
                    <label class="form-check-label" for="tableRestore">
                        <strong>Selective Tables</strong>
                        <p class="text-muted small mb-0">Restore only specific tables</p>
                    </label>
                </div>
            </div>
            
            <div class="mb-3" id="tableSelection" style="display: none;">
                <label class="form-label fw-semibold">Select Tables to Restore</label>
                <div class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                    <?php if ($backup['tables_included']): ?>
                        <?php foreach (explode(',', $backup['tables_included']) as $table): ?>
                        <div class="form-check">
                            <input class="form-check-input restore-table" type="checkbox" value="<?php echo trim($table); ?>" id="table_<?php echo trim($table); ?>">
                            <label class="form-check-label" for="table_<?php echo trim($table); ?>">
                                <?php echo trim($table); ?>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="mt-3">
                <button class="btn btn-primary" onclick="nextStep(4)">
                    Continue <i class="bi bi-arrow-right ms-2"></i>
                </button>
                <button class="btn btn-outline-secondary" onclick="prevStep(2)">
                    <i class="bi bi-arrow-left me-2"></i>Back
                </button>
            </div>
        </div>
        
        <!-- Step 4: Final Confirmation -->
        <div class="restore-step" id="step4">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div>
                    <h5 class="fw-bold mb-1">
                        <span class="badge bg-secondary me-2">4</span>
                        Final Confirmation
                    </h5>
                    <p class="text-muted mb-0">Review and confirm restoration</p>
                </div>
                <i class="bi bi-check-circle text-success" style="font-size: 1.5rem;"></i>
            </div>
            
            <div class="alert alert-danger">
                <h6 class="fw-bold">⚠️ Final Warning</h6>
                <p class="mb-0">You are about to restore the database. Current data will be REPLACED and CANNOT be recovered without a backup.</p>
            </div>
            
            <div class="backup-preview mb-3">
                <h6 class="fw-bold mb-3">Restoration Summary</h6>
                <div id="restoreSummary"></div>
            </div>
            
            <div class="mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="confirmRestore">
                    <label class="form-check-label" for="confirmRestore">
                        I understand that this action will replace all current data and cannot be undone
                    </label>
                </div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">Type <strong>RESTORE</strong> to confirm</label>
                <input type="text" class="form-control" id="confirmText" placeholder="RESTORE">
            </div>
            
            <div class="mt-3">
                <button class="btn btn-danger" onclick="startRestore()">
                    <i class="bi bi-arrow-counterclockwise me-2"></i>Start Restoration
                </button>
                <button class="btn btn-outline-secondary" onclick="prevStep(3)">
                    <i class="bi bi-arrow-left me-2"></i>Back
                </button>
            </div>
        </div>
    </div>
    
    <!-- Sidebar -->
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm sticky-top" style="top: 20px;">
            <div class="card-header bg-white py-3">
                <h6 class="mb-0 fw-bold">Restoration Progress</h6>
            </div>
            <div class="card-body">
                <div class="d-flex align-items-center mb-3">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <i class="bi bi-1-circle"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <p class="mb-0 small fw-semibold">Review Backup</p>
                    </div>
                </div>
                
                <div class="d-flex align-items-center mb-3 opacity-50">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <i class="bi bi-2-circle"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <p class="mb-0 small fw-semibold">Safety Backup</p>
                    </div>
                </div>
                
                <div class="d-flex align-items-center mb-3 opacity-50">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <i class="bi bi-3-circle"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <p class="mb-0 small fw-semibold">Configure Options</p>
                    </div>
                </div>
                
                <div class="d-flex align-items-center opacity-50">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <i class="bi bi-4-circle"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <p class="mb-0 small fw-semibold">Confirm & Restore</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card border-0 shadow-sm mt-3">
            <div class="card-body">
                <h6 class="fw-bold mb-3">Important Notes</h6>
                <ul class="small mb-0">
                    <li class="mb-2">Restoration may take several minutes depending on database size</li>
                    <li class="mb-2">Users will be temporarily unable to access the system</li>
                    <li class="mb-2">Always create a safety backup before restoration</li>
                    <li>Contact technical support if issues occur</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<?php else: ?>
<!-- No Backup Selected -->
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5">
        <i class="bi bi-inbox display-1 text-muted"></i>
        <h4 class="mt-3">No Backup Selected</h4>
        <p class="text-muted">Please select a backup from the backup manager to restore.</p>
        <a href="<?php echo APP_URL; ?>/admin/backup-manager.php" class="btn btn-primary">
            <i class="bi bi-arrow-left me-2"></i>Go to Backup Manager
        </a>
    </div>
</div>
<?php endif; ?>

<script>
let currentStep = 1;
let safetyBackupCreated = false;

// Toggle table selection
$('input[name="restoreMode"]').change(function() {
    if ($('#tableRestore').is(':checked')) {
        $('#tableSelection').show();
    } else {
        $('#tableSelection').hide();
    }
});

// Navigation
function nextStep(step) {
    $(`#step${currentStep}`).removeClass('active').addClass('completed');
    $(`#step${step}`).addClass('active');
    currentStep = step;
    
    if (step === 4) {
        updateRestoreSummary();
    }
}

function prevStep(step) {
    $(`#step${currentStep}`).removeClass('active');
    $(`#step${step}`).addClass('active').removeClass('completed');
    currentStep = step;
}

// Create safety backup
function createSafetyBackup() {
    Swal.fire({
        title: 'Creating Safety Backup...',
        text: 'Please wait while we backup your current data',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.post(APP_URL + '/admin/actions/backup-operations.php', {
        action: 'create_backup',
        name: 'safety_backup_' + Date.now(),
        type: 'full',
        compress: 1
    })
    .done(function(response) {
        Swal.close();
        if (response.success) {
            safetyBackupCreated = true;
            $('#safetyBackupStatus').html(`
                <div class="alert alert-success">
                    <i class="bi bi-check-circle me-2"></i>
                    Safety backup created successfully!
                </div>
            `);
            showToast('Safety backup created', 'success');
        } else {
            showToast('Failed to create safety backup', 'error');
        }
    });
}

// Update summary
function updateRestoreSummary() {
    const mode = $('input[name="restoreMode"]:checked').val();
    let summary = `
        <p><strong>Backup:</strong> <?php echo htmlspecialchars($backup['backup_name'] ?? ''); ?></p>
        <p><strong>Mode:</strong> ${mode === 'full' ? 'Full Restoration' : 'Selective Tables'}</p>
    `;
    
    if (mode === 'tables') {
        const tables = [];
        $('.restore-table:checked').each(function() {
            tables.push($(this).val());
        });
        summary += `<p><strong>Tables:</strong> ${tables.join(', ')}</p>`;
    }
    
    summary += `<p><strong>Safety Backup:</strong> ${safetyBackupCreated ? '✓ Created' : '✗ Not Created'}</p>`;
    
    $('#restoreSummary').html(summary);
}

// Start restoration
function startRestore() {
    if (!$('#confirmRestore').is(':checked')) {
        showToast('Please confirm the restoration', 'warning');
        return;
    }
    
    if ($('#confirmText').val() !== 'RESTORE') {
        showToast('Please type RESTORE to confirm', 'warning');
        return;
    }
    
    const mode = $('input[name="restoreMode"]:checked').val();
    const tables = [];
    
    if (mode === 'tables') {
        $('.restore-table:checked').each(function() {
            tables.push($(this).val());
        });
        
        if (tables.length === 0) {
            showToast('Please select at least one table', 'warning');
            return;
        }
    }
    
    Swal.fire({
        title: 'Restoring Database...',
        html: `
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
            </div>
            <p class="mt-3 text-muted">This may take several minutes. Do not close this window.</p>
        `,
        allowOutsideClick: false,
        showConfirmButton: false
    });
    
    $.post(APP_URL + '/admin/actions/restore-operations.php', {
        action: 'restore_backup',
        backup_id: <?php echo $backup_id ?? 0; ?>,
        mode: mode,
        tables: tables.join(',')
    })
    .done(function(response) {
        if (response.success) {
            Swal.fire({
                title: 'Success!',
                text: 'Database restored successfully',
                icon: 'success',
                confirmButtonColor: '#059669'
            }).then(() => {
                window.location.href = APP_URL + '/admin/backup-manager.php';
            });
        } else {
            Swal.fire({
                title: 'Restoration Failed',
                text: response.message,
                icon: 'error',
                confirmButtonColor: '#dc2626'
            });
        }
    })
    .fail(function() {
        Swal.fire({
            title: 'Error',
            text: 'Failed to restore database',
            icon: 'error',
            confirmButtonColor: '#dc2626'
        });
    });
}
</script>

<?php renderAdminFooter(); ?>