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

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

$allowedKeys = [
    'theme_mode', 'accent_color', 'player_default_volume', 'player_resume_enabled', 'player_auto_next_enabled',
    'player_history_enabled', 'player_count_rule', 'player_default_repeat', 'player_default_shuffle',
    'player_mobile_compact', 'scan_path', 'scan_allowed_extensions', 'scan_auto_enabled',
    'scan_auto_interval_minutes', 'scan_refresh_metadata', 'scan_show_missing_files',
    'home_show_recent_added', 'home_show_recent_played', 'home_show_popular', 'home_show_liked',
    'home_show_stats', 'home_section_limit',
];

try {
    if (!isset($_FILES['settings_file']) || $_FILES['settings_file']['error'] !== UPLOAD_ERR_OK) throw new Exception('업로드된 설정 파일이 없습니다.');
    $data = json_decode(file_get_contents($_FILES['settings_file']['tmp_name']), true);
    $settingsRows = $data['settings'] ?? ($data['data']['settings'] ?? null);
    $validType = in_array(($data['type'] ?? $data['export_type'] ?? ''), ['melonlite_settings', 'settings', 'selective_export'], true);
    if (!is_array($data) || !$validType || !is_array($settingsRows)) {
        throw new Exception('설정 JSON 구조가 올바르지 않습니다.');
    }
    $imported = 0;
    foreach ($settingsRows as $row) {
        $key = (string)($row['setting_key'] ?? '');
        if (!backupSettingRowIsExportable($row)) continue;
        if (!in_array($key, $allowedKeys, true)) continue;
        setSetting($key, (string)($row['setting_value'] ?? ''), (string)($row['setting_group'] ?? 'general'));
        $imported++;
    }
    logMaintenance('settings_imported', $imported . '개 설정을 가져왔습니다.');
    header('Location: ../settings.php?status=success&message=' . urlencode($imported . '개 설정을 가져왔습니다.'));
} catch (Exception $e) {
    logMaintenance('settings_imported', $e->getMessage(), 'failed');
    header('Location: ../settings.php?status=error&message=' . urlencode('설정 가져오기 실패: ' . $e->getMessage()));
}
exit;
