<?php
// automated_backup.php - Run this via cron job
require_once 'includes/config.php';
require_once 'layouts/dbconn.php';
require_once 'includes/AuditLogger.php';

class AutomatedBackup {
    private $conn;
    private $logger;
    private $backup_dir;
    private $retention_days;
    private $notify_email;
    
    public function __construct($conn, $backup_dir, $retention_days = 30, $notify_email = '') {
        $this->conn = $conn;
        $this->logger = new AuditLogger($conn, 0); // 0 for system actions
        $this->backup_dir = $backup_dir;
        $this->retention_days = $retention_days;
        $this->notify_email = $notify_email;
        
        if (!file_exists($this->backup_dir)) {
            mkdir($this->backup_dir, 0755, true);
        }
    }
    
    public function run() {
        try {
            // Create backup
            $filename = $this->createBackup();
            
            // Clean old backups
            $this->cleanOldBackups();
            
            // Send notification
            if ($filename) {
                $this->sendNotification('Backup Success', "Automated backup created successfully: $filename");
                $this->logger->logConfigChange('automated_backup', "Created automated backup: $filename");
            }
            
            return true;
        } catch (Exception $e) {
            $this->sendNotification('Backup Failed', $e->getMessage(), true);
            $this->logger->logConfigChange('automated_backup_failed', $e->getMessage());
            return false;
        }
    }
    
    private function createBackup() {
        $tables = array();
        $result = $this->conn->query('SHOW TABLES');
        while ($row = $result->fetch_row()) {
            $tables[] = $row[0];
        }

        $sql = "-- Automated Database Backup\n";
        $sql .= "-- Generated: " . date('Y-m-d H:i:s') . "\n\n";

        foreach ($tables as $table) {
            $sql .= "DROP TABLE IF EXISTS `$table`;\n";
            
            $result = $this->conn->query("SHOW CREATE TABLE `$table`");
            $row = $result->fetch_row();
            $sql .= $row[1] . ";\n\n";

            $result = $this->conn->query("SELECT * FROM `$table`");
            if ($result->num_rows > 0) {
                $sql .= "INSERT INTO `$table` VALUES\n";
                $first_row = true;
                
                while ($row = $result->fetch_assoc()) {
                    $sql .= (!$first_row ? ",\n" : "") . "(";
                    $values = array_map(function($value) {
                        return $value === null ? 'NULL' : "'" . $this->conn->real_escape_string($value) . "'";
                    }, $row);
                    $sql .= implode(", ", $values) . ")";
                    $first_row = false;
                }
                $sql .= ";\n";
            }
            $sql .= "\n";
        }

        $filename = 'automated_backup_' . date('Y-m-d_H-i-s') . '.sql';
        $filepath = $this->backup_dir . $filename;

        if (file_put_contents($filepath, $sql)) {
            return $filename;
        }
        throw new Exception("Failed to write backup file");
    }
    
    private function cleanOldBackups() {
        $cutoff = time() - ($this->retention_days * 86400);
        
        foreach (glob($this->backup_dir . "automated_backup_*.sql") as $file) {
            if (filemtime($file) < $cutoff) {
                unlink($file);
                $this->logger->logConfigChange(
                    'backup_cleanup',
                    "Deleted old backup: " . basename($file)
                );
            }
        }
    }
    
    private function sendNotification($subject, $message, $is_error = false) {
        if (!$this->notify_email) return;
        
        $headers = "From: System Backup <noreply@" . $_SERVER['SERVER_NAME'] . ">\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        
        $html_message = "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; }
                .error { color: #dc3545; }
                .success { color: #198754; }
            </style>
        </head>
        <body>
            <h2 class='" . ($is_error ? 'error' : 'success') . "'>" . htmlspecialchars($subject) . "</h2>
            <p>" . nl2br(htmlspecialchars($message)) . "</p>
            <p>Time: " . date('Y-m-d H:i:s') . "</p>
        </body>
        </html>";
        
        mail($this->notify_email, "Backup System: $subject", $html_message, $headers);
    }
}

// Run automated backup
$backup = new AutomatedBackup(
    $conn, 
    'backups/',
    30, // Keep backups for 30 days
    'admin@example.com' // Change this to your email
);
$backup->run();
?>