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

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

$adminJobId = null;
try {
    $sections = array_values(array_intersect((array)($_POST['sections'] ?? []), array_keys(backupExportSections())));
    if (empty($sections)) throw new RuntimeException('내보낼 데이터를 하나 이상 선택하세요.');
    $jobStart = startAdminJob('export', '선택 데이터 내보내기', 'export:selective', ['sections' => $sections], 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'] ?? ''));
    $export = createJsonBackup('selective_export', $sections, $note, false);
    finishAdminJob($adminJobId, 'completed', [
        'processed_count' => count($sections),
        'summary_message' => '선택 데이터 내보내기가 완료되었습니다.',
        'context' => [
            'sections' => $sections,
            'file_name' => $export['file_name'] ?? '',
            'file_size' => $export['size'] ?? 0,
        ],
    ]);
    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) {
    $safeMessage = maskInternalPathText($e->getMessage());
    finishAdminJob($adminJobId, 'failed', [
        'processed_count' => 0,
        'failed_count' => 1,
        'summary_message' => '내보내기 작업이 실패했습니다.',
        'error_type' => 'export_error',
        'context' => ['message' => $safeMessage],
    ]);
    logMaintenance('export_failed', $safeMessage, 'failed');
    if (function_exists('writeAppLog')) writeAppLog('error', 'export', 'Selective export failed', ['error' => $safeMessage]);
    header('Location: backup_center.php?status=error&message=' . urlencode('내보내기 실패: ' . $safeMessage));
}
exit;
