<?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';
require_once dirname(__DIR__) . '/includes/admin_jobs.php';
requirePermission('backup_create');

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

$adminJobId = null;
try {
    $jobStart = startAdminJob('backup', '전체 DB 백업', 'backup:full_db', [], true);
    if (empty($jobStart['ok']) && !empty($jobStart['duplicate'])) {
        header('Location: backup_center.php?status=error&message=' . urlencode('이미 백업 작업이 진행 중입니다. 작업 큐에서 진행 상태를 확인하세요.'));
        exit;
    }
    $adminJobId = (int)($jobStart['id'] ?? 0);
    $note = trim((string)($_POST['note'] ?? ''));
    $backup = createJsonBackup('full_db', null, $note, true);
    finishAdminJob($adminJobId, 'completed', [
        'processed_count' => 1,
        'summary_message' => '전체 DB 백업이 완료되었습니다.',
        'context' => [
            'file_name' => $backup['file_name'] ?? '',
            'file_size' => $backup['size'] ?? 0,
        ],
    ]);
    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) {
    $safeMessage = maskInternalPathText($e->getMessage());
    finishAdminJob($adminJobId, 'failed', [
        'processed_count' => 0,
        'failed_count' => 1,
        'summary_message' => '백업 작업이 실패했습니다.',
        'error_type' => 'backup_error',
        'context' => ['message' => $safeMessage],
    ]);
    logMaintenance('backup_created', $safeMessage, 'failed');
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'backup', 'Full database backup failed', ['error' => $safeMessage]);
    }
    header('Location: backup_center.php?status=error&message=' . urlencode('백업 실패: ' . $safeMessage));
}
exit;
