<?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/auth.php';
requirePermission('maintenance_run');

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

$action = (string)($_POST['action'] ?? '');

try {
    $pdo = getDBConnection();
    if ($action === 'refresh_missing_files') {
        $stmt = $pdo->query("SELECT id, file_path FROM songs");
        $update = $pdo->prepare("UPDATE songs SET is_missing = :is_missing, missing_checked_at = NOW() WHERE id = :id");
        $changed = 0;
        foreach ($stmt->fetchAll() as $song) {
            $missing = !file_exists(toWinPath($song['file_path'])) ? 1 : 0;
            $update->execute([':is_missing' => $missing, ':id' => $song['id']]);
            $changed++;
        }
        $message = '파일 없음 표시를 갱신했습니다. 확인 곡 수: ' . $changed;
    } elseif ($action === 'cleanup_scan_logs') {
        $stmt = $pdo->prepare("DELETE FROM scan_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY)");
        $stmt->execute();
        $message = '오래된 스캔 로그 삭제: ' . $stmt->rowCount() . '건';
    } elseif ($action === 'cleanup_app_logs') {
        $stmt = $pdo->prepare("DELETE FROM app_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY)");
        $stmt->execute();
        $message = '오래된 앱 로그 정리: ' . $stmt->rowCount() . '건';
    } elseif ($action === 'cleanup_admin_logs') {
        $stmt = $pdo->prepare("DELETE FROM admin_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 180 DAY)");
        $stmt->execute();
        $message = '오래된 관리자 로그 정리: ' . $stmt->rowCount() . '건';
    } elseif ($action === 'cleanup_play_history') {
        $stmt = $pdo->prepare("DELETE FROM play_history WHERE played_at < DATE_SUB(NOW(), INTERVAL 180 DAY)");
        $stmt->execute();
        $message = '오래된 재생 기록 삭제: ' . $stmt->rowCount() . '건';
    } elseif ($action === 'cleanup_cover_cache') {
        $dir = ensureCoverCacheDir();
        $deleted = 0;
        foreach (glob($dir . '/*') ?: [] as $file) {
            if (is_file($file) && isPathInside($file, $dir)) {
                if (@unlink($file)) $deleted++;
            }
        }
        $pdo->exec("UPDATE songs SET cover_cache_path = NULL");
        $message = '앨범아트 캐시 정리: ' . $deleted . '개 파일';
    } elseif ($action === 'check_empty_playlists') {
        $count = (int)$pdo->query("SELECT COUNT(*) FROM playlists p LEFT JOIN playlist_songs ps ON ps.playlist_id = p.id WHERE ps.id IS NULL")->fetchColumn();
        $message = '빈 플레이리스트: ' . $count . '개';
    } elseif ($action === 'reset_defaults') {
        $keys = ['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_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', '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_show_recommend', 'sidebar_show_auto_playlists', 'sidebar_show_admin', 'sidebar_show_settings_detail', 'sidebar_groups_default_open', 'sidebar_mobile_auto_close', 'sidebar_compact_mode'];
        $placeholders = [];
        $params = [];
        foreach ($keys as $idx => $key) {
            $ph = ':key' . $idx;
            $placeholders[] = $ph;
            $params[$ph] = $key;
        }
        $stmt = $pdo->prepare("DELETE FROM settings WHERE setting_key IN (" . implode(',', $placeholders) . ")");
        $stmt->execute($params);
        $message = '설정 기본값을 복구했습니다.';
    } else {
        throw new Exception('알 수 없는 유지보수 작업입니다.');
    }
    logMaintenance($action, $message);
    if (function_exists('writeAppLog')) writeAppLog('info', 'maintenance', $message, ['action' => $action]);
    header('Location: ../settings.php?status=success&message=' . urlencode($message));
} catch (Exception $e) {
    logMaintenance($action ?: 'maintenance', $e->getMessage(), 'failed');
    header('Location: ../settings.php?status=error&message=' . urlencode('유지보수 실패: ' . $e->getMessage()));
}
exit;
