<?php
/**
 * ============================================================================
 * admin/disaster-recovery.php - Disaster Recovery Center
 * Emergency recovery procedures and system health checks
 * ============================================================================
 */

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

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

$breadcrumbs = [['title' => 'Disaster Recovery', 'url' => '']];

// Check system health
function checkSystemHealth() {
    global $db;
    $health = [
        'database' => 'ok',
        'tables' => 'ok',
        'backups' => 'ok',
        'disk_space' => 'ok',
        'permissions' => 'ok'
    ];
    
    // Check database connection
    try {
        $db->query("SELECT 1");
    } catch (Exception $e) {
        $health['database'] = 'critical';
    }
    
    // Check critical tables
    try {
        $critical_tables = ['users', 'products', 'orders', 'database_backups'];
        foreach ($critical_tables as $table) {
            $db->query("SELECT 1 FROM $table LIMIT 1");
        }
    } catch (Exception $e) {
        $health['tables'] = 'warning';
    }
    
    // Check recent backups
    try {
        $sql = "SELECT COUNT(*) as count FROM database_backups 
                WHERE backup_status = 'completed' 
                AND started_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $stmt = $db->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result['count'] == 0) {
            $health['backups'] = 'warning';
        }
    } catch (Exception $e) {
        $health['backups'] = 'critical';
    }
    
    // Check disk space
    $free_space = disk_free_space('/');
    $total_space = disk_total_space('/');
    $used_percent = (($total_space - $free_space) / $total_space) * 100;
    if ($used_percent > 90) {
        $health['disk_space'] = 'critical';
    } elseif ($used_percent > 80) {
        $health['disk_space'] = 'warning';
    }
    
    return $health;
}

$health = checkSystemHealth();
$overall_status = in_array('critical', $health) ? 'critical' : (in_array('warning', $health) ? 'warning' : 'ok');

renderAdminHeader('Disaster Recovery', $breadcrumbs);
?>

<style>
.health-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
}
.health-indicator.ok { background-color: #10b981; }
.health-indicator.warning { background-color: #f59e0b; }
.health-indicator.critical { background-color: #ef4444; }

.recovery-action {
    transition: all 0.3s ease;
    cursor: pointer;
}
.recovery-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.emergency-btn {
    font-size: 1.1rem;
    padding: 1rem 2rem;
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">
            <i class="bi bi-shield-exclamation me-2"></i>Disaster Recovery Center
        </h2>
        <p class="text-muted mb-0">Emergency recovery procedures and system diagnostics</p>
    </div>
    <div>
        <span class="badge bg-<?php echo $overall_status === 'ok' ? 'success' : ($overall_status === 'warning' ? 'warning' : 'danger'); ?> fs-6 px-3 py-2">
            System Status: <?php echo strtoupper($overall_status); ?>
        </span>
    </div>
</div>

<!-- Emergency Actions -->
<div class="alert alert-danger border-0 shadow-sm mb-4">
    <div class="d-flex align-items-center mb-3">
        <i class="bi bi-exclamation-triangle-fill me-3" style="font-size: 2rem;"></i>
        <div>
            <h5 class="mb-0">Emergency Recovery Actions</h5>
            <p class="mb-0">Use these tools only in emergency situations</p>
        </div>
    </div>
    <div class="d-flex gap-2 mt-3">
        <button class="btn btn-danger" onclick="emergencyRestore()">
            <i class="bi bi-arrow-counterclockwise me-2"></i>Emergency Restore
        </button>
        <button class="btn btn-warning" onclick="repairDatabase()">
            <i class="bi bi-tools me-2"></i>Repair Database
        </button>
        <button class="btn btn-info" onclick="systemDiagnostics()">
            <i class="bi bi-activity me-2"></i>Run Diagnostics
        </button>
    </div>
</div>

<!-- System Health Overview -->
<div class="row mb-4">
    <div class="col-md-4 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-2">Database Connection</h6>
                        <h5 class="mb-0">
                            <span class="health-indicator <?php echo $health['database']; ?>"></span>
                            <?php echo ucfirst($health['database']); ?>
                        </h5>
                    </div>
                    <i class="bi bi-database text-primary" style="font-size: 2rem;"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-2">Critical Tables</h6>
                        <h5 class="mb-0">
                            <span class="health-indicator <?php echo $health['tables']; ?>"></span>
                            <?php echo ucfirst($health['tables']); ?>
                        </h5>
                    </div>
                    <i class="bi bi-table text-success" style="font-size: 2rem;"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-muted mb-2">Recent Backups</h6>
                        <h5 class="mb-0">
                            <span class="health-indicator <?php echo $health['backups']; ?>"></span>
                            <?php echo ucfirst($health['backups']); ?>
                        </h5>
                    </div>
                    <i class="bi bi-save text-warning" style="font-size: 2rem;"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recovery Procedures -->
<div class="row mb-4">
    <div class="col-lg-6 mb-3">
        <div class="card border-0 shadow-sm recovery-action" onclick="window.location.href='<?php echo APP_URL; ?>/admin/backup-manager.php'">
            <div class="card-body p-4">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                            <i class="bi bi-arrow-counterclockwise fs-4"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h5 class="fw-bold mb-2">Restore from Backup</h5>
                        <p class="text-muted mb-0">Restore your database from a previous backup. Choose specific tables or perform a full restoration.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-6 mb-3">
        <div class="card border-0 shadow-sm recovery-action" onclick="createEmergencyBackup()">
            <div class="card-body p-4">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-success text-white d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                            <i class="bi bi-save fs-4"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h5 class="fw-bold mb-2">Emergency Backup</h5>
                        <p class="text-muted mb-0">Create an immediate backup of your current database state before performing recovery operations.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-6 mb-3">
        <div class="card border-0 shadow-sm recovery-action" onclick="checkDatabaseIntegrity()">
            <div class="card-body p-4">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-info text-white d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                            <i class="bi bi-check-circle fs-4"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h5 class="fw-bold mb-2">Check Database Integrity</h5>
                        <p class="text-muted mb-0">Verify database tables for corruption and inconsistencies. Identifies issues that need repair.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-6 mb-3">
        <div class="card border-0 shadow-sm recovery-action" onclick="optimizeAllTables()">
            <div class="card-body p-4">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle bg-warning text-white d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                            <i class="bi bi-gear fs-4"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h5 class="fw-bold mb-2">Optimize Database</h5>
                        <p class="text-muted mb-0">Optimize all database tables to improve performance and fix minor issues.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recovery Documentation -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-book me-2"></i>Recovery Procedures Documentation
        </h5>
    </div>
    <div class="card-body">
        <div class="accordion" id="recoveryAccordion">
            <!-- Database Corruption -->
            <div class="accordion-item border-0 mb-2">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#corruption">
                        <i class="bi bi-exclamation-triangle text-danger me-2"></i>
                        Database Corruption Recovery
                    </button>
                </h2>
                <div id="corruption" class="accordion-collapse collapse" data-bs-parent="#recoveryAccordion">
                    <div class="accordion-body">
                        <ol>
                            <li><strong>Create Emergency Backup:</strong> Click "Emergency Backup" to save current state</li>
                            <li><strong>Check Integrity:</strong> Run "Check Database Integrity" to identify corrupted tables</li>
                            <li><strong>Repair Tables:</strong> Use "Repair Database" to fix corrupted tables</li>
                            <li><strong>Verify:</strong> Check system health indicators after repair</li>
                            <li><strong>Restore if Needed:</strong> If repair fails, restore from the most recent working backup</li>
                        </ol>
                    </div>
                </div>
            </div>
            
            <!-- Data Loss -->
            <div class="accordion-item border-0 mb-2">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#dataloss">
                        <i class="bi bi-database-x text-warning me-2"></i>
                        Data Loss Recovery
                    </button>
                </h2>
                <div id="dataloss" class="accordion-collapse collapse" data-bs-parent="#recoveryAccordion">
                    <div class="accordion-body">
                        <ol>
                            <li><strong>Identify Issue:</strong> Determine which tables or data are affected</li>
                            <li><strong>Choose Backup:</strong> Go to Backup Manager and select appropriate backup</li>
                            <li><strong>Selective Restore:</strong> Use selective table restoration if only specific data is lost</li>
                            <li><strong>Full Restore:</strong> Perform full database restoration for complete data loss</li>
                            <li><strong>Verify Data:</strong> Check that all data has been restored correctly</li>
                        </ol>
                    </div>
                </div>
            </div>
            
            <!-- Performance Issues -->
            <div class="accordion-item border-0 mb-2">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#performance">
                        <i class="bi bi-speedometer text-info me-2"></i>
                        Performance Degradation Recovery
                    </button>
                </h2>
                <div id="performance" class="accordion-collapse collapse" data-bs-parent="#recoveryAccordion">
                    <div class="accordion-body">
                        <ol>
                            <li><strong>Run Diagnostics:</strong> Use "Run Diagnostics" to identify issues</li>
                            <li><strong>Optimize Database:</strong> Click "Optimize Database" to defragment tables</li>
                            <li><strong>Check Indexes:</strong> Verify that all indexes are properly maintained</li>
                            <li><strong>Clear Cache:</strong> Clear application cache if performance issues persist</li>
                            <li><strong>Monitor:</strong> Use Performance Monitor to track improvements</li>
                        </ol>
                    </div>
                </div>
            </div>
            
            <!-- Connection Issues -->
            <div class="accordion-item border-0">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#connection">
                        <i class="bi bi-plug text-danger me-2"></i>
                        Database Connection Issues
                    </button>
                </h2>
                <div id="connection" class="accordion-collapse collapse" data-bs-parent="#recoveryAccordion">
                    <div class="accordion-body">
                        <ol>
                            <li><strong>Verify Credentials:</strong> Check database connection settings in config file</li>
                            <li><strong>Check Service:</strong> Ensure MySQL/MariaDB service is running</li>
                            <li><strong>Network Issues:</strong> Verify network connectivity to database server</li>
                            <li><strong>Restart Service:</strong> Restart database service if needed</li>
                            <li><strong>Contact Support:</strong> If issues persist, contact technical support</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- System Information -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-info-circle me-2"></i>System Information
        </h5>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <table class="table table-sm">
                    <tr>
                        <td class="text-muted">Database Version</td>
                        <td class="fw-semibold"><?php 
                            try {
                                $version = $db->query("SELECT VERSION()")->fetchColumn();
                                echo $version;
                            } catch (Exception $e) {
                                echo 'N/A';
                            }
                        ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">PHP Version</td>
                        <td class="fw-semibold"><?php echo PHP_VERSION; ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Server Time</td>
                        <td class="fw-semibold"><?php echo date('Y-m-d H:i:s'); ?></td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table table-sm">
                    <tr>
                        <td class="text-muted">Disk Free Space</td>
                        <td class="fw-semibold"><?php echo number_format(disk_free_space('/') / 1024 / 1024 / 1024, 2); ?> GB</td>
                    </tr>
                    <tr>
                        <td class="text-muted">Memory Limit</td>
                        <td class="fw-semibold"><?php echo ini_get('memory_limit'); ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Max Execution Time</td>
                        <td class="fw-semibold"><?php echo ini_get('max_execution_time'); ?>s</td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// Emergency Restore
function emergencyRestore() {
    Swal.fire({
        title: 'Emergency Database Restore',
        html: 'This will restore the database from the most recent backup.<br><strong class="text-danger">All current data will be replaced!</strong>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        confirmButtonText: 'Proceed to Restore',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = APP_URL + '/admin/backup-manager.php';
        }
    });
}

// Repair Database
function repairDatabase() {
    Swal.fire({
        title: 'Repair Database?',
        text: 'This will attempt to repair all database tables.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#f59e0b',
        confirmButtonText: 'Yes, Repair Now'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Repairing Database...',
                html: 'Please wait while we repair the database tables.',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.post(APP_URL + '/admin/actions/disaster-recovery.php', {
                action: 'repair_all_tables'
            })
            .done(function(response) {
                Swal.close();
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success',
                        confirmButtonColor: '#059669'
                    }).then(() => location.reload());
                } else {
                    showToast(response.message, 'error');
                }
            });
        }
    });
}

// System Diagnostics
function systemDiagnostics() {
    Swal.fire({
        title: 'Running System Diagnostics...',
        html: 'Checking database health and performance...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.post(APP_URL + '/admin/actions/disaster-recovery.php', {
        action: 'run_diagnostics'
    })
    .done(function(response) {
        Swal.close();
        if (response.success) {
            let html = '<div class="text-start">';
            html += '<h6>Diagnostic Results:</h6><ul>';
            response.results.forEach(result => {
                const icon = result.status === 'ok' ? '✓' : '✗';
                const color = result.status === 'ok' ? 'text-success' : 'text-danger';
                html += `<li class="${color}">${icon} ${result.message}</li>`;
            });
            html += '</ul></div>';
            
            Swal.fire({
                title: 'Diagnostics Complete',
                html: html,
                icon: 'info',
                width: 600
            });
        }
    });
}

// Create Emergency Backup
function createEmergencyBackup() {
    Swal.fire({
        title: 'Create Emergency Backup?',
        text: 'This will create an immediate backup of your database.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#059669',
        confirmButtonText: 'Yes, Create Backup'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Creating Backup...',
                html: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.post(APP_URL + '/admin/actions/backup-operations.php', {
                action: 'create_backup',
                name: 'emergency_backup_' + Date.now(),
                type: 'full',
                compress: 1
            })
            .done(function(response) {
                Swal.close();
                if (response.success) {
                    showToast('Emergency backup created successfully', 'success');
                } else {
                    showToast('Backup failed: ' + response.message, 'error');
                }
            });
        }
    });
}

// Check Database Integrity
function checkDatabaseIntegrity() {
    Swal.fire({
        title: 'Checking Database Integrity...',
        html: 'This may take a few minutes...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.post(APP_URL + '/admin/actions/disaster-recovery.php', {
        action: 'check_integrity'
    })
    .done(function(response) {
        Swal.close();
        if (response.success) {
            Swal.fire({
                title: 'Integrity Check Complete',
                html: response.message,
                icon: response.issues_found ? 'warning' : 'success'
            });
        }
    });
}

// Optimize All Tables
function optimizeAllTables() {
    Swal.fire({
        title: 'Optimize All Tables?',
        text: 'This will optimize all database tables.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Optimize'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Optimizing Database...',
                html: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.post(APP_URL + '/admin/actions/disaster-recovery.php', {
                action: 'optimize_all'
            })
            .done(function(response) {
                Swal.close();
                if (response.success) {
                    showToast('Database optimized successfully', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(response.message, 'error');
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>