<?php
/**
 * Backup System for School Website
 * 
 * This script creates automatic backups of:
 * - SQLite database
 * - Uploaded images
 * 
 * Can be run manually or via cron job
 */

// Prevent direct access from browser (optional security)
$secret_key = 'your-secret-backup-key-123'; // Change this!
if (!isset($_GET['key']) || $_GET['key'] !== $secret_key) {
    die('Access denied. Invalid backup key.');
}

// Configuration
$backupDir = __DIR__ . '/backups';
$dataDir = __DIR__ . '/data';
$dbFile = $dataDir . '/school.db';
$uploadsDir = $dataDir . '/uploads';

// Create backup directory if not exists
if (!is_dir($backupDir)) {
    mkdir($backupDir, 0755, true);
}

// Generate timestamp for backup filename
$timestamp = date('Y-m-d_H-i-s');
$backupSubDir = $backupDir . '/' . date('Y-m-d');

if (!is_dir($backupSubDir)) {
    mkdir($backupSubDir, 0755, true);
}

$results = [];

// 1. Backup Database
try {
    if (file_exists($dbFile)) {
        $dbBackupFile = $backupSubDir . '/school_' . $timestamp . '.db';
        if (copy($dbFile, $dbBackupFile)) {
            $dbSize = filesize($dbBackupFile);
            $results['database'] = [
                'status' => 'success',
                'file' => $dbBackupFile,
                'size' => formatBytes($dbSize)
            ];
        } else {
            $results['database'] = ['status' => 'failed', 'error' => 'Copy failed'];
        }
    } else {
        $results['database'] = ['status' => 'failed', 'error' => 'Database file not found'];
    }
} catch (Exception $e) {
    $results['database'] = ['status' => 'failed', 'error' => $e->getMessage()];
}

// 2. Backup Uploads (optional - can be large)
try {
    if (is_dir($uploadsDir)) {
        $uploadsBackupFile = $backupSubDir . '/uploads_' . $timestamp . '.zip';
        
        if (class_exists('ZipArchive')) {
            $zip = new ZipArchive();
            if ($zip->open($uploadsBackupFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($uploadsDir),
                    RecursiveIteratorIterator::LEAVES_ONLY
                );
                
                $fileCount = 0;
                foreach ($files as $file) {
                    if (!$file->isDir()) {
                        $filePath = $file->getRealPath();
                        $relativePath = substr($filePath, strlen($uploadsDir) + 1);
                        $zip->addFile($filePath, $relativePath);
                        $fileCount++;
                    }
                }
                
                $zip->close();
                $zipSize = filesize($uploadsBackupFile);
                $results['uploads'] = [
                    'status' => 'success',
                    'file' => $uploadsBackupFile,
                    'size' => formatBytes($zipSize),
                    'files' => $fileCount
                ];
            } else {
                $results['uploads'] = ['status' => 'failed', 'error' => 'Could not create ZIP'];
            }
        } else {
            $results['uploads'] = ['status' => 'skipped', 'error' => 'ZipArchive not available'];
        }
    } else {
        $results['uploads'] = ['status' => 'skipped', 'error' => 'Uploads directory not found'];
    }
} catch (Exception $e) {
    $results['uploads'] = ['status' => 'failed', 'error' => $e->getMessage()];
}

// 3. Clean old backups (keep last 30 days)
$deletedCount = 0;
$retentionDays = 30;
try {
    $backupFolders = glob($backupDir . '/*', GLOB_ONLYDIR);
    foreach ($backupFolders as $folder) {
        $folderDate = basename($folder);
        $folderTime = strtotime($folderDate);
        
        if ($folderTime && $folderTime < time() - ($retentionDays * 24 * 60 * 60)) {
            deleteDirectory($folder);
            $deletedCount++;
        }
    }
    $results['cleanup'] = [
        'status' => 'success',
        'deleted' => $deletedCount,
        'retention_days' => $retentionDays
    ];
} catch (Exception $e) {
    $results['cleanup'] = ['status' => 'failed', 'error' => $e->getMessage()];
}

// 4. Generate backup report
$results['summary'] = [
    'timestamp' => date('Y-m-d H:i:s'),
    'backup_dir' => $backupSubDir,
    'total_backups' => count(glob($backupDir . '/*', GLOB_ONLYDIR))
];

// Output results
header('Content-Type: application/json');
echo json_encode($results, JSON_PRETTY_PRINT);

// Helper function to format bytes
function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

// Helper function to delete directory recursively
function deleteDirectory($dir) {
    if (!is_dir($dir)) return false;
    
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        is_dir($path) ? deleteDirectory($path) : unlink($path);
    }
    return rmdir($dir);
}
?>
