<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header('Location: login.php');
    exit();
}

include 'layouts/dbconn.php';
include 'includes/AuditLogger.php';

// Initialize the audit logger
$logger = new AuditLogger($conn, $_SESSION['user_id']);

// Backup directory
$backup_dir = 'backups/';

// Create backup function
function createBackup($conn, $backup_dir) {
    $tables = array();
    $result = $conn->query('SHOW TABLES');
    while ($row = $result->fetch_row()) {
        $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";

    // Add DROP TABLE and CREATE TABLE statements
    foreach ($tables as $table) {
        // Get create table statement
        $result = $conn->query("SHOW CREATE TABLE `$table`");
        $row = $result->fetch_row();
        
        $sql .= "DROP TABLE IF EXISTS `$table`;\n";
        $sql .= $row[1] . ";\n\n";
    }

    // Get table data
    foreach ($tables as $table) {
        $result = $conn->query("SELECT * FROM `$table`");
        
        if ($result->num_rows > 0) {
            $sql .= "INSERT INTO `$table` VALUES\n";
            $first_row = true;
            
            while ($row = $result->fetch_assoc()) {
                if (!$first_row) {
                    $sql .= ",\n";
                }
                
                $values = array();
                foreach ($row as $value) {
                    if ($value === null) {
                        $values[] = 'NULL';
                    } else {
                        $values[] = "'" . $conn->real_escape_string($value) . "'";
                    }
                }
                
                $sql .= "(" . implode(", ", $values) . ")";
                $first_row = false;
            }
            $sql .= ";\n";
        }
        
        $sql .= "\n";
    }

    $sql .= "\nSET FOREIGN_KEY_CHECKS=1;\n";

    // Generate filename with timestamp
    $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
    $filepath = $backup_dir . $filename;

    // Save backup file
    if (file_put_contents($filepath, $sql)) {
        return $filename;
    }
    return false;
}

// Initialize response array
$response = ['success' => false, 'message' => ''];

try {
    if (!isset($_POST['action'])) {
        throw new Exception("No action specified");
    }

    $action = $_POST['action'];
    
    switch ($action) {
        case 'create_backup':
            // Create backup directory if it doesn't exist
            if (!file_exists($backup_dir)) {
                mkdir($backup_dir, 0755, true);
            }
            
            $filename = createBackup($conn, $backup_dir);
            if ($filename) {
                $logger->logConfigChange(
                    'backup',
                    "Created manual backup: $filename"
                );
                $_SESSION['success'] = "Backup created successfully: $filename";
            } else {
                throw new Exception("Error creating backup");
            }
            break;
            
        case 'restore_backup':
            if (!isset($_POST['filename'])) {
                throw new Exception("No backup file specified");
            }
            
            $filename = basename($_POST['filename']); // Sanitize filename
            $backup_path = $backup_dir . $filename;
            
            if (!file_exists($backup_path)) {
                throw new Exception("Backup file not found");
            }
            
            // Begin transaction
            $conn->begin_transaction();
            
            try {
                $sql = file_get_contents($backup_path);
                if ($conn->multi_query($sql)) {
                    do {
                        if ($result = $conn->store_result()) {
                            $result->free();
                        }
                    } while ($conn->next_result());
                    
                    $conn->commit();
                    $logger->logConfigChange(
                        'restore',
                        "Restored database from backup: $filename"
                    );
                    $_SESSION['success'] = "Database restored successfully from: $filename";
                } else {
                    throw new Exception("Error executing backup file");
                }
            } catch (Exception $e) {
                $conn->rollback();
                throw $e;
            }
            break;
            
        case 'delete_backup':
            if (!isset($_POST['filename'])) {
                throw new Exception("No backup file specified");
            }
            
            $filename = basename($_POST['filename']); // Sanitize filename
            $backup_path = $backup_dir . $filename;
            
            if (!file_exists($backup_path)) {
                throw new Exception("Backup file not found");
            }
            
            if (unlink($backup_path)) {
                $logger->logConfigChange(
                    'backup_delete',
                    "Deleted backup file: $filename"
                );
                $_SESSION['success'] = "Backup deleted successfully";
            } else {
                throw new Exception("Error deleting backup file");
            }
            break;
            
        case 'update_schedule':
            $frequency = $_POST['frequency'] ?? 'daily';
            $retention_days = intval($_POST['retention_days'] ?? 30);
            $notify_email = filter_var($_POST['notify_email'] ?? '', FILTER_VALIDATE_EMAIL);
            
            // Save settings to database
            $sql = "INSERT INTO backup_settings (setting_key, setting_value) 
                   VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)";
            $stmt = $conn->prepare($sql);
            
            $settings = [
                'backup_frequency' => $frequency,
                'retention_days' => $retention_days,
                'notify_email' => $notify_email ?: ''
            ];
            
            foreach ($settings as $key => $value) {
                $stmt->bind_param("ss", $key, $value);
                $stmt->execute();
            }
            
            $logger->logConfigChange(
                'backup_settings',
                "Updated backup schedule settings",
                null,
                $settings
            );
            
            $_SESSION['success'] = "Schedule settings updated successfully";
            break;
            
        default:
            throw new Exception("Invalid action specified");
    }
} catch (Exception $e) {
    $_SESSION['error'] = $e->getMessage();
}

// Always redirect back to backup.php
header('Location: backup.php');
exit();
?>