<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';
requirePermission('settings_manage');

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

$groups = [
    'general' => ['home_show_stats', 'home_show_recent_added', 'home_show_recent_played', 'home_show_popular', 'home_show_liked', 'home_show_recommendations', 'home_show_auto_playlists', 'home_section_limit', 'recommendation_limit'],
    'access' => ['public_music_pages_enabled', 'require_login_for_all_pages', 'show_admin_menu_only_when_logged_in'],
    'theme' => ['theme_mode', 'accent_color'],
    'player' => ['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' => ['scan_path', 'scan_allowed_extensions', 'scan_auto_enabled', 'scan_auto_interval_minutes', 'scan_refresh_metadata', 'scan_force_metadata', 'scan_show_missing_files'],
    'pwa' => ['pwa_app_name', 'pwa_enabled', 'pwa_show_install_guide', 'list_default_limit', 'album_art_lazy_loading', 'media_session_enabled', 'keyboard_shortcuts_enabled', 'pwa_audio_cache_enabled'],
    'sidebar' => ['sidebar_show_recommend', 'sidebar_show_auto_playlists', 'sidebar_show_admin', 'sidebar_show_settings_detail', 'sidebar_groups_default_open', 'sidebar_mobile_auto_close', 'sidebar_compact_mode'],
];
$checkboxes = ['home_show_stats', 'home_show_recent_added', 'home_show_recent_played', 'home_show_popular', 'home_show_liked', 'home_show_recommendations', 'home_show_auto_playlists', 'public_music_pages_enabled', 'require_login_for_all_pages', 'show_admin_menu_only_when_logged_in', 'player_resume_enabled', 'player_auto_next_enabled', 'player_history_enabled', 'player_default_shuffle', 'player_mobile_compact', 'scan_auto_enabled', 'scan_refresh_metadata', 'scan_force_metadata', 'scan_show_missing_files', 'pwa_enabled', 'pwa_show_install_guide', 'album_art_lazy_loading', 'media_session_enabled', 'keyboard_shortcuts_enabled', 'pwa_audio_cache_enabled', 'sidebar_show_recommend', 'sidebar_show_auto_playlists', 'sidebar_show_admin', 'sidebar_show_settings_detail', 'sidebar_groups_default_open', 'sidebar_mobile_auto_close', 'sidebar_compact_mode'];

try {
    foreach ($groups as $group => $keys) {
        foreach ($keys as $key) {
            if (in_array($key, $checkboxes, true)) {
                $value = isset($_POST[$key]) ? '1' : '0';
            } else {
                $value = trim((string)($_POST[$key] ?? ''));
            }
            if ($key === 'theme_mode' && !in_array($value, ['system', 'light', 'dark', 'melon', 'black'], true)) $value = 'melon';
            if ($key === 'accent_color' && !preg_match('/^#[0-9a-fA-F]{6}$/', $value)) $value = '#00CD3C';
            if ($key === 'player_default_volume') $value = (string)max(0, min(100, (int)$value));
            if ($key === 'home_section_limit') $value = (string)max(3, min(20, (int)$value));
            if ($key === 'recommendation_limit') $value = (string)max(3, min(50, (int)$value));
            if ($key === 'list_default_limit') $value = (string)max(10, min(200, (int)$value));
            if ($key === 'pwa_app_name' && $value === '') $value = '개인 음악실';
            if ($key === 'scan_auto_interval_minutes') $value = (string)max(1, min(1440, (int)$value));
            if ($key === 'scan_path' && $value === '') $value = MUSIC_SCAN_PATH;
            if ($key === 'scan_allowed_extensions' && $value === '') $value = implode(',', ALLOWED_AUDIO_EXTENSIONS);
            setSetting($key, $value, $group);
        }
    }
    logMaintenance('settings_updated', '설정이 저장되었습니다.');
    writeAuditLog('settings_updated', 'Settings updated', 'success', 'info', 'settings');
    header('Location: settings.php?status=success&message=' . urlencode('설정이 저장되었습니다.'));
} catch (Exception $e) {
    logMaintenance('settings_updated', $e->getMessage(), 'failed');
    writeAuditLog('settings_update_failed', 'Settings update failed: ' . $e->getMessage(), 'failed', 'error', 'settings');
    header('Location: settings.php?status=error&message=' . urlencode('설정 저장 실패: ' . $e->getMessage()));
}
exit;
