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

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

try {
    $sections = array_values(array_intersect((array)($_POST['sections'] ?? []), array_keys(backupExportSections())));
    if (empty($sections)) throw new RuntimeException('내보낼 데이터를 하나 이상 선택하세요.');
    $note = trim((string)($_POST['note'] ?? ''));
    $export = createJsonBackup('selective_export', $sections, $note, false);
    writeAuditLog('export_created', 'Export created: ' . $export['file_name'], 'success', 'info', 'export', $export['file_name']);
    logMaintenance('export_created', 'Export created: ' . $export['file_name']);
    if (function_exists('writeAppLog')) {
        writeAppLog('info', 'export', 'Selective JSON export created', [
            'file_name' => $export['file_name'],
            'sections' => $sections,
            'file_size' => $export['size'],
        ]);
    }
    header('Location: backup_download.php?file=' . urlencode($export['file_name']));
} catch (Throwable $e) {
    logMaintenance('export_failed', $e->getMessage(), 'failed');
    if (function_exists('writeAppLog')) writeAppLog('error', 'export', 'Selective export failed', ['error' => $e->getMessage()]);
    header('Location: backup_center.php?status=error&message=' . urlencode('내보내기 실패: ' . $e->getMessage()));
}
exit;
