<?php
/**
 * ============================================================================
 * admin/backup-manager.php - Database Backup Management
 * Create, manage, and schedule database backups
 * ============================================================================
 */

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' => '']];

// Get existing backups
try {
    $sql = "SELECT * FROM database_backups 
            WHERE deleted_at IS NULL 
            ORDER BY started_at DESC 
            LIMIT 50";
    $stmt = $db->query($sql);
    $backups = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Backup statistics
    $sql = "SELECT 
                COUNT(*) as total_backups,
                SUM(backup_size) / 1024 / 1024 / 1024 as total_size_gb,
                COUNT(CASE WHEN backup_status = 'completed' THEN 1 END) as successful,
                COUNT(CASE WHEN backup_status = 'failed' THEN 1 END) as failed
            FROM database_backups 
            WHERE deleted_at IS NULL";
    $stmt = $db->query($sql);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Backup manager error: ' . $e->getMessage());
    $backups = [];
    $stats = ['total_backups' => 0, 'total_size_gb' => 0, 'successful' => 0, 'failed' => 0];
}

renderAdminHeader('Backup Manager', $breadcrumbs);
?>

<style>
.backup-card {
    transition: all 0.3s ease;
}
.backup-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1) !important;
}
</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-save me-2"></i>Backup Manager
        </h2>
        <p class="text-muted mb-0">Create and manage database backups</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="scheduleBackup()">
            <i class="bi bi-clock me-2"></i>Schedule Backup
        </button>
        <button class="btn btn-primary" onclick="createBackup()">
            <i class="bi bi-plus-circle me-2"></i>Create Backup Now
        </button>
    </div>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm backup-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-archive-fill text-primary" style="font-size: 2rem;"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-0">Total Backups</h6>
                        <h3 class="fw-bold mb-0"><?php echo number_format($stats['total_backups']); ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card border-0 shadow-sm backup-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-hdd-fill text-info" style="font-size: 2rem;"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-0">Total Size</h6>
                        <h3 class="fw-bold mb-0"><?php echo number_format($stats['total_size_gb'], 2); ?> GB</h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card border-0 shadow-sm backup-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-check-circle-fill text-success" style="font-size: 2rem;"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-0">Successful</h6>
                        <h3 class="fw-bold mb-0"><?php echo number_format($stats['successful']); ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card border-0 shadow-sm backup-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-x-circle-fill text-danger" style="font-size: 2rem;"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-0">Failed</h6>
                        <h3 class="fw-bold mb-0"><?php echo number_format($stats['failed']); ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Backup List -->
<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-list-ul me-2"></i>Backup History
        </h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Backup Name</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Size</th>
                        <th>Tables</th>
                        <th>Created</th>
                        <th>Duration</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($backups)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-5 text-muted">
                            <i class="bi bi-inbox display-4 d-block mb-3"></i>
                            No backups found. Create your first backup to get started.
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($backups as $backup): ?>
                        <tr>
                            <td class="fw-semibold">
                                <i class="bi bi-file-earmark-zip me-2 text-primary"></i>
                                <?php echo htmlspecialchars($backup['backup_name']); ?>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo $backup['backup_type'] === 'full' ? 'primary' : 'secondary'; ?>">
                                    <?php echo ucfirst($backup['backup_type']); ?>
                                </span>
                            </td>
                            <td>
                                <?php
                                $statusColors = [
                                    'completed' => 'success',
                                    'in_progress' => 'warning',
                                    'failed' => 'danger',
                                    'corrupted' => 'danger'
                                ];
                                $color = $statusColors[$backup['backup_status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $color; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $backup['backup_status'])); ?>
                                </span>
                            </td>
                            <td><?php echo $backup['backup_size'] ? number_format($backup['backup_size'] / 1024 / 1024, 2) . ' MB' : '-'; ?></td>
                            <td><?php echo $backup['tables_included'] ? count(explode(',', $backup['tables_included'])) : 'All'; ?></td>
                            <td><?php echo date('Y-m-d H:i', strtotime($backup['started_at'])); ?></td>
                            <td>
                                <?php 
                                if ($backup['completed_at']) {
                                    $duration = strtotime($backup['completed_at']) - strtotime($backup['started_at']);
                                    echo gmdate("i:s", $duration);
                                } else {
                                    echo '-';
                                }
                                ?>
                            </td>
                            <td class="text-center">
                                <div class="btn-group btn-group-sm">
                                    <?php if ($backup['backup_status'] === 'completed'): ?>
                                    <button class="btn btn-outline-success" onclick="downloadBackup(<?php echo $backup['id']; ?>)">
                                        <i class="bi bi-download"></i>
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="restoreBackup(<?php echo $backup['id']; ?>)">
                                        <i class="bi bi-arrow-counterclockwise"></i>
                                    </button>
                                    <?php endif; ?>
                                    <button class="btn btn-outline-info" onclick="viewBackupDetails(<?php echo $backup['id']; ?>)">
                                        <i class="bi bi-info-circle"></i>
                                    </button>
                                    <button class="btn btn-outline-danger" onclick="deleteBackup(<?php echo $backup['id']; ?>)">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create Backup Modal -->
<div class="modal fade" id="createBackupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create New Backup</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="backupForm">
                    <div class="mb-3">
                        <label class="form-label">Backup Name</label>
                        <input type="text" class="form-control" id="backupName" 
                               value="backup_<?php echo date('Y-m-d_His'); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Backup Type</label>
                        <select class="form-select" id="backupType">
                            <option value="full">Full Backup (All tables)</option>
                            <option value="partial">Partial Backup (Select tables)</option>
                        </select>
                    </div>
                    
                    <div class="mb-3" id="tablesSelection" style="display: none;">
                        <label class="form-label">Select Tables</label>
                        <div class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                            <?php
                            try {
                                $sql = "SHOW TABLES";
                                $stmt = $db->query($sql);
                                $allTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
                                
                                foreach ($allTables as $table) {
                                    echo '<div class="form-check">';
                                    echo '<input class="form-check-input table-checkbox" type="checkbox" value="' . $table . '" id="table_' . $table . '">';
                                    echo '<label class="form-check-label" for="table_' . $table . '">' . $table . '</label>';
                                    echo '</div>';
                                }
                            } catch (Exception $e) {
                                echo '<p class="text-muted">Unable to load tables</p>';
                            }
                            ?>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="compressBackup" checked>
                            <label class="form-check-label" for="compressBackup">
                                Compress backup (GZIP)
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="encryptBackup">
                            <label class="form-check-label" for="encryptBackup">
                                Encrypt backup
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitBackup()">
                    <i class="bi bi-save me-2"></i>Create Backup
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Show/hide table selection
$('#backupType').change(function() {
    if ($(this).val() === 'partial') {
        $('#tablesSelection').show();
    } else {
        $('#tablesSelection').hide();
    }
});

// Create Backup
function createBackup() {
    $('#createBackupModal').modal('show');
}

// Submit Backup
function submitBackup() {
    const name = $('#backupName').val();
    const type = $('#backupType').val();
    const compress = $('#compressBackup').is(':checked');
    const encrypt = $('#encryptBackup').is(':checked');
    
    let tables = [];
    if (type === 'partial') {
        $('.table-checkbox:checked').each(function() {
            tables.push($(this).val());
        });
        
        if (tables.length === 0) {
            showToast('Please select at least one table', 'warning');
            return;
        }
    }
    
    $('#createBackupModal').modal('hide');
    
    Swal.fire({
        title: 'Creating Backup...',
        html: 'Please wait while the backup is being created.',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.post(APP_URL + '/admin/actions/backup-operations.php', {
        action: 'create_backup',
        name: name,
        type: type,
        tables: tables.join(','),
        compress: compress ? 1 : 0,
        encrypt: encrypt ? 1 : 0
    }).done(function(response) {
        Swal.close();
        
        if (response.success) {
            Swal.fire({
                title: 'Success!',
                text: 'Backup created successfully',
                icon: 'success',
                confirmButtonColor: '#059669'
            }).then(() => {
                location.reload();
            });
        } else {
            showToast('Backup failed: ' + response.message, 'error');
        }
    }).fail(function() {
        Swal.close();
        showToast('Connection error', 'error');
    });
}

// Download Backup
function downloadBackup(id) {
    window.location.href = APP_URL + '/admin/actions/backup-operations.php?action=download&id=' + id;
}

// Restore Backup
function restoreBackup(id) {
    window.location.href = APP_URL + '/admin/restore.php?backup_id=' + id;
}

// View Backup Details
function viewBackupDetails(id) {
    showLoading();
    
    $.post(APP_URL + '/admin/actions/backup-operations.php', {
        action: 'get_details',
        id: id
    }).done(function(response) {
        hideLoading();
        
        if (response.success) {
            const backup = response.data;
            
            Swal.fire({
                title: 'Backup Details',
                html: `
                    <div class="text-start">
                        <p><strong>Name:</strong> ${backup.backup_name}</p>
                        <p><strong>Type:</strong> ${backup.backup_type}</p>
                        <p><strong>Size:</strong> ${(backup.backup_size / 1024 / 1024).toFixed(2)} MB</p>
                        <p><strong>Status:</strong> ${backup.backup_status}</p>
                        <p><strong>Created:</strong> ${backup.started_at}</p>
                        <p><strong>Completed:</strong> ${backup.completed_at || 'N/A'}</p>
                        ${backup.tables_included ? '<p><strong>Tables:</strong> ' + backup.tables_included + '</p>' : ''}
                        ${backup.error_message ? '<p class="text-danger"><strong>Error:</strong> ' + backup.error_message + '</p>' : ''}
                    </div>
                `,
                width: 600
            });
        }
    });
}

// Delete Backup
function deleteBackup(id) {
    Swal.fire({
        title: 'Delete Backup?',
        text: 'This will permanently delete the backup file.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        confirmButtonText: 'Yes, Delete'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            
            $.post(APP_URL + '/admin/actions/backup-operations.php', {
                action: 'delete_backup',
                id: id
            }).done(function(response) {
                hideLoading();
                
                if (response.success) {
                    showToast('Backup deleted successfully', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast('Delete failed: ' + response.message, 'error');
                }
            });
        }
    });
}

// Schedule Backup
function scheduleBackup() {
    Swal.fire({
        title: 'Schedule Automatic Backups',
        html: `
            <div class="text-start">
                <div class="mb-3">
                    <label class="form-label">Frequency</label>
                    <select class="form-select" id="scheduleFrequency">
                        <option value="daily">Daily</option>
                        <option value="weekly">Weekly</option>
                        <option value="monthly">Monthly</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Time</label>
                    <input type="time" class="form-control" id="scheduleTime" value="02:00">
                </div>
                <div class="mb-3">
                    <label class="form-label">Retention Days</label>
                    <input type="number" class="form-control" id="retentionDays" value="30" min="1">
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Schedule',
        preConfirm: () => {
            return {
                frequency: $('#scheduleFrequency').val(),
                time: $('#scheduleTime').val(),
                retention: $('#retentionDays').val()
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            showToast('Backup schedule created (feature coming soon)', 'info');
        }
    });
}
</script>

<?php renderAdminFooter(); ?>