<?php
$pageTitle = 'Database Backup';
require_once __DIR__ . '/includes/header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create_backup') {
    $csrf = new CSRF();
    if (!$csrf->verify($_POST['csrf_token'] ?? '')) {
        jsonResponse(false, 'Invalid CSRF token.');
    }

    $backupDir = BASE_PATH . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'backups';
    if (!is_dir($backupDir)) {
        mkdir($backupDir, 0755, true);
    }

    $filename = 'backup_' . date('Y-m-d_His') . '.sql';
    $filepath = $backupDir . DIRECTORY_SEPARATOR . $filename;

    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $tables = [];
    $stmt = $pdo->query("SHOW TABLES");
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $tables[] = $row[0];
    }

    $output = '';
    $output .= "-- Tap2Order Database Backup\n";
    $output .= "-- Generated: " . date('Y-m-d H:i:s') . "\n";
    $output .= "-- \n\n";
    $output .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";

    foreach ($tables as $table) {
        $output .= "-- Table: {$table}\n";
        $output .= "DROP TABLE IF EXISTS `{$table}`;\n";

        $createStmt = $pdo->query("SHOW CREATE TABLE `{$table}`");
        $createRow = $createStmt->fetch(PDO::FETCH_NUM);
        $output .= $createRow[1] . ";\n\n";

        $dataStmt = $pdo->query("SELECT * FROM `{$table}`");
        $rows = $dataStmt->fetchAll(PDO::FETCH_NUM);

        if (!empty($rows)) {
            $colStmt = $pdo->query("SHOW COLUMNS FROM `{$table}`");
            $columns = [];
            while ($colRow = $colStmt->fetch(PDO::FETCH_NUM)) {
                $columns[] = $colRow[0];
            }

            $output .= "INSERT INTO `{$table}` (`" . implode('`, `', $columns) . "`) VALUES\n";

            $valueLines = [];
            foreach ($rows as $row) {
                $values = [];
                foreach ($row as $val) {
                    if ($val === null) {
                        $values[] = 'NULL';
                    } else {
                        $values[] = "'" . addslashes($val) . "'";
                    }
                }
                $valueLines[] = '(' . implode(', ', $values) . ')';
            }
            $output .= implode(",\n", $valueLines) . ";\n\n";
        }
    }

    $output .= "SET FOREIGN_KEY_CHECKS = 1;\n";

    if (file_put_contents($filepath, $output)) {
        $activityLog = new ActivityLog();
        $activityLog->log($_SESSION['user_id'], null, 'backup', 'create', 'Created database backup: ' . $filename);
        jsonResponse(true, 'Backup created successfully: ' . $filename);
    } else {
        jsonResponse(false, 'Failed to create backup file.');
    }
}

$db = Database::getInstance();
$backupDir = BASE_PATH . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'backups';
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

$backups = [];
if (is_dir($backupDir)) {
    $files = glob($backupDir . DIRECTORY_SEPARATOR . '*.sql');
    foreach ($files as $file) {
        $backups[] = [
            'name' => basename($file),
            'size' => filesize($file),
            'date' => date('Y-m-d H:i:s', filemtime($file)),
            'path' => $file,
        ];
    }
    usort($backups, function($a, $b) {
        return strtotime($b['date']) - strtotime($a['date']);
    });
}

if (isset($_GET['download']) && !empty($_GET['file'])) {
    $file = basename($_GET['file']);
    $filePath = $backupDir . DIRECTORY_SEPARATOR . $file;
    if (file_exists($filePath) && preg_match('/^backup_.*\.sql$/', $file)) {
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete']) && !empty($_POST['file'])) {
    $csrf = new CSRF();
    if (!$csrf->verify($_POST['csrf_token'] ?? '')) {
        jsonResponse(false, 'Invalid CSRF token.');
    }
    $file = basename($_POST['file']);
    $filePath = $backupDir . DIRECTORY_SEPARATOR . $file;
    if (file_exists($filePath) && preg_match('/^backup_.*\.sql$/', $file)) {
        unlink($filePath);
        $activityLog = new ActivityLog();
        $activityLog->log($_SESSION['user_id'], null, 'backup', 'delete', 'Deleted backup: ' . $file);
    }
    redirect($baseUrl . '/admin/backup.php');
}
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Database Backup</h6>
    <button type="button" class="btn btn-primary btn-sm" id="createBackupBtn"><i class="fas fa-download me-1"></i>Create Backup</button>
</div>

<div class="row mb-4">
    <div class="col-md-4">
        <div class="stat-card" style="border-left-color:#4f46e5;">
            <div class="stat-value"><?php echo count($backups); ?></div>
            <div class="stat-label">Total Backups</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card" style="border-left-color:#10b981;">
            <div class="stat-value"><?php echo !empty($backups) ? date('M d, Y', strtotime($backups[0]['date'])) : 'None'; ?></div>
            <div class="stat-label">Last Backup</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card" style="border-left-color:#f59e0b;">
            <div class="stat-value"><?php echo !empty($backups) ? round(array_sum(array_column($backups, 'size')) / 1024, 1) . ' KB' : '0 KB'; ?></div>
            <div class="stat-label">Total Size</div>
        </div>
    </div>
</div>

<div class="table-card">
    <div class="card-header"><i class="fas fa-database me-2"></i>Backup Files</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead class="table-light">
                    <tr><th>Filename</th><th>Size</th><th>Date</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php if (empty($backups)): ?>
                        <tr><td colspan="4" class="text-center text-muted py-3">No backups found. Create your first backup above.</td></tr>
                    <?php else: ?>
                        <?php foreach ($backups as $backup): ?>
                        <tr>
                            <td><i class="fas fa-file-code me-2 text-primary"></i><?php echo sanitize($backup['name']); ?></td>
                            <td><?php echo round($backup['size'] / 1024, 1); ?> KB</td>
                            <td><?php echo formatDateTime($backup['date']); ?></td>
                            <td>
                                <a href="?download=1&file=<?php echo urlencode($backup['name']); ?>" class="btn btn-sm btn-outline-success btn-action" title="Download"><i class="fas fa-download"></i></a>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this backup?')">
                                    <input type="hidden" name="delete" value="1">
                                    <input type="hidden" name="file" value="<?php echo sanitize($backup['name']); ?>">
                                    <?php echo $csrf->field(); ?>
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.getElementById('createBackupBtn').addEventListener('click', function() {
    this.disabled = true;
    this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Creating...';
    fetch(BASE_URL + '/admin/backup.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
        body: 'action=create_backup&csrf_token=' + encodeURIComponent(CSRF_TOKEN)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            showAlert('success', data.message);
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showAlert('danger', data.message);
            document.getElementById('createBackupBtn').disabled = false;
            document.getElementById('createBackupBtn').innerHTML = '<i class="fas fa-download me-1"></i>Create Backup';
        }
    })
    .catch(function() {
        showAlert('danger', 'Network error.');
        document.getElementById('createBackupBtn').disabled = false;
        document.getElementById('createBackupBtn').innerHTML = '<i class="fas fa-download me-1"></i>Create Backup';
    });
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
