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

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

$action = (string)($_POST['action'] ?? '');
$adminJobId = null;
$maintenanceJobNames = [
    'refresh_missing_files' => '파일 없음 상태 갱신',
    'cleanup_scan_logs' => '오래된 스캔 로그 정리',
    'cleanup_app_logs' => '오래된 앱 로그 정리',
    'cleanup_admin_logs' => '오래된 관리자 로그 정리',
    'cleanup_play_history' => '오래된 재생 기록 정리',
    'cleanup_cover_cache' => '앨범아트 캐시 정리',
    'check_empty_playlists' => '빈 플레이리스트 확인',
    'reset_defaults' => '기본 설정 복구',
];

try {
    $pdo = getDBConnection();
    $jobStart = startAdminJob('maintenance', $maintenanceJobNames[$action] ?? '유지보수 작업', 'maintenance:' . ($action ?: 'unknown'), ['action' => $action], true);
    if (empty($jobStart['ok']) && !empty($jobStart['duplicate'])) {
        header('Location: ../settings.php?status=error&message=' . urlencode('이미 같은 유지보수 작업이 진행 중입니다. 작업 큐에서 진행 상태를 확인하세요.'));
        exit;
    }
    $adminJobId = (int)($jobStart['id'] ?? 0);
    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 = filesystemPathExists($song['file_path'], 'file') ? 0 : 1;
            $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);
    finishAdminJob($adminJobId, 'completed', [
        'processed_count' => 1,
        'summary_message' => $message,
        'context' => ['action' => $action],
    ]);
    if (function_exists('writeAppLog')) writeAppLog('info', 'maintenance', $message, ['action' => $action]);
    header('Location: ../settings.php?status=success&message=' . urlencode($message));
} catch (Exception $e) {
    $safeMessage = maskInternalPathText($e->getMessage());
    finishAdminJob($adminJobId, 'failed', [
        'processed_count' => 0,
        'failed_count' => 1,
        'summary_message' => '유지보수 작업이 실패했습니다.',
        'error_type' => 'maintenance_error',
        'context' => ['action' => $action, 'message' => $safeMessage],
    ]);
    logMaintenance($action ?: 'maintenance', $safeMessage, 'failed');
    header('Location: ../settings.php?status=error&message=' . urlencode('유지보수 실패: ' . $safeMessage));
}
exit;
