<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit();
}

// Check if user is admin
if (!checkPermission('admin', $_SESSION['role'])) {
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit();
}

$db = new Database();
$conn = $db->getConnection();

try {
    // Create backup directory if it doesn't exist
    $backup_dir = '../backups/';
    if (!is_dir($backup_dir)) {
        mkdir($backup_dir, 0755, true);
    }
    
    // Generate backup filename
    $backup_name = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
    $backup_path = $backup_dir . $backup_name;
    
    // Get database configuration - already loaded via require_once at top
    $backup_content = "-- Database Backup Created on " . date('Y-m-d H:i:s') . "\n";
    $backup_content .= "-- Generated by Antibiotic Management System\n\n";
    
    // Get all tables
    $tables = [];
    $result = $conn->query("SHOW TABLES");
    while ($row = $result->fetch(PDO::FETCH_NUM)) {
        $tables[] = $row[0];
    }
    
    // Export each table
    foreach ($tables as $table) {
        $backup_content .= "\n-- Table: $table\n";
        $backup_content .= "DROP TABLE IF EXISTS `$table`;\n";
        
        // Get CREATE TABLE statement
        $result = $conn->query("SHOW CREATE TABLE `$table`");
        $row = $result->fetch(PDO::FETCH_ASSOC);
        $backup_content .= $row['Create Table'] . ";\n\n";
        
        // Get table data
        $result = $conn->query("SELECT * FROM `$table`");
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $columns = array_keys($row);
            $values = array_values($row);
            
            // Escape values
            $escaped_values = array_map(function($value) use ($conn) {
                return $value === null ? 'NULL' : $conn->quote($value);
            }, $values);
            
            $backup_content .= "INSERT INTO `$table` (`" . implode('`, `', $columns) . "`) VALUES (" . implode(', ', $escaped_values) . ");\n";
        }
        $backup_content .= "\n";
    }
    
    // Write backup file
    if (file_put_contents($backup_path, $backup_content)) {
        $backup_size = filesize($backup_path);
        
        // Record backup in database
        $stmt = $conn->prepare("
            INSERT INTO system_backups (backup_name, backup_path, backup_size, backup_type, created_by) 
            VALUES (?, ?, ?, 'manual', ?)
        ");
        $stmt->execute([$backup_name, $backup_path, $backup_size, $_SESSION['user_id']]);
        
        // Log activity
        logActivity($conn, $_SESSION['user_id'], 'إنشاء نسخة احتياطية', 'system_backups', $conn->lastInsertId());
        
        // Create notification
        createNotification($conn, $_SESSION['user_id'], 'نسخة احتياطية جديدة', 'تم إنشاء نسخة احتياطية بنجاح: ' . $backup_name, 'success');
        
        echo json_encode([
            'success' => true,
            'message' => 'تم إنشاء النسخة الاحتياطية بنجاح',
            'backup_name' => $backup_name,
            'backup_size' => formatFileSize($backup_size)
        ]);
    } else {
        throw new Exception('فشل في كتابة ملف النسخة الاحتياطية');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
