<?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_delete');

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

try {
    $file = backupSafeFilename($_POST['backup_file'] ?? '');
    if ($file === '') throw new RuntimeException('잘못된 백업 파일명입니다.');
    if (trim((string)($_POST['confirm_phrase'] ?? '')) !== '삭제합니다') throw new RuntimeException('확인 문구가 일치하지 않습니다.');
    $deleted = deleteBackupFile($file);
    writeAuditLog('backup_deleted', 'Backup deleted: ' . $deleted, 'success', 'warning', 'backup', $deleted);
    logMaintenance('backup_deleted', 'Backup file deleted: ' . $deleted);
    if (function_exists('writeAppLog')) writeAppLog('warning', 'backup', 'Backup file deleted', ['file_name' => $deleted]);
    header('Location: backup_center.php?status=success&message=' . urlencode('백업 파일을 삭제했습니다.'));
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'backup', 'Backup delete failed', ['error' => $e->getMessage()]);
    header('Location: backup_center.php?status=error&message=' . urlencode('삭제 실패: ' . $e->getMessage()));
}
exit;
