<?php
/**
 * Database Backup Script
 * Creates a backup of the database before migration
 */

// Include database connection
require_once 'connect.php';

// Configuration
$backupDir = 'backups/';
$timestamp = date('Y-m-d_H-i-s');
$backupFile = $backupDir . "backup_{$db}_{$timestamp}.sql";

// Create backup directory if it doesn't exist
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Database Backup Tool</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
        .container { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .button { background: #007bff; color: white; padding: 12px 24px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; margin: 5px; }
        .button:hover { background: #0056b3; }
        .button.success { background: #28a745; }
        .button.success:hover { background: #218838; }
        .log { background: #f8f9fa; border: 1px solid #dee2e6; padding: 15px; border-radius: 5px; height: 300px; overflow-y: auto; font-family: monospace; font-size: 14px; }
        .status { padding: 10px; border-radius: 5px; margin: 10px 0; }
        .status.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .status.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <div class="container">
        <h1>💾 Database Backup Tool</h1>
        <p>Create a backup of your database before performing migrations</p>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
            <h3>Backup Configuration</h3>
            <p><strong>Database:</strong> <?= htmlspecialchars($db) ?></p>
            <p><strong>Host:</strong> <?= htmlspecialchars($host) ?></p>
            <p><strong>Backup File:</strong> <?= htmlspecialchars($backupFile) ?></p>
        </div>
        
        <div style="text-align: center; margin: 20px 0;">
            <button class="button success" onclick="createBackup()">🚀 Create Backup</button>
            <button class="button" onclick="listBackups()">📋 List Backups</button>
        </div>
        
        <div id="status-section"></div>
        
        <h3>📝 Backup Log</h3>
        <div id="log" class="log">
            <div style="color: #6c757d;">Backup log will appear here...</div>
        </div>
    </div>

    <script>
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const colors = {
                'info': '#333',
                'success': '#28a745',
                'error': '#dc3545'
            };
            
            logDiv.innerHTML += `<div style="color: ${colors[type]}; margin: 2px 0;">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function showStatus(message, type) {
            const statusDiv = document.getElementById('status-section');
            statusDiv.innerHTML = `<div class="status ${type}">${message}</div>`;
        }

        function createBackup() {
            log('Starting database backup...', 'info');
            
            fetch('backup_database.php?action=backup', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    log('✅ Backup created successfully: ' + data.filename, 'success');
                    showStatus('Backup created successfully! File: ' + data.filename, 'success');
                } else {
                    log('❌ Backup failed: ' + data.error, 'error');
                    showStatus('Backup failed: ' + data.error, 'error');
                }
            })
            .catch(error => {
                log('❌ Backup error: ' + error, 'error');
                showStatus('Backup error: ' + error, 'error');
            });
        }

        function listBackups() {
            log('Listing available backups...', 'info');
            
            fetch('backup_database.php?action=list', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    log('📋 Available backups:', 'info');
                    data.backups.forEach(backup => {
                        log('  - ' + backup.name + ' (' + backup.size + ', ' + backup.date + ')', 'info');
                    });
                } else {
                    log('❌ Failed to list backups: ' + data.error, 'error');
                }
            })
            .catch(error => {
                log('❌ Error listing backups: ' + error, 'error');
            });
        }
    </script>
</body>
</html>

<?php
// Handle AJAX requests
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    try {
        switch ($_GET['action']) {
            case 'backup':
                echo json_encode(createDatabaseBackup($pdo, $db, $backupFile));
                break;
                
            case 'list':
                echo json_encode(listBackupFiles($backupDir));
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Invalid action']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

/**
 * Create database backup
 */
function createDatabaseBackup($pdo, $database, $backupFile) {
    try {
        $sql = "-- Database Backup\n";
        $sql .= "-- Generated on: " . date('Y-m-d H:i:s') . "\n";
        $sql .= "-- Database: $database\n\n";
        
        $sql .= "SET FOREIGN_KEY_CHECKS=0;\n\n";
        
        // Get all tables
        $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        
        foreach ($tables as $table) {
            // Get table structure
            $createTable = $pdo->query("SHOW CREATE TABLE `$table`")->fetch(PDO::FETCH_ASSOC);
            $sql .= "-- Table structure for `$table`\n";
            $sql .= "DROP TABLE IF EXISTS `$table`;\n";
            $sql .= $createTable['Create Table'] . ";\n\n";
            
            // Get table data
            $rows = $pdo->query("SELECT * FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
            
            if (!empty($rows)) {
                $sql .= "-- Data for table `$table`\n";
                $sql .= "INSERT INTO `$table` VALUES\n";
                
                $values = [];
                foreach ($rows as $row) {
                    $rowValues = [];
                    foreach ($row as $value) {
                        if ($value === null) {
                            $rowValues[] = 'NULL';
                        } else {
                            $rowValues[] = "'" . addslashes($value) . "'";
                        }
                    }
                    $values[] = '(' . implode(', ', $rowValues) . ')';
                }
                
                $sql .= implode(",\n", $values) . ";\n\n";
            }
        }
        
        $sql .= "SET FOREIGN_KEY_CHECKS=1;\n";
        
        // Write to file
        if (file_put_contents($backupFile, $sql) !== false) {
            return [
                'success' => true,
                'filename' => basename($backupFile),
                'size' => formatBytes(filesize($backupFile))
            ];
        } else {
            return ['success' => false, 'error' => 'Failed to write backup file'];
        }
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * List backup files
 */
function listBackupFiles($backupDir) {
    try {
        $backups = [];
        
        if (is_dir($backupDir)) {
            $files = glob($backupDir . '*.sql');
            
            foreach ($files as $file) {
                $backups[] = [
                    'name' => basename($file),
                    'size' => formatBytes(filesize($file)),
                    'date' => date('Y-m-d H:i:s', filemtime($file))
                ];
            }
        }
        
        return ['success' => true, 'backups' => $backups];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * Format file size
 */
function formatBytes($size, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB'];
    
    for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
        $size /= 1024;
    }
    
    return round($size, $precision) . ' ' . $units[$i];
}
?>