<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/functions_backup.php';
require_once dirname(__DIR__) . '/includes/auth.php';
requirePermission('backup_create');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: backup_center.php');
    exit;
}
requireCsrfToken();

try {
    $note = trim((string)($_POST['note'] ?? ''));
    $backup = createJsonBackup('full_db', null, $note, true);
    writeAuditLog('backup_created', 'Backup created: ' . $backup['file_name'], 'success', 'info', 'backup', $backup['file_name']);
    logMaintenance('backup_created', 'Backup created: ' . $backup['file_name']);
    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'backup', 'Full database backup created', [
            'file_name' => $backup['file_name'],
            'file_size' => $backup['size'],
            'checksum' => $backup['checksum'],
        ]);
    }
    header('Location: backup_center.php?status=success&message=' . urlencode('전체 DB 백업을 생성했습니다.') . '&file=' . urlencode($backup['file_name']));
} catch (Throwable $e) {
    logMaintenance('backup_created', $e->getMessage(), 'failed');
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'backup', 'Full database backup failed', ['error' => $e->getMessage()]);
    }
    header('Location: backup_center.php?status=error&message=' . urlencode('백업 실패: ' . $e->getMessage()));
}
exit;
