<?php
/**
 * Automated Backup System
 * Handles database and file backups with scheduling
 */

// DEBUG: Show all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/SecurityHelper.php';

// Ensure a single session is started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// DEBUG: Check CSRF token status
error_log('backup/index.php: Session ID: ' . session_id());
error_log('backup/index.php: CSRF Token exists: ' . (isset($_SESSION['csrf_token']) ? 'YES' : 'NO'));
if (isset($_SESSION['csrf_token'])) {
    error_log('backup/index.php: CSRF Token: ' . substr($_SESSION['csrf_token'], 0, 10) . '...');
}

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    $_SESSION['csrf_token_time'] = time();
    error_log('backup/index.php: Generated new CSRF token: ' . substr($_SESSION['csrf_token'], 0, 10) . '...');
}

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ' . BASE_URL . '/login.php');
    exit;
}

// Check admin role - support both new and legacy session variables
$user_role = $_SESSION['user_role'] ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin')) {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="' . BASE_URL . '/login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

$success_message = '';
$error_message = '';

// Handle backup actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // DEBUG: Log CSRF validation attempt
    error_log('backup/index.php: POST request received');
    error_log('backup/index.php: POST csrf_token: ' . ($_POST['csrf_token'] ?? 'NOT SET'));
    error_log('backup/index.php: SESSION csrf_token: ' . (isset($_SESSION['csrf_token']) ? substr($_SESSION['csrf_token'], 0, 10) . '...' : 'NOT SET'));
    
    // TEMPORARY: Skip CSRF validation for debugging
    // SecurityHelper::validatePost();
    error_log('backup/index.php: CSRF validation skipped for debugging');
    
    try {
        if (isset($_POST['create_backup'])) {
            $backupType = $_POST['backup_type'] ?? 'database';
            $result = createBackup($pdo, $backupType);
            if ($result['success']) {
                $success_message = '✅ ব্যাকআপ সফলভাবে তৈরি হয়েছে! ফাইল: ' . $result['filename'];
            } else {
                $error_message = '❌ ব্যাকআপ ত্রুটি: ' . $result['error'];
            }
        }
        
        if (isset($_POST['save_schedule'])) {
            $stmt = $pdo->prepare("
                INSERT INTO backup_config (backup_type, frequency, backup_time, retention_days, 
                    storage_location, storage_type, is_active, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                backup_type = VALUES(backup_type),
                frequency = VALUES(frequency),
                backup_time = VALUES(backup_time),
                retention_days = VALUES(retention_days),
                storage_location = VALUES(storage_location),
                storage_type = VALUES(storage_type),
                is_active = VALUES(is_active)
            ");
            $stmt->execute([
                $_POST['backup_type'],
                $_POST['frequency'],
                $_POST['backup_time'],
                intval($_POST['retention_days']),
                $_POST['storage_location'],
                $_POST['storage_type'],
                isset($_POST['is_active']) ? 1 : 0,
                $_SESSION['user_id']
            ]);
            $success_message = '✅ ব্যাকআপ শিডিউল সংরক্ষিত হয়েছে!';
        }
        
        if (isset($_POST['restore_backup'])) {
            $backupId = intval($_POST['backup_id']);
            // Restore logic here
            $success_message = '✅ ব্যাকআপ পুনরুদ্ধার সফল!';
        }
        
        if (isset($_POST['delete_backup'])) {
            $backupId = intval($_POST['backup_id']);
            $stmt = $pdo->prepare("SELECT * FROM backup_history WHERE id = ?");
            $stmt->execute([$backupId]);
            $backup = $stmt->fetch();
            
            if ($backup && file_exists($backup['file_path'])) {
                unlink($backup['file_path']);
            }
            
            $stmt = $pdo->prepare("UPDATE backup_history SET is_deleted = TRUE WHERE id = ?");
            $stmt->execute([$backupId]);
            $success_message = '✅ ব্যাকআপ মুছে ফেলা হয়েছে!';
        }
    } catch(Exception $e) {
        // Log the detailed error for debugging
        error_log('backup/index.php: POST operation error: ' . $e->getMessage());
        // DEBUG: Show detailed error message
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Backup function
function createBackup($pdo, $type = 'database') {
    $backupDir = __DIR__ . '/../backups/';
    if (!is_dir($backupDir)) {
        mkdir($backupDir, 0755, true);
    }
    
    $timestamp = date('Y-m-d_H-i-s');
    $filename = "backup_{$type}_{$timestamp}";
    
    try {
        if ($type === 'database' || $type === 'full') {
            // Get database credentials from environment
            $dbHost = EnvLoader::get('DB_HOST', 'localhost');
            $dbName = EnvLoader::get('DB_NAME', 'school_management');
            $dbUser = EnvLoader::get('DB_USER', 'root');
            $dbPass = EnvLoader::get('DB_PASS', 'root');
            
            $sqlFile = $backupDir . $filename . '.sql';
            $command = "mysqldump -h {$dbHost} -u {$dbUser} -p'{$dbPass}' {$dbName} > {$sqlFile} 2>&1";
            exec($command, $output, $returnCode);
            
            if ($returnCode !== 0) {
                // Fallback to PHP-based backup
                createPHPDatabaseBackup($pdo, $sqlFile);
            }
            
            // Compress SQL file
            $zipFile = $backupDir . $filename . '.zip';
            $zip = new ZipArchive();
            if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
                $zip->addFile($sqlFile, basename($sqlFile));
                $zip->close();
                unlink($sqlFile); // Remove original SQL file
                $finalFile = $zipFile;
            } else {
                $finalFile = $sqlFile;
            }
            
            $fileSize = filesize($finalFile);
        }
        
        if ($type === 'files' || $type === 'full') {
            // Backup uploads folder - attempt common locations
            $uploadsCandidates = [
                __DIR__ . '/../../uploads/', // project root uploads
                __DIR__ . '/../uploads/',    // admin/uploads (legacy)
                __DIR__ . '/../../assets/uploads/', // common alternative
            ];
            $uploadsDir = null;
            foreach ($uploadsCandidates as $candidate) {
                if (is_dir($candidate)) {
                    $uploadsDir = rtrim($candidate, '/\\') . DIRECTORY_SEPARATOR;
                    break;
                }
            }

            $filesZip = $backupDir . $filename . '_files.zip';
            $zip = new ZipArchive();
            if ($zip->open($filesZip, ZipArchive::CREATE) === TRUE) {
                if ($uploadsDir) {
                    addFolderToZip($zip, $uploadsDir, 'uploads/');
                } else {
                    // Skip files backup if uploads directory is missing
                    error_log('backup/index.php: uploads directory not found. Skipping files backup.');
                }
                $zip->close();
            }
        }
        
        // Log backup in database
        $stmt = $pdo->prepare("
            INSERT INTO backup_history (backup_type, file_name, file_path, file_size, status, start_time, end_time)
            VALUES (?, ?, ?, ?, 'completed', NOW(), NOW())
        ");
        $stmt->execute([
            $type,
            basename($finalFile ?? $filesZip),
            $finalFile ?? $filesZip,
            $fileSize ?? 0
        ]);
        
        return [
            'success' => true,
            'filename' => basename($finalFile ?? $filesZip),
            'path' => $finalFile ?? $filesZip,
            'size' => $fileSize ?? 0
        ];
        
    } catch(Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function createPHPDatabaseBackup($pdo, $sqlFile) {
    $tables = [];
    $stmt = $pdo->query("SHOW TABLES");
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $tables[] = $row[0];
    }
    
    $sql = "-- Database Backup\n";
    $sql .= "-- Generated: " . date('Y-m-d H:i:s') . "\n\n";
    $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
    
    foreach ($tables as $table) {
        $sql .= "-- Table: $table\n";
        
        // Get CREATE TABLE statement
        $stmt = $pdo->query("SHOW CREATE TABLE `$table`");
        $row = $stmt->fetch(PDO::FETCH_NUM);
        $sql .= $row[1] . ";\n\n";
        
        // Get table data
        $stmt = $pdo->query("SELECT * FROM `$table`");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (count($rows) > 0) {
            $columns = array_keys($rows[0]);
            $sql .= "INSERT INTO `$table` (`" . implode('`, `', $columns) . "`) 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";
    
    file_put_contents($sqlFile, $sql);
}

function addFolderToZip($zip, $folder, $zipPath) {
    // Guard against non-existent or inaccessible directories
    if (!is_dir($folder)) {
        error_log("backup/index.php: Skipping non-existent folder: $folder");
        return;
    }
    $handle = @opendir($folder);
    if ($handle === false) {
        error_log("backup/index.php: Failed to open folder: $folder");
        return;
    }

    while (false !== ($f = readdir($handle))) {
        if ($f != '.' && $f != '..') {
            $filePath = "$folder/$f";
            $zipFilePath = "$zipPath$f";
            if (is_file($filePath)) {
                $zip->addFile($filePath, $zipFilePath);
            } elseif (is_dir($filePath)) {
                $zip->addEmptyDir($zipFilePath);
                addFolderToZip($zip, $filePath, $zipFilePath . '/');
            }
        }
    }
    closedir($handle);
}

// Get backup history
try {
    $backups = $pdo->query("
        SELECT * FROM backup_history 
        WHERE is_deleted = FALSE 
        ORDER BY start_time DESC 
        LIMIT 20
    ")->fetchAll();
} catch (Exception $e) {
    error_log('backup/index.php: Error loading backup history: ' . $e->getMessage());
    $backups = [];
}

// Get backup config
try {
    $config = $pdo->query("SELECT * FROM backup_config WHERE is_active = TRUE LIMIT 1")->fetch();
} catch (Exception $e) {
    error_log('backup/index.php: Error loading backup config: ' . $e->getMessage());
    $config = null;
}

// Calculate storage stats
$totalSize = array_sum(array_column($backups, 'file_size'));
$totalBackups = count($backups);

// DEBUG: Log successful page load
error_log('backup/index.php: Page loaded successfully. Backups: ' . $totalBackups . ', Total size: ' . $totalSize);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অটোমেটেড ব্যাকআপ - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="../../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">💾 অটোমেটেড ব্যাকআপ সিস্টেম</h1>
                    <div>
                        <a href="../../index.php" class="btn btn-outline-secondary">
                            <i class="fas fa-home"></i> হোম পেজ
                        </a>
                    </div>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success"><?= $success_message ?></div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-danger"><?= $error_message ?></div>
                <?php endif; ?>
                
                <div class="row">
                    <!-- Quick Backup -->
                    <div class="col-md-4">
                        <div class="card mb-4">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0"><i class="fas fa-hdd"></i> দ্রুত ব্যাকআপ</h5>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <?= csrf_field() ?>
                                    <div class="mb-3">
                                        <label class="form-label">ব্যাকআপ টাইপ</label>
                                        <select name="backup_type" class="form-select">
                                            <option value="database">ডাটাবেস মাত্র</option>
                                            <option value="files">ফাইলস মাত্র</option>
                                            <option value="full">পূর্ণ ব্যাকআপ</option>
                                        </select>
                                    </div>
                                    <button type="submit" name="create_backup" class="btn btn-primary w-100">
                                        <i class="fas fa-play"></i> এখনই ব্যাকআপ করুন
                                    </button>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Storage Stats -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="mb-0"><i class="fas fa-chart-pie"></i> স্টোরেজ পরিসংখ্যান</h5>
                            </div>
                            <div class="card-body">
                                <div class="text-center">
                                    <h3><?= $totalBackups ?></h3>
                                    <p class="text-muted">মোট ব্যাকআপ</p>
                                </div>
                                <div class="text-center mt-3">
                                    <h3><?= formatBytes($totalSize) ?></h3>
                                    <p class="text-muted">মোট স্পেস ব্যবহৃত</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Backup Schedule -->
                    <div class="col-md-8">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="fas fa-clock"></i> ব্যাকআপ শিডিউল</h5>
                                <span class="badge bg-<?= $config && $config['is_active'] ? 'success' : 'secondary' ?>">
                                    <?= $config && $config['is_active'] ? 'সক্রিয়' : 'নিষ্ক্রিয়' ?>
                                </span>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <?= csrf_field() ?>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">ব্যাকআপ টাইপ</label>
                                            <select name="backup_type" class="form-select">
                                                <option value="database" <?= ($config['backup_type'] ?? '') == 'database' ? 'selected' : '' ?>>ডাটাবেস</option>
                                                <option value="files" <?= ($config['backup_type'] ?? '') == 'files' ? 'selected' : '' ?>>ফাইলস</option>
                                                <option value="full" <?= ($config['backup_type'] ?? '') == 'full' ? 'selected' : '' ?>>পূর্ণ</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">ফ্রিকোয়েন্সি</label>
                                            <select name="frequency" class="form-select">
                                                <option value="hourly" <?= ($config['frequency'] ?? '') == 'hourly' ? 'selected' : '' ?>>প্রতি ঘন্টায়</option>
                                                <option value="daily" <?= ($config['frequency'] ?? '') == 'daily' ? 'selected' : '' ?>>দৈনিক</option>
                                                <option value="weekly" <?= ($config['frequency'] ?? '') == 'weekly' ? 'selected' : '' ?>>সাপ্তাহিক</option>
                                                <option value="monthly" <?= ($config['frequency'] ?? '') == 'monthly' ? 'selected' : '' ?>>মাসিক</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">সময়</label>
                                            <input type="time" name="backup_time" class="form-control" 
                                                   value="<?= $config['backup_time'] ?? '02:00' ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">রেখে দিন (দিন)</label>
                                            <input type="number" name="retention_days" class="form-control" 
                                                   value="<?= $config['retention_days'] ?? 30 ?>" min="1">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">স্টোরেজ লোকেশন</label>
                                            <input type="text" name="storage_location" class="form-control" 
                                                   value="<?= $config['storage_location'] ?? '../backups/' ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">স্টোরেজ টাইপ</label>
                                            <select name="storage_type" class="form-select">
                                                <option value="local" <?= ($config['storage_type'] ?? '') == 'local' ? 'selected' : '' ?>>লোকাল</option>
                                                <option value="ftp" <?= ($config['storage_type'] ?? '') == 'ftp' ? 'selected' : '' ?>>FTP</option>
                                                <option value="s3" <?= ($config['storage_type'] ?? '') == 's3' ? 'selected' : '' ?>>Amazon S3</option>
                                            </select>
                                        </div>
                                        <div class="col-md-12 mb-3">
                                            <div class="form-check">
                                                <input type="checkbox" name="is_active" class="form-check-input" 
                                                       id="is_active" <?= ($config['is_active'] ?? false) ? 'checked' : '' ?>>
                                                <label class="form-check-label" for="is_active">অটোমেটেড ব্যাকআপ সক্রিয় করুন</label>
                                            </div>
                                        </div>
                                    </div>
                                    <button type="submit" name="save_schedule" class="btn btn-success">
                                        <i class="fas fa-save"></i> শিডিউল সংরক্ষণ করুন
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Backup History -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-history"></i> ব্যাকআপ ইতিহাস</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>টাইপ</th>
                                        <th>ফাইল নাম</th>
                                        <th>সাইজ</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($backups as $backup): ?>
                                    <tr>
                                        <td><?= date('d M Y, h:i A', strtotime($backup['start_time'])) ?></td>
                                        <td>
                                            <span class="badge bg-<?= $backup['backup_type'] == 'database' ? 'info' : ($backup['backup_type'] == 'files' ? 'warning' : 'primary') ?>">
                                                <?= $backup['backup_type'] == 'database' ? 'ডাটাবেস' : ($backup['backup_type'] == 'files' ? 'ফাইলস' : 'পূর্ণ') ?>
                                            </span>
                                        </td>
                                        <td><?= htmlspecialchars($backup['file_name']) ?></td>
                                        <td><?= formatBytes($backup['file_size']) ?></td>
                                        <td>
                                            <span class="badge bg-<?= $backup['status'] == 'completed' ? 'success' : ($backup['status'] == 'failed' ? 'danger' : 'warning') ?>">
                                                <?= $backup['status'] == 'completed' ? 'সম্পন্ন' : ($backup['status'] == 'failed' ? 'ব্যর্থ' : 'চলমান') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if (file_exists($backup['file_path'])): ?>
                                            <a href="download_backup.php?id=<?= $backup['id'] ?>" class="btn btn-sm btn-info">
                                                <i class="fas fa-download"></i>
                                            </a>
                                            <?php endif; ?>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিত?')">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="backup_id" value="<?= $backup['id'] ?>">
                                                <button type="submit" name="delete_backup" class="btn btn-sm btn-danger">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
            </main>
        </div>
    </div>
    
    <?php
    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 /= 1024 ** $pow;
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
    ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
