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

$status = $_GET['status'] ?? '';
$message = $_GET['message'] ?? '';
$preview = null;
$storedFile = '';
$applyResult = null;
$adminJobId = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireCsrfToken();
    $action = (string)($_POST['action'] ?? 'preview');
    try {
        $jobStart = startAdminJob('import', $action === 'apply' ? '가져오기 적용' : '가져오기 미리보기', 'import:' . $action, ['action' => $action], $action === 'apply');
        if (empty($jobStart['ok']) && !empty($jobStart['duplicate'])) {
            throw new RuntimeException('이미 가져오기 작업이 진행 중입니다. 작업 큐에서 진행 상태를 확인하세요.');
        }
        $adminJobId = (int)($jobStart['id'] ?? 0);
        if ($action === 'apply') {
            $storedFile = backupSafeFilename($_POST['stored_file'] ?? '');
            if ($storedFile === '') throw new RuntimeException('가져오기 파일이 올바르지 않습니다.');
            if (trim((string)($_POST['confirm_phrase'] ?? '')) !== '가져옵니다') throw new RuntimeException('확인 문구가 일치하지 않습니다.');
            $sections = (array)($_POST['import_tables'] ?? []);
            $conflictMode = ($_POST['conflict_mode'] ?? 'skip') === 'update' ? 'update' : 'skip';
            $applyResult = applySelectiveImport($storedFile, $sections, $conflictMode);
            writeAuditLog('import_completed', 'Import completed: ' . $storedFile, 'success', 'warning', 'import', $storedFile);
            logMaintenance('import_completed', 'Import completed: ' . $storedFile);
            if (function_exists('writeAppLog')) writeAppLog('info', 'import', 'Selective import completed', ['file_name' => $storedFile, 'result' => $applyResult]);
            finishAdminJob($adminJobId, 'completed', [
                'processed_count' => (int)($applyResult['added'] ?? 0) + (int)($applyResult['changed'] ?? 0) + (int)($applyResult['conflict'] ?? 0) + (int)($applyResult['skipped'] ?? 0),
                'failed_count' => 0,
                'summary_message' => '가져오기 적용이 완료되었습니다.',
                'context' => [
                    'file_name' => $storedFile,
                    'result' => $applyResult,
                ],
            ]);
            $status = 'success';
            $message = '가져오기를 완료했습니다.';
        } else {
            [$storedFile, $data] = backupSaveUploadedImport('import_file');
            $preview = backupPreviewImport($data);
            writeAuditLog('import_preview', 'Import preview: ' . $storedFile, 'success', 'info', 'import', $storedFile);
            logMaintenance('import_preview', 'Import preview: ' . $storedFile);
            if (function_exists('writeAppLog')) writeAppLog('info', 'import', 'Import preview generated', ['file_name' => $storedFile, 'counts' => $preview['counts'] ?? []]);
            finishAdminJob($adminJobId, 'completed', [
                'processed_count' => array_sum(array_map('intval', $preview['counts'] ?? [])),
                'failed_count' => !empty($preview['errors']) ? count($preview['errors']) : 0,
                'summary_message' => '가져오기 미리보기가 완료되었습니다.',
                'context' => [
                    'file_name' => $storedFile,
                    'valid' => !empty($preview['valid']),
                    'counts' => $preview['counts'] ?? [],
                ],
            ]);
        }
    } catch (Throwable $e) {
        $status = 'error';
        $message = maskInternalPathText($e->getMessage());
        finishAdminJob($adminJobId, 'failed', [
            'processed_count' => 0,
            'failed_count' => 1,
            'summary_message' => '가져오기 작업이 실패했습니다.',
            'error_type' => 'import_error',
            'context' => ['action' => $action, 'message' => $message],
        ]);
        if (function_exists('writeAppLog')) writeAppLog('error', 'import', 'Import failed', ['error' => $message]);
    }
}

$importTables = backupImportAllowedSections();

renderHeader('가져오기 미리보기', 'backup');
?>
<div class="settings-page backup-center-page">
    <div class="page-title-section">
        <h1 class="page-main-title">가져오기 / 검증</h1>
        <p class="page-subtitle">MelonLite에서 내보낸 JSON을 검증하고, 안전한 항목만 선택 병합합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="notice <?php echo $status === 'error' ? 'notice-danger' : 'notice-success'; ?>">
            <?php echo h($message); ?>
        </div>
    <?php endif; ?>

    <?php if ($applyResult): ?>
        <div class="backup-summary-grid">
            <div class="backup-summary-card"><strong><?php echo number_format($applyResult['added']); ?></strong><span>추가</span></div>
            <div class="backup-summary-card"><strong><?php echo number_format($applyResult['changed']); ?></strong><span>변경</span></div>
            <div class="backup-summary-card"><strong><?php echo number_format($applyResult['conflict']); ?></strong><span>충돌/건너뜀</span></div>
            <div class="backup-summary-card"><strong><?php echo number_format($applyResult['skipped']); ?></strong><span>제외</span></div>
        </div>
    <?php endif; ?>

    <?php if ($preview): ?>
        <div class="settings-card danger-zone">
            <div class="settings-card-header">
                <h2>미리보기 결과</h2>
                <span class="status-badge <?php echo $preview['valid'] ? 'ok' : 'danger'; ?>"><?php echo $preview['valid'] ? '검증 통과' : '검증 실패'; ?></span>
            </div>
            <?php if (!empty($preview['errors'])): ?>
                <ul class="backup-message-list"><?php foreach ($preview['errors'] as $error): ?><li><?php echo h($error); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
            <?php if (!empty($preview['warnings'])): ?>
                <ul class="backup-message-list muted"><?php foreach ($preview['warnings'] as $warning): ?><li><?php echo h($warning); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
            <div class="backup-summary-grid">
                <div class="backup-summary-card"><strong><?php echo number_format($preview['additions']); ?></strong><span>추가 예상</span></div>
                <div class="backup-summary-card"><strong><?php echo number_format($preview['changes']); ?></strong><span>변경 예상</span></div>
                <div class="backup-summary-card"><strong><?php echo number_format($preview['conflicts']); ?></strong><span>충돌 예상</span></div>
                <div class="backup-summary-card"><strong><?php echo number_format($preview['skipped']); ?></strong><span>건너뜀 예상</span></div>
            </div>

            <div class="backup-table-wrap">
                <table class="backup-table">
                    <thead><tr><th>섹션</th><th>항목 수</th></tr></thead>
                    <tbody>
                    <?php foreach (($preview['counts'] ?? []) as $table => $count): ?>
                        <tr><td><?php echo h($table); ?></td><td><?php echo number_format((int)$count); ?></td></tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($preview['valid']): ?>
                <form action="import.php" method="POST" class="backup-form" onsubmit="return confirm('선택한 항목을 현재 DB에 병합할까요? 기존 데이터와 충돌할 수 있습니다.');">
                    <?php echo csrfInput(); ?>
                    <input type="hidden" name="action" value="apply">
                    <input type="hidden" name="stored_file" value="<?php echo h($storedFile); ?>">
                    <div class="form-grid">
                        <?php foreach ($importTables as $table): ?>
                            <label class="check-card">
                                <input type="checkbox" name="import_tables[]" value="<?php echo h($table); ?>" <?php echo isset(($preview['counts'] ?? [])[$table]) ? 'checked' : ''; ?>>
                                <span><?php echo h($table); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    <label class="form-label">충돌 처리</label>
                    <select name="conflict_mode" class="form-control">
                        <option value="skip">기존 데이터 보호하고 건너뛰기</option>
                        <option value="update">가져온 값으로 갱신</option>
                    </select>
                    <label class="form-label">확인 문구</label>
                    <input type="text" name="confirm_phrase" class="form-control" placeholder="가져옵니다" required>
                    <button type="submit" class="btn btn-danger">선택 데이터 병합 실행</button>
                </form>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="settings-card">
            <div class="settings-card-header"><h2>JSON 가져오기</h2></div>
            <form action="import.php" method="POST" enctype="multipart/form-data" class="backup-form">
                <?php echo csrfInput(); ?>
                <input type="hidden" name="action" value="preview">
                <label class="form-label" for="import_file">MelonLite JSON 파일</label>
                <input type="file" id="import_file" name="import_file" class="form-control" accept="application/json,.json" required>
                <p class="settings-muted">먼저 구조와 체크섬을 검증하고 추가/변경/충돌/건너뜀 개수를 미리 보여줍니다.</p>
                <button type="submit" class="btn btn-primary">가져오기 미리보기</button>
            </form>
        </div>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
