<?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/layout.php';
require_once dirname(__DIR__) . '/includes/admin_notifications.php';
require_once dirname(__DIR__) . '/includes/admin_diagnostic_report.php';
require_once dirname(__DIR__) . '/includes/admin_backup_status.php';
require_once dirname(__DIR__) . '/includes/admin_library_health.php';
require_once dirname(__DIR__) . '/includes/admin_jobs.php';
require_once dirname(__DIR__) . '/includes/stats_functions.php';
requireAdmin();

$pdo = getDBConnection();
syncAdminOperationalNotifications();
$stats = getLibraryStats();
$adminUser = currentAdminUser();
$recentScanLogs = [];
$diagnosticAlerts = [];
$scanErrorCount = 0;
$duplicateSuspects = 0;
$recentCriticalLogs = [];
$recentPlaybackIssues = [];
$recentScanFailures = [];
$listeningSummary = getListeningSummary();
$operationCards = getOperationalDashboardSummary();
$recentOperationalLogs = getRecentOperationalLogs(5);
$recentAuditSummary = getRecentAuditSummary(5);
$notificationSummary = getAdminNotificationSummary();
$weeklyOperationReport = getWeeklyOperationReport();
$jobQueueSummary = getAdminJobDashboardSummary();
$autoDiagnosticReport = getAdminAutoDiagnosticReport();
syncAdminAutoDiagnosticNotification($autoDiagnosticReport);
$backupStatusSummary = getAdminBackupStatusSummary();
syncAdminBackupStatusNotification($backupStatusSummary);
$libraryHealthReport = getAdminLibraryHealthReport(4);

try {
    $recentScanLogs = $pdo->query("SELECT id, scan_started_at, scan_finished_at, total_found, new_count, updated_count, deleted_count, skipped_count, message, created_at FROM scan_logs ORDER BY id DESC LIMIT 5")->fetchAll();
    $scanErrorCount = (int)$pdo->query("SELECT COUNT(*) FROM scan_logs WHERE message LIKE '%ERROR%' OR message LIKE '%오류%'")->fetchColumn();
} catch (Exception $e) {
    $recentScanLogs = [];
}

try {
    $stmt = $pdo->prepare("
        SELECT id, log_level, log_type, message, created_at
        FROM app_logs
        WHERE log_level IN ('error', 'critical')
        ORDER BY created_at DESC, id DESC
        LIMIT 5
    ");
    $stmt->execute();
    $recentCriticalLogs = $stmt->fetchAll();
} catch (Exception $e) {
    $recentCriticalLogs = [];
}

try {
    $stmt = $pdo->prepare("
        SELECT id, log_level, log_type, message, created_at
        FROM app_logs
        WHERE log_type IN ('stream_error', 'player_error', 'play_count_error', 'song_api_error')
           OR log_type LIKE :stream_type
           OR log_type LIKE :play_type
           OR message LIKE :stream_message
           OR message LIKE :play_message
        ORDER BY created_at DESC, id DESC
        LIMIT 5
    ");
    $stmt->execute([
        ':stream_type' => '%stream%',
        ':play_type' => '%play%',
        ':stream_message' => '%stream.php%',
        ':play_message' => '%재생%',
    ]);
    $recentPlaybackIssues = $stmt->fetchAll();
} catch (Exception $e) {
    $recentPlaybackIssues = [];
}

try {
    $stmt = $pdo->prepare("
        SELECT id, scan_finished_at, created_at, message, metadata_error_count, missing_count
        FROM scan_logs
        WHERE message LIKE :error_en
           OR message LIKE :error_ko
           OR COALESCE(metadata_error_count, 0) > 0
           OR COALESCE(missing_count, 0) > 0
        ORDER BY id DESC
        LIMIT 5
    ");
    $stmt->execute([
        ':error_en' => '%ERROR%',
        ':error_ko' => '%오류%',
    ]);
    $recentScanFailures = $stmt->fetchAll();
} catch (Exception $e) {
    $recentScanFailures = [];
}

try {
    $diagnosticAlerts = array_slice(getDiagnosticAlerts(), 0, 5);
} catch (Exception $e) {
    $diagnosticAlerts = [];
}

try {
    $duplicateSuspects = (int)$pdo->query("
        SELECT COUNT(*) FROM (
            SELECT file_hash
            FROM songs
            WHERE file_hash IS NOT NULL AND file_hash != ''
            GROUP BY file_hash
            HAVING COUNT(*) > 1
        ) d
    ")->fetchColumn();
} catch (Exception $e) {
    $duplicateSuspects = 0;
}

function adminOperationTableExists(PDO $pdo, $table) {
    static $cache = [];
    $table = (string)$table;
    if ($table === '') return false;
    if (array_key_exists($table, $cache)) return $cache[$table];
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name");
        $stmt->execute([':table_name' => $table]);
        $cache[$table] = ((int)$stmt->fetchColumn()) > 0;
    } catch (Throwable $e) {
        $cache[$table] = false;
    }
    return $cache[$table];
}

function adminOperationScalar(PDO $pdo, $table, $sql, $params = [], $default = 0) {
    if (!adminOperationTableExists($pdo, $table)) return $default;
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $value = $stmt->fetchColumn();
        return $value === false || $value === null ? $default : $value;
    } catch (Throwable $e) {
        return $default;
    }
}

function adminOperationStatus($count, $warningAt = 1, $errorAt = 10) {
    $count = (int)$count;
    if ($count >= $errorAt) return 'error';
    if ($count >= $warningAt) return 'warning';
    return 'ok';
}

function adminOperationLastLabel($value) {
    $value = trim((string)$value);
    if ($value === '') return '기록 없음';
    $time = strtotime($value);
    return $time ? date('Y-m-d H:i', $time) : $value;
}

$operationCenterCards = [];
$operationCenterPriorityCount = 0;
$playbackTodoCount = (int)adminOperationScalar($pdo, 'app_playback_failures', "SELECT COUNT(*) FROM app_playback_failures WHERE status IN ('new','reviewing')");
$playbackLastSeen = adminOperationScalar($pdo, 'app_playback_failures', "SELECT MAX(last_seen_at) FROM app_playback_failures WHERE status IN ('new','reviewing')", [], '');
$feedbackTodoCount = (int)adminOperationScalar($pdo, 'app_feedback', "SELECT COUNT(*) FROM app_feedback WHERE status IN ('received','reviewing')");
$feedbackLastSeen = adminOperationScalar($pdo, 'app_feedback', "SELECT MAX(created_at) FROM app_feedback WHERE status IN ('received','reviewing')", [], '');
$metadataTodoCount = (int)adminOperationScalar($pdo, 'metadata_correction_requests', "SELECT COUNT(*) FROM metadata_correction_requests WHERE status IN ('received','reviewing')");
$metadataLastSeen = adminOperationScalar($pdo, 'metadata_correction_requests', "SELECT MAX(created_at) FROM metadata_correction_requests WHERE status IN ('received','reviewing')", [], '');
$errors7dCount = (int)adminOperationScalar($pdo, 'app_logs', "SELECT COUNT(*) FROM app_logs WHERE log_level IN ('error','critical') AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
$errors7dLastSeen = adminOperationScalar($pdo, 'app_logs', "SELECT MAX(created_at) FROM app_logs WHERE log_level IN ('error','critical') AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)", [], '');
$activePatchCount = (int)adminOperationScalar($pdo, 'app_patch_notes', "SELECT COUNT(*) FROM app_patch_notes WHERE is_active = 1 AND (published_at IS NULL OR published_at <= NOW())");
$latestPatchSeen = adminOperationScalar($pdo, 'app_patch_notes', "SELECT MAX(COALESCE(published_at, created_at)) FROM app_patch_notes WHERE is_active = 1", [], '');
$diagnosticIssueCount = 0;
foreach (($autoDiagnosticReport['items'] ?? []) as $diagnosticItem) {
    if (($diagnosticItem['status'] ?? 'ok') !== 'ok') $diagnosticIssueCount++;
}

$operationCenterCandidates = [
    [
        'title' => '재생 실패 확인 필요',
        'count' => $playbackTodoCount,
        'status' => adminOperationStatus($playbackTodoCount, 1, 10),
        'detail' => '미확인 또는 확인 중인 재생 실패',
        'last' => $playbackLastSeen,
        'href' => 'playback_failures.php',
        'icon' => 'fa-solid fa-circle-exclamation',
        'permission' => 'playback_failure_manage',
    ],
    [
        'title' => '새 피드백 / 오류 신고',
        'count' => $feedbackTodoCount,
        'status' => adminOperationStatus($feedbackTodoCount, 1, 10),
        'detail' => '접수 또는 확인 중인 피드백',
        'last' => $feedbackLastSeen,
        'href' => 'feedback.php',
        'icon' => 'fa-solid fa-comment-dots',
        'permission' => 'feedback_manage',
    ],
    [
        'title' => '음악 정보 수정 요청',
        'count' => $metadataTodoCount,
        'status' => adminOperationStatus($metadataTodoCount, 1, 10),
        'detail' => '접수 또는 확인 중인 수정 요청',
        'last' => $metadataLastSeen,
        'href' => 'metadata_requests.php',
        'icon' => 'fa-solid fa-clipboard-question',
        'permission' => 'metadata_request_manage',
    ],
    [
        'title' => '중요 알림',
        'count' => (int)$notificationSummary['critical'],
        'status' => adminOperationStatus((int)$notificationSummary['critical'], 1, 5),
        'detail' => '읽지 않은 중요 알림',
        'last' => '',
        'href' => 'alerts.php',
        'icon' => 'fa-solid fa-bell',
        'permission' => 'alert_view',
    ],
    [
        'title' => '진행 중인 관리자 작업',
        'count' => (int)$jobQueueSummary['active'],
        'status' => ((int)$jobQueueSummary['failed_24h'] > 0) ? 'error' : adminOperationStatus((int)$jobQueueSummary['active'], 1, 5),
        'detail' => '최근 24시간 실패 ' . number_format((int)$jobQueueSummary['failed_24h']) . '건',
        'last' => '',
        'href' => 'jobs.php',
        'icon' => 'fa-solid fa-list-check',
        'permission' => 'job_queue_view',
    ],
    [
        'title' => '최근 백업 상태',
        'count' => (int)($backupStatusSummary['backup_count'] ?? 0),
        'status' => (string)($backupStatusSummary['status'] ?? 'warning'),
        'detail' => (string)($backupStatusSummary['label'] ?? '확인 필요'),
        'last' => (string)($backupStatusSummary['latest_at'] ?? ''),
        'href' => 'backup_center.php#backup-status-summary',
        'icon' => 'fa-solid fa-database',
        'permission' => 'backup_view',
    ],
    [
        'title' => '자동 점검 리포트',
        'count' => $diagnosticIssueCount,
        'status' => (string)($autoDiagnosticReport['status'] ?? 'ok'),
        'detail' => (string)($autoDiagnosticReport['label'] ?? '정상'),
        'last' => '',
        'href' => 'diagnostics.php',
        'icon' => 'fa-solid fa-stethoscope',
        'permission' => 'diagnostics_view',
    ],
    [
        'title' => '최근 7일 오류',
        'count' => $errors7dCount,
        'status' => adminOperationStatus($errors7dCount, 1, 20),
        'detail' => 'app_logs error / critical',
        'last' => $errors7dLastSeen,
        'href' => 'logs.php?level=error',
        'icon' => 'fa-solid fa-bug',
        'permission' => 'log_view',
    ],
    [
        'title' => '최근 업데이트 상태',
        'count' => $activePatchCount,
        'status' => $activePatchCount > 0 ? 'ok' : 'warning',
        'detail' => $activePatchCount > 0 ? '활성 패치노트' : '게시된 패치노트 없음',
        'last' => $latestPatchSeen,
        'href' => 'patch_notes.php',
        'icon' => 'fa-regular fa-note-sticky',
        'permission' => 'patch_note_manage',
    ],
];

$operationCenterCandidates = [
    [
        'title' => '재생 실패 확인 필요',
        'count' => $playbackTodoCount,
        'status' => adminOperationStatus($playbackTodoCount, 1, 10),
        'detail' => '미확인 또는 확인 중인 재생 실패',
        'last' => $playbackLastSeen,
        'href' => 'playback_failures.php',
        'icon' => 'fa-solid fa-circle-exclamation',
        'permission' => 'playback_failure_manage',
    ],
    [
        'title' => '새 피드백 / 오류 신고',
        'count' => $feedbackTodoCount,
        'status' => adminOperationStatus($feedbackTodoCount, 1, 10),
        'detail' => '접수 또는 확인 중인 피드백',
        'last' => $feedbackLastSeen,
        'href' => 'feedback.php',
        'icon' => 'fa-solid fa-comment-dots',
        'permission' => 'feedback_manage',
    ],
    [
        'title' => '음악 정보 수정 요청',
        'count' => $metadataTodoCount,
        'status' => adminOperationStatus($metadataTodoCount, 1, 10),
        'detail' => '접수 또는 확인 중인 수정 요청',
        'last' => $metadataLastSeen,
        'href' => 'metadata_requests.php',
        'icon' => 'fa-solid fa-clipboard-question',
        'permission' => 'metadata_request_manage',
    ],
    [
        'title' => '중요 알림',
        'count' => (int)$notificationSummary['critical'],
        'status' => adminOperationStatus((int)$notificationSummary['critical'], 1, 5),
        'detail' => '읽지 않은 중요 알림',
        'last' => '',
        'href' => 'alerts.php',
        'icon' => 'fa-solid fa-bell',
        'permission' => 'alert_view',
    ],
    [
        'title' => '진행 중인 관리자 작업',
        'count' => (int)$jobQueueSummary['active'],
        'status' => ((int)$jobQueueSummary['failed_24h'] > 0) ? 'error' : adminOperationStatus((int)$jobQueueSummary['active'], 1, 5),
        'detail' => '최근 24시간 실패 ' . number_format((int)$jobQueueSummary['failed_24h']) . '건',
        'last' => '',
        'href' => 'jobs.php',
        'icon' => 'fa-solid fa-list-check',
        'permission' => 'job_queue_view',
    ],
    [
        'title' => '최근 백업 상태',
        'count' => (int)($backupStatusSummary['backup_count'] ?? 0),
        'status' => (string)($backupStatusSummary['status'] ?? 'warning'),
        'detail' => (string)($backupStatusSummary['label'] ?? '확인 필요'),
        'last' => (string)($backupStatusSummary['latest_at'] ?? ''),
        'href' => 'backup_center.php#backup-status-summary',
        'icon' => 'fa-solid fa-database',
        'permission' => 'backup_view',
    ],
    [
        'title' => '자동 점검 리포트',
        'count' => $diagnosticIssueCount,
        'status' => (string)($autoDiagnosticReport['status'] ?? 'ok'),
        'detail' => (string)($autoDiagnosticReport['label'] ?? '정상'),
        'last' => '',
        'href' => 'diagnostics.php',
        'icon' => 'fa-solid fa-stethoscope',
        'permission' => 'diagnostics_view',
    ],
    [
        'title' => '최근 7일 오류',
        'count' => $errors7dCount,
        'status' => adminOperationStatus($errors7dCount, 1, 20),
        'detail' => 'app_logs error / critical',
        'last' => $errors7dLastSeen,
        'href' => 'logs.php?level=error',
        'icon' => 'fa-solid fa-bug',
        'permission' => 'log_view',
    ],
    [
        'title' => '최근 업데이트 상태',
        'count' => $activePatchCount,
        'status' => $activePatchCount > 0 ? 'ok' : 'warning',
        'detail' => $activePatchCount > 0 ? '활성 패치노트' : '게시된 패치노트 없음',
        'last' => $latestPatchSeen,
        'href' => 'patch_notes.php',
        'icon' => 'fa-regular fa-note-sticky',
        'permission' => 'patch_note_manage',
    ],
];

$operationCenterCandidates[] = [
    'title' => '음악 라이브러리 건강검진',
    'count' => (int)($libraryHealthReport['summary']['total_issues'] ?? 0),
    'status' => (string)($libraryHealthReport['summary']['overall'] ?? 'ok'),
    'detail' => (string)($libraryHealthReport['message'] ?? '라이브러리 상태를 확인합니다.'),
    'last' => (string)($libraryHealthReport['latest_scan_at'] ?? ''),
    'href' => 'library_health.php',
    'icon' => 'fa-solid fa-heart-pulse',
    'permission' => 'diagnostics_view',
];

foreach ($operationCenterCandidates as $candidate) {
    if (!empty($candidate['permission']) && !hasPermission($candidate['permission'])) continue;
    if (($candidate['status'] ?? 'ok') !== 'ok' || (int)($candidate['count'] ?? 0) > 0) $operationCenterPriorityCount++;
    $operationCenterCards[] = $candidate;
}

$cards = [
    ['title' => '라이브러리 건강검진', 'desc' => '파일 없음, 재생 실패, 메타데이터 누락, 중복 후보 요약', 'href' => 'library_health.php', 'icon' => 'fa-solid fa-heart-pulse', 'permission' => 'diagnostics_view'],
    ['title' => '진단센터', 'desc' => 'PHP, DB, 스토리지, PWA 상태 점검', 'href' => 'diagnostics.php', 'icon' => 'fa-solid fa-stethoscope', 'permission' => 'diagnostics_view'],
    ['title' => '오류 로그', 'desc' => 'PHP, 스캔, 스트리밍, 유지보수 오류 확인', 'href' => 'logs.php', 'icon' => 'fa-solid fa-clipboard-list', 'permission' => 'log_view'],
    ['title' => '감사 로그', 'desc' => '관리자 로그인, 권한, 위험 작업 기록 확인', 'href' => 'audit_logs.php', 'icon' => 'fa-solid fa-user-shield', 'permission' => 'audit_view'],
    ['title' => '관리자 계정', 'desc' => '관리자 역할과 활성 상태 관리', 'href' => 'users.php', 'icon' => 'fa-solid fa-users-gear', 'permission' => 'admin_manage'],
    ['title' => '알림센터', 'desc' => '관리자가 확인해야 할 주의 항목 모아보기', 'href' => 'alerts.php', 'icon' => 'fa-solid fa-bell', 'permission' => 'alert_view'],
    ['title' => '공지 관리', 'desc' => '사용자 화면 상단 공지와 업데이트 안내 관리', 'href' => 'announcements.php', 'icon' => 'fa-solid fa-bullhorn', 'permission' => 'announcement_manage'],
    ['title' => '패치노트 관리', 'desc' => '최근 업데이트 내역과 패치노트 등록/숨김', 'href' => 'patch_notes.php', 'icon' => 'fa-regular fa-note-sticky', 'permission' => 'patch_note_manage'],
    ['title' => '서비스 상태', 'desc' => '점검 안내와 재생, 스캔, 백업, PWA 상태 확인', 'href' => 'service_status.php', 'icon' => 'fa-solid fa-signal', 'permission' => 'service_status_manage'],
    ['title' => '작업 큐', 'desc' => '스캔, 백업, 가져오기, 점검 작업 진행 상태 확인', 'href' => 'jobs.php', 'icon' => 'fa-solid fa-list-check', 'permission' => 'job_queue_view'],
    ['title' => '피드백 관리', 'desc' => '사용자 오류 신고, 사용 불편, 기능 제안 처리', 'href' => 'feedback.php', 'icon' => 'fa-solid fa-comment-dots', 'permission' => 'feedback_manage'],
    ['title' => '재생 실패 관리', 'desc' => '재생 실패 곡과 파일 문제 후보 확인', 'href' => 'playback_failures.php', 'icon' => 'fa-solid fa-circle-exclamation', 'permission' => 'playback_failure_manage'],
    ['title' => '성능 점검', 'desc' => '로그, 캐시, 재생 기록 규모 확인', 'href' => 'performance.php', 'icon' => 'fa-solid fa-gauge', 'permission' => 'performance_view'],
    ['title' => '청취 통계', 'desc' => '최근 재생 흐름과 TOP 곡 요약', 'href' => 'listening_stats.php', 'icon' => 'fa-solid fa-chart-simple', 'permission' => 'performance_view'],
    ['title' => '관리자 스캔', 'desc' => '음악 폴더 스캔과 최근 스캔 상태 확인', 'href' => 'scan.php', 'icon' => 'fa-solid fa-rotate', 'permission' => 'music_scan'],
    ['title' => '음악 파일 업로드', 'desc' => '스캔 대상 폴더에 새 음악 파일과 폴더를 추가', 'href' => 'music_upload.php', 'icon' => 'fa-solid fa-cloud-arrow-up', 'permission' => 'music_scan'],
    ['title' => '음악 발견 추천', 'desc' => 'API 키 없이 추가해볼 만한 음악 후보 확인', 'href' => 'discovery.php', 'icon' => 'fa-solid fa-lightbulb', 'permission' => 'admin_home'],
    ['title' => '메타데이터 관리', 'desc' => '누락 태그와 수동 수정 보호 상태 확인', 'href' => 'metadata.php', 'icon' => 'fa-solid fa-pen-to-square', 'permission' => 'metadata_view'],
    ['title' => '메타데이터 품질', 'desc' => '누락, 깨짐, fallback, 파일 없음 후보 점검', 'href' => 'metadata_quality.php', 'icon' => 'fa-solid fa-wand-magic-sparkles', 'permission' => 'metadata_view'],
    ['title' => '일괄 수정', 'desc' => '여러 곡의 아티스트, 앨범, 장르, 연도 수정', 'href' => 'bulk_edit.php', 'icon' => 'fa-solid fa-table-list', 'permission' => 'metadata_bulk_edit'],
    ['title' => '스마트 정리', 'desc' => '누락 메타데이터와 정리 후보를 빠르게 확인', 'href' => 'smart_organize.php', 'icon' => 'fa-solid fa-broom', 'permission' => 'smart_organize'],
    ['title' => '태그 관리', 'desc' => '태그 생성, 이름 변경, 병합, 삭제 관리', 'href' => 'tag_manage.php', 'icon' => 'fa-solid fa-tags', 'permission' => 'tag_manage'],
    ['title' => '표기 통합', 'desc' => '아티스트, 앨범, 장르 표기 차이를 병합', 'href' => 'name_merge.php', 'icon' => 'fa-solid fa-object-group', 'permission' => 'name_merge'],
    ['title' => '중복곡 관리', 'desc' => '중복 의심 곡 확인', 'href' => 'duplicates.php', 'icon' => 'fa-solid fa-clone', 'permission' => 'duplicates_manage'],
    ['title' => '파일 없음 관리', 'desc' => '사라진 파일 상태 확인', 'href' => 'missing_files.php', 'icon' => 'fa-solid fa-file-circle-question', 'permission' => 'missing_files_manage'],
    ['title' => '백업 센터', 'desc' => '전체 백업, 선택 export, import 미리보기와 복원', 'href' => 'backup_center.php', 'icon' => 'fa-solid fa-database', 'permission' => 'backup_view'],
    ['title' => 'API 토큰', 'desc' => '외부 클라이언트 연동용 토큰 생성과 폐기', 'href' => 'api_tokens.php', 'icon' => 'fa-solid fa-key', 'permission' => 'admin_manage'],
    ['title' => '유지보수', 'desc' => '로그, 캐시, 파일 없음 상태 정리', 'href' => '../settings.php#maintenance-tools', 'icon' => 'fa-solid fa-screwdriver-wrench', 'permission' => 'maintenance_run'],
    ['title' => '설정', 'desc' => '테마, 플레이어, 스캔, 접근 보안 설정', 'href' => '../settings.php', 'icon' => 'fa-solid fa-gear', 'permission' => 'settings_manage'],
    ['title' => '정보 수정 요청', 'desc' => '사용자가 제보한 곡 정보 오류와 보정 요청 처리', 'href' => 'metadata_requests.php', 'icon' => 'fa-solid fa-clipboard-question', 'permission' => 'metadata_request_manage'],
];
$cards = array_values(array_filter($cards, function ($card) {
    return empty($card['permission']) || hasPermission($card['permission']);
}));

$adminCenterSections = [
    'metadata_requests' => ['title' => '정보 수정 요청', 'desc' => '사용자가 남긴 곡 정보 보정 요청을 확인하고 처리합니다.', 'hrefs' => ['metadata_requests.php']],
    'priority' => ['title' => '자주 쓰는 관리', 'desc' => '스캔, 업로드, 품질 관리, 파일 문제처럼 자주 확인하는 작업입니다.', 'hrefs' => ['scan.php', 'music_upload.php', 'metadata_quality.php', 'duplicates.php', 'missing_files.php', 'backup_center.php']],
    'music' => ['title' => '음악 / 메타데이터', 'desc' => '라이브러리 정리, 추천 후보, 메타데이터 수정 기능입니다.', 'hrefs' => ['discovery.php', 'metadata.php', 'bulk_edit.php', 'smart_organize.php', 'tag_manage.php', 'name_merge.php']],
    'ops' => ['title' => '운영 / 점검', 'desc' => '진단, 오류, 알림, 공지, 성능 상태를 확인합니다.', 'hrefs' => ['diagnostics.php', 'library_health.php', 'logs.php', 'audit_logs.php', 'alerts.php', 'announcements.php', 'patch_notes.php', 'service_status.php', 'jobs.php', 'feedback.php', 'playback_failures.php', 'performance.php', 'listening_stats.php']],
    'system' => ['title' => '계정 / 설정', 'desc' => '관리자 계정, API 토큰, 유지보수와 서비스 설정입니다.', 'hrefs' => ['users.php', 'api_tokens.php', '../settings.php#maintenance-tools', '../settings.php']],
];
$cardsByHref = [];
foreach ($cards as $card) {
    $cardsByHref[$card['href']] = $card;
}

renderHeader('통합 관리자 센터', 'admin_home');
?>
<div class="admin-dashboard">
    <div class="page-title-section">
        <h1 class="page-main-title">통합 관리자 센터</h1>
        <p class="page-subtitle">사이드바는 가볍게 유지하고, 운영 / 스캔 / 메타데이터 / 백업 / 권한 관리는 이 화면에서 처리합니다.</p>
    </div>

    <section class="home-section admin-session-card">
        <div>
            <h2 class="section-title">로그인 정보</h2>
            <p><?php echo h($adminUser['display_name'] ?: $adminUser['username']); ?>님으로 로그인 중입니다.</p>
            <p class="settings-muted">마지막 로그인: <?php echo h($adminUser['last_login_at'] ?: '-'); ?></p>
        </div>
        <a class="btn btn-secondary" href="../logout.php"><i class="fa-solid fa-right-from-bracket"></i> 로그아웃</a>
    </section>

    <?php renderStatGrid([
        ['label' => '전체 곡', 'value' => number_format($stats['songs'])],
        ['label' => '메타데이터 누락', 'value' => number_format($stats['metadata_missing'])],
        ['label' => '파일 없음', 'value' => number_format($stats['missing'])],
        ['label' => '중복 의심', 'value' => number_format($duplicateSuspects)],
        ['label' => '스캔 오류', 'value' => number_format($scanErrorCount)],
        ['label' => '진행 작업', 'value' => number_format($jobQueueSummary['active'])],
        ['label' => '총 재생', 'value' => number_format($stats['plays'])],
    ]); ?>

    <section class="home-section admin-operation-center-section">
        <div class="section-heading-row admin-operation-center-head">
            <div>
                <h2 class="section-title">관리자 운영 센터</h2>
                <p class="settings-muted">오늘 확인할 운영 항목과 최근 7일 상태를 요약합니다. 상세 데이터는 각 관리 화면에서 확인합니다.</p>
            </div>
            <span class="diagnostic-state-pill status-<?php echo $operationCenterPriorityCount > 0 ? 'warning' : 'ok'; ?>">
                <?php echo $operationCenterPriorityCount > 0 ? '확인 필요 ' . number_format($operationCenterPriorityCount) . '건' : '확인 필요 항목 없음'; ?>
            </span>
        </div>
        <div class="admin-operation-center-grid">
            <?php foreach ($operationCenterCards as $opCard): ?>
                <a class="admin-operation-card status-<?php echo h($opCard['status'] ?? 'ok'); ?>" href="<?php echo h($opCard['href']); ?>" data-admin-card data-admin-panel-title="<?php echo h($opCard['title']); ?>" aria-controls="admin-workspace-panel">
                    <span class="admin-operation-icon"><i class="<?php echo h($opCard['icon']); ?>"></i></span>
                    <span class="admin-operation-main">
                        <strong><?php echo h($opCard['title']); ?></strong>
                        <small><?php echo h($opCard['detail']); ?></small>
                        <em>마지막 기록: <?php echo h(trim((string)($opCard['last'] ?? '')) === '' ? '기록 없음' : adminOperationLastLabel($opCard['last'] ?? '')); ?></em>
                    </span>
                    <span class="admin-operation-count"><?php echo number_format((int)$opCard['count']); ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="home-section admin-library-health-section status-<?php echo h($libraryHealthReport['summary']['overall'] ?? 'ok'); ?>">
        <div class="section-heading-row admin-library-health-head">
            <div>
                <h2 class="section-title">음악 라이브러리 건강검진</h2>
                <p class="settings-muted"><?php echo h($libraryHealthReport['message'] ?? '음악 파일과 DB 상태를 점검합니다.'); ?></p>
            </div>
            <div class="admin-library-health-actions">
                <span class="diagnostic-state-pill status-<?php echo h($libraryHealthReport['summary']['overall'] ?? 'ok'); ?>">
                    <?php echo h($libraryHealthReport['label'] ?? '정상'); ?>
                </span>
                <a class="section-more-link" href="library_health.php" data-admin-card data-admin-panel-title="음악 라이브러리 건강검진">상세 보기</a>
            </div>
        </div>
        <div class="admin-library-health-grid">
            <?php
            $healthPreviewItems = array_values(array_filter($libraryHealthReport['items'] ?? [], function ($item) {
                return ($item['status'] ?? 'ok') !== 'ok';
            }));
            if (!$healthPreviewItems) $healthPreviewItems = array_slice($libraryHealthReport['items'] ?? [], 0, 4);
            ?>
            <?php foreach (array_slice($healthPreviewItems, 0, 6) as $item): ?>
                <a class="admin-library-health-card status-<?php echo h($item['status'] ?? 'ok'); ?>" href="<?php echo h($item['href'] ?? 'library_health.php'); ?>" data-admin-card data-admin-panel-title="<?php echo h($item['title'] ?? '라이브러리 점검'); ?>">
                    <span class="admin-library-health-icon"><i class="<?php echo h($item['icon'] ?? 'fa-solid fa-circle-info'); ?>"></i></span>
                    <span class="admin-library-health-main">
                        <strong><?php echo h($item['title'] ?? '점검 항목'); ?></strong>
                        <small><?php echo h($item['detail'] ?? ''); ?></small>
                    </span>
                    <span class="admin-library-health-count"><?php echo number_format((int)($item['count'] ?? 0)); ?></span>
                </a>
            <?php endforeach; ?>
        </div>
        <?php if (($libraryHealthReport['summary']['overall'] ?? 'ok') === 'ok'): ?>
            <p class="admin-library-health-empty">현재 확인 필요한 라이브러리 문제가 없습니다.</p>
        <?php endif; ?>
    </section>

    <section id="auto-diagnostic-report" class="home-section admin-auto-diagnostic-section status-<?php echo h($autoDiagnosticReport['status'] ?? 'ok'); ?>">
        <div class="section-heading-row admin-auto-diagnostic-head">
            <div>
                <h2 class="section-title">자동 점검 리포트</h2>
                <p class="settings-muted">재생 실패, 스캔 실패, 메타데이터 누락, 최근 오류를 민감정보 없이 요약합니다.</p>
            </div>
            <div class="admin-auto-diagnostic-actions">
                <span class="diagnostic-state-pill status-<?php echo h($autoDiagnosticReport['status'] ?? 'ok'); ?>">
                    <?php echo h($autoDiagnosticReport['label'] ?? '정상'); ?>
                </span>
                <a class="section-more-link" href="diagnostics.php">전체 진단</a>
            </div>
        </div>
        <div class="admin-auto-diagnostic-grid">
            <?php foreach (($autoDiagnosticReport['items'] ?? []) as $item): ?>
                <a class="admin-auto-diagnostic-card status-<?php echo h($item['status'] ?? 'ok'); ?>" href="<?php echo h($item['href'] ?? 'diagnostics.php'); ?>">
                    <span class="admin-auto-diagnostic-icon"><i class="<?php echo h($item['icon'] ?? 'fa-solid fa-circle-info'); ?>"></i></span>
                    <span class="admin-auto-diagnostic-main">
                        <span class="admin-auto-diagnostic-title"><?php echo h($item['title'] ?? '점검 항목'); ?></span>
                        <strong><?php echo number_format((int)($item['count'] ?? 0)); ?></strong>
                        <small><?php echo h($item['detail'] ?? ''); ?></small>
                    </span>
                    <span class="admin-auto-diagnostic-badge"><?php echo h($item['label'] ?? '정상'); ?></span>
                </a>
            <?php endforeach; ?>
        </div>
        <?php if (($autoDiagnosticReport['status'] ?? 'ok') === 'ok'): ?>
            <p class="admin-auto-diagnostic-empty">현재 확인 필요한 문제가 없습니다.</p>
        <?php endif; ?>
    </section>

    <section class="home-section backup-status-dashboard-section status-<?php echo h($backupStatusSummary['status'] ?? 'warning'); ?>">
        <div class="section-heading-row backup-status-dashboard-head">
            <div>
                <h2 class="section-title">백업 / 복구 준비 상태</h2>
                <p class="settings-muted"><?php echo h($backupStatusSummary['message'] ?? '백업 상태를 확인합니다.'); ?></p>
            </div>
            <div class="backup-status-dashboard-actions">
                <span class="diagnostic-state-pill status-<?php echo h($backupStatusSummary['status'] ?? 'warning'); ?>">
                    <?php echo h($backupStatusSummary['label'] ?? '주의'); ?>
                </span>
                <a class="section-more-link" href="backup_center.php#backup-status-summary">백업 센터</a>
            </div>
        </div>
        <div class="backup-status-dashboard-grid">
            <article class="backup-status-dashboard-card">
                <span>최근 DB 백업</span>
                <strong><?php echo h($backupStatusSummary['latest_at'] ?? '없음'); ?></strong>
                <small><?php echo h($backupStatusSummary['latest']['file_name'] ?? '복구용 DB 백업 없음'); ?></small>
            </article>
            <article class="backup-status-dashboard-card">
                <span>백업 파일</span>
                <strong><?php echo number_format((int)($backupStatusSummary['backup_count'] ?? 0)); ?>개</strong>
                <small>전체 <?php echo h($backupStatusSummary['total_size_text'] ?? '0 bytes'); ?></small>
            </article>
            <article class="backup-status-dashboard-card">
                <span>복구 준비</span>
                <strong><?php echo h($backupStatusSummary['restore_label'] ?? '확인 필요'); ?></strong>
                <small>최근 백업 <?php echo h($backupStatusSummary['latest_size_text'] ?? '-'); ?></small>
            </article>
            <article class="backup-status-dashboard-card">
                <span>실패 / 이상</span>
                <strong><?php echo number_format((int)($backupStatusSummary['failed_count'] ?? 0)); ?> / <?php echo number_format((int)($backupStatusSummary['abnormal_count'] ?? 0)); ?></strong>
                <small>최근 30일 실패 로그 / 비정상 크기</small>
            </article>
        </div>
    </section>

    <section class="home-section operation-overview-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">운영 상태 요약</h2>
                <p class="settings-muted">최근 기간과 안전한 파일 상태만 기준으로 빠르게 점검합니다. 대시보드 진입만으로 스캔이나 백업은 실행하지 않습니다.</p>
            </div>
            <a class="section-more-link" href="diagnostics.php">운영 진단</a>
        </div>
        <div class="operation-status-grid">
            <?php foreach ($operationCards as $card): ?>
                <?php $status = $card['status'] ?? 'unknown'; ?>
                <article class="operation-status-card status-<?php echo h($status); ?>">
                    <span class="operation-status-label"><?php echo h($card['label']); ?></span>
                    <strong><?php echo h($card['value']); ?></strong>
                    <?php if (!empty($card['detail'])): ?><small><?php echo h($card['detail']); ?></small><?php endif; ?>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="home-section operation-overview-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">관리자 알림 요약</h2>
                <p class="settings-muted">운영 알림, 보안 알림, 백업 상태, 최근 7일 리포트를 알림센터에서 확인합니다.</p>
            </div>
            <a class="section-more-link" href="alerts.php">알림센터</a>
        </div>
        <div class="operation-status-grid">
            <article class="operation-status-card status-<?php echo $notificationSummary['unread'] > 0 ? 'warning' : 'ok'; ?>">
                <span class="operation-status-label">미확인 알림</span>
                <strong><?php echo number_format($notificationSummary['unread']); ?></strong>
                <small>읽음 처리 전 알림</small>
            </article>
            <article class="operation-status-card status-<?php echo $notificationSummary['critical'] > 0 ? 'error' : 'ok'; ?>">
                <span class="operation-status-label">중요 알림</span>
                <strong><?php echo number_format($notificationSummary['critical']); ?></strong>
                <small>오류 / critical 기준</small>
            </article>
            <article class="operation-status-card status-<?php echo $notificationSummary['security'] > 0 ? 'warning' : 'ok'; ?>">
                <span class="operation-status-label">보안 알림</span>
                <strong><?php echo number_format($notificationSummary['security']); ?></strong>
                <small>권한 / CSRF / 인증 관련</small>
            </article>
            <article class="operation-status-card status-<?php echo ($weeklyOperationReport['summary']['errors'] ?? 0) > 0 ? 'error' : (($weeklyOperationReport['summary']['warnings'] ?? 0) > 0 ? 'warning' : 'ok'); ?>">
                <span class="operation-status-label">최근 7일 리포트</span>
                <strong><?php echo number_format((int)($weeklyOperationReport['summary']['errors'] ?? 0)); ?> / <?php echo number_format((int)($weeklyOperationReport['summary']['warnings'] ?? 0)); ?></strong>
                <small>오류 / 주의 항목</small>
            </article>
        </div>
    </section>

    <section class="home-section admin-issue-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">최근 문제 빠른 점검</h2>
                <p class="settings-muted">최근 오류, 재생 실패 후보, 스캔 실패를 민감 경로 없이 요약합니다.</p>
            </div>
            <a class="section-more-link" href="logs.php">로그 보기</a>
        </div>
        <div class="admin-issue-grid">
            <article class="admin-issue-card">
                <div class="admin-issue-card-head">
                    <strong><i class="fa-solid fa-triangle-exclamation"></i> 최근 중요 오류</strong>
                    <a href="logs.php?level=error">확인</a>
                </div>
                <div class="admin-log-list">
                    <?php if (empty($recentCriticalLogs)): ?>
                        <p class="empty-text">최근 중요 오류가 없습니다.</p>
                    <?php else: ?>
                        <?php foreach ($recentCriticalLogs as $log): ?>
                            <div class="admin-log-row compact">
                                <strong><?php echo h(strtoupper($log['log_level'] ?? '') . ' / ' . ($log['log_type'] ?? '')); ?></strong>
                                <span><?php echo h($log['created_at'] ?? '-'); ?></span>
                                <p><?php echo h(maskInternalPathText($log['message'] ?? '')); ?></p>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </article>

            <article class="admin-issue-card">
                <div class="admin-issue-card-head">
                    <strong><i class="fa-solid fa-circle-play"></i> 재생 실패 후보</strong>
                    <a href="logs.php">확인</a>
                </div>
                <div class="admin-log-list">
                    <?php if (empty($recentPlaybackIssues)): ?>
                        <p class="empty-text">최근 재생 관련 오류가 없습니다.</p>
                    <?php else: ?>
                        <?php foreach ($recentPlaybackIssues as $log): ?>
                            <div class="admin-log-row compact">
                                <strong><?php echo h(strtoupper($log['log_level'] ?? '') . ' / ' . ($log['log_type'] ?? '')); ?></strong>
                                <span><?php echo h($log['created_at'] ?? '-'); ?></span>
                                <p><?php echo h(maskInternalPathText($log['message'] ?? '')); ?></p>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </article>

            <article class="admin-issue-card">
                <div class="admin-issue-card-head">
                    <strong><i class="fa-solid fa-rotate"></i> 최근 스캔 실패</strong>
                    <a href="scan.php">확인</a>
                </div>
                <div class="admin-log-list">
                    <?php if (empty($recentScanFailures)): ?>
                        <p class="empty-text">최근 스캔 실패 후보가 없습니다.</p>
                    <?php else: ?>
                        <?php foreach ($recentScanFailures as $log): ?>
                            <div class="admin-log-row compact">
                                <strong>스캔 #<?php echo h($log['id'] ?? '-'); ?></strong>
                                <span><?php echo h($log['scan_finished_at'] ?? $log['created_at'] ?? '-'); ?></span>
                                <p><?php echo h(maskInternalPathText(scanMessageToKorean($log['message'] ?? ''))); ?></p>
                                <small>메타데이터 오류 <?php echo number_format((int)($log['metadata_error_count'] ?? 0)); ?>건 · 파일 없음 <?php echo number_format((int)($log['missing_count'] ?? 0)); ?>건</small>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </article>
        </div>
    </section>

    <section class="home-section recovery-action-section">
        <div class="section-heading-row">
            <div>
                <h2 class="section-title">복구 / 확인 바로가기</h2>
                <p class="settings-muted">문제가 보이면 먼저 진단과 로그를 확인하고, 필요한 경우에만 수동 작업을 실행합니다.</p>
            </div>
        </div>
        <div class="dashboard-quick-actions">
            <?php if (hasPermission('diagnostics_view')): ?><a class="btn btn-secondary" href="diagnostics.php"><i class="fa-solid fa-stethoscope"></i> 운영 진단</a><?php endif; ?>
            <?php if (hasPermission('log_view')): ?><a class="btn btn-secondary" href="logs.php"><i class="fa-solid fa-clipboard-list"></i> 오류 로그</a><?php endif; ?>
            <?php if (hasPermission('audit_view')): ?><a class="btn btn-secondary" href="audit_logs.php"><i class="fa-solid fa-user-shield"></i> 감사 로그</a><?php endif; ?>
            <?php if (hasPermission('backup_view')): ?><a class="btn btn-secondary" href="backup_center.php"><i class="fa-solid fa-database"></i> 백업 상태</a><?php endif; ?>
            <?php if (hasPermission('music_scan')): ?><a class="btn btn-secondary" href="scan.php"><i class="fa-solid fa-rotate"></i> 스캔 확인</a><?php endif; ?>
            <?php if (hasPermission('music_scan')): ?><a class="btn btn-secondary" href="music_upload.php"><i class="fa-solid fa-cloud-arrow-up"></i> 음악 업로드</a><?php endif; ?>
            <?php if (hasPermission('job_queue_view')): ?><a class="btn btn-secondary" href="jobs.php"><i class="fa-solid fa-list-check"></i> 작업 큐</a><?php endif; ?>
            <?php if (hasPermission('metadata_view')): ?><a class="btn btn-secondary" href="metadata_quality.php"><i class="fa-solid fa-wand-magic-sparkles"></i> 품질 관리</a><?php endif; ?>
        </div>
    </section>

    <section class="home-section admin-center-menu-section">
        <div class="section-heading-row admin-center-menu-head">
            <div>
                <h2 class="section-title">관리 메뉴</h2>
                <p class="settings-muted">관리자 기능은 이 센터에서 찾고 실행합니다. 사이드바에는 센터 진입점만 표시됩니다.</p>
            </div>
            <label class="admin-center-search" for="admin-center-search">
                <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                <input type="search" id="admin-center-search" placeholder="관리 기능 검색">
            </label>
        </div>
        <div class="admin-center-sections" id="admin-center-sections">
            <?php foreach ($adminCenterSections as $section): ?>
                <?php
                $sectionCards = [];
                foreach ($section['hrefs'] as $href) {
                    if (isset($cardsByHref[$href])) $sectionCards[] = $cardsByHref[$href];
                }
                if (empty($sectionCards)) continue;
                ?>
                <div class="admin-center-section">
                    <div class="admin-center-section-title">
                        <strong><?php echo h($section['title']); ?></strong>
                        <span><?php echo h($section['desc']); ?></span>
                    </div>
                    <div class="admin-card-grid">
                        <?php foreach ($sectionCards as $card): ?>
                            <a class="admin-hub-card" href="<?php echo h($card['href']); ?>" data-admin-card data-admin-panel-title="<?php echo h($card['title']); ?>" data-search-text="<?php echo h($card['title'] . ' ' . $card['desc']); ?>" aria-controls="admin-workspace-panel">
                                <i class="<?php echo h($card['icon']); ?>"></i>
                                <strong><?php echo h($card['title']); ?></strong>
                                <span><?php echo h($card['desc']); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <p class="empty-text admin-center-empty" id="admin-center-empty" hidden>검색 결과가 없습니다.</p>
    </section>

    <section class="home-section admin-workspace-section" id="admin-workspace-panel" data-admin-workspace hidden>
        <div class="admin-workspace-head">
            <div>
                <span class="admin-workspace-eyebrow">관리 작업</span>
                <h2 class="section-title" id="admin-workspace-title">관리 메뉴를 선택하세요</h2>
                <p class="settings-muted" id="admin-workspace-subtitle">메뉴를 선택하면 이 영역에서 바로 확인하고 다른 관리 메뉴로 전환할 수 있습니다.</p>
            </div>
            <div class="admin-workspace-actions">
                <a class="btn btn-secondary btn-sm" id="admin-workspace-open-page" href="#" data-no-pjax hidden>
                    <i class="fa-solid fa-up-right-from-square"></i> 전체 페이지
                </a>
                <button type="button" class="btn btn-secondary btn-sm" id="admin-workspace-close">
                    <i class="fa-solid fa-xmark"></i> 닫기
                </button>
            </div>
        </div>
        <div class="admin-workspace-status" id="admin-workspace-status" role="status" aria-live="polite" hidden></div>
        <div class="admin-workspace-body" id="admin-workspace-body" tabindex="-1"></div>
    </section>

    <div class="home-section-grid">
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">시스템 상태</h2><a class="section-more-link" href="diagnostics.php">더보기</a></div>
            <div class="admin-log-list">
                <?php if (empty($diagnosticAlerts)): ?>
                    <p class="empty-text">현재 진단 알림이 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($diagnosticAlerts as $alert): ?>
                        <div class="admin-log-row">
                            <strong><?php echo h($alert['title']); ?></strong>
                            <span><?php echo h($alert['status']); ?></span>
                            <p><?php echo h($alert['message']); ?></p>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>

        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">최근 오류</h2><a class="section-more-link" href="logs.php">더보기</a></div>
            <div class="admin-log-list">
                <?php if (empty($recentOperationalLogs)): ?>
                    <p class="empty-text">최근 주의/오류 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentOperationalLogs as $log): ?>
                        <div class="admin-log-row">
                            <strong><?php echo h(strtoupper($log['log_level']) . ' / ' . $log['log_type']); ?></strong>
                            <span><?php echo h($log['created_at']); ?></span>
                            <p><?php echo h(maskInternalPathText($log['message'] ?? '')); ?></p>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">최근 스캔 로그</h2><a class="section-more-link" href="scan.php">더보기</a></div>
            <div class="admin-log-list">
                <?php if (empty($recentScanLogs)): ?>
                    <p class="empty-text">최근 스캔 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentScanLogs as $log): ?>
                        <div class="admin-log-row">
                            <strong>스캔 #<?php echo h($log['id']); ?></strong>
                            <span><?php echo h($log['scan_finished_at'] ?? $log['created_at'] ?? '-'); ?></span>
                            <?php if (!empty($log['message'])): ?><p><?php echo h(maskInternalPathText(scanMessageToKorean($log['message']))); ?></p><?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>

        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">최근 관리자 작업 로그</h2><a class="section-more-link" href="audit_logs.php">더보기</a></div>
            <div class="admin-log-list">
                <?php if (empty($recentAuditSummary)): ?>
                    <p class="empty-text">최근 관리자 작업 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentAuditSummary as $log): ?>
                        <div class="admin-log-row">
                            <strong><?php echo h($log['action_type']); ?></strong>
                            <span><?php echo h($log['created_at']); ?> · <?php echo h($log['display_name'] ?: $log['username'] ?: 'system'); ?></span>
                            <?php if (!empty($log['message'])): ?><p><?php echo h(maskInternalPathText($log['message'])); ?></p><?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
    </div>
</div>
<script>
(function () {
    function bindAdminCenterSearch() {
        var input = document.getElementById('admin-center-search');
        var empty = document.getElementById('admin-center-empty');
        if (!input) return;

        var applyFilter = function () {
            var query = (input.value || '').trim().toLowerCase();
            var visibleCount = 0;
            document.querySelectorAll('.admin-center-section').forEach(function (section) {
                var sectionVisible = false;
                section.querySelectorAll('[data-admin-card]').forEach(function (card) {
                    var text = (card.getAttribute('data-search-text') || '').toLowerCase();
                    var matched = query === '' || text.indexOf(query) !== -1;
                    card.hidden = !matched;
                    if (matched) {
                        sectionVisible = true;
                        visibleCount++;
                    }
                });
                section.hidden = !sectionVisible;
            });
            if (empty) empty.hidden = visibleCount > 0;
        };

        if (input.dataset.adminCenterSearchBound !== '1') {
            input.dataset.adminCenterSearchBound = '1';
            input.addEventListener('input', applyFilter);
        }
        applyFilter();
    }

    function adminWorkspaceElements() {
        return {
            panel: document.getElementById('admin-workspace-panel'),
            title: document.getElementById('admin-workspace-title'),
            subtitle: document.getElementById('admin-workspace-subtitle'),
            body: document.getElementById('admin-workspace-body'),
            status: document.getElementById('admin-workspace-status'),
            openPage: document.getElementById('admin-workspace-open-page'),
            close: document.getElementById('admin-workspace-close')
        };
    }

    function adminWorkspaceSafeUrl(rawUrl) {
        var blockedFiles = {
            'backup_download.php': true,
            'backup_delete.php': true,
            'restore_run.php': true,
            'export.php': true,
            'log_clear.php': true,
            'metadata_action.php': true,
            'missing_action.php': true,
            'bulk_update.php': true,
            'settings_save.php': true
        };
        try {
            var url = new URL(rawUrl, window.location.href);
            if (url.origin !== window.location.origin) return null;
            var file = url.pathname.split('/').pop();
            if (blockedFiles[file]) return null;
            var appRoot = String(window.APP_ROOT_PATH || window.APP_BASE_PATH || '/music/');
            if (!appRoot.startsWith('/')) appRoot = new URL(appRoot, window.location.origin).pathname;
            if (!appRoot.endsWith('/')) appRoot += '/';
            var adminPrefix = appRoot + 'admin/';
            var settingsPath = appRoot + 'settings.php';
            if (url.pathname.indexOf(adminPrefix) !== 0 && url.pathname !== settingsPath) return null;
            return url;
        } catch (err) {
            return null;
        }
    }

    function setAdminWorkspaceStatus(message, type) {
        var els = adminWorkspaceElements();
        if (!els.status) return;
        els.status.hidden = !message;
        els.status.textContent = message || '';
        els.status.className = 'admin-workspace-status' + (type ? ' status-' + type : '');
    }

    function executeAdminWorkspaceScripts(root) {
        if (!root) return;
        root.querySelectorAll('script').forEach(function (oldScript) {
            var script = document.createElement('script');
            Array.prototype.slice.call(oldScript.attributes).forEach(function (attr) {
                script.setAttribute(attr.name, attr.value);
            });
            script.text = oldScript.textContent || '';
            oldScript.replaceWith(script);
        });
    }

    function normalizeAdminWorkspaceLinks(root) {
        if (!root) return;
        root.querySelectorAll('a[href]').forEach(function (link) {
            var raw = link.getAttribute('href') || '';
            if (!raw || raw.indexOf('#') === 0 || /^(javascript:|mailto:|tel:)/i.test(raw)) return;
            try {
                link.setAttribute('href', new URL(raw, window.location.href).href);
            } catch (err) {}
        });
        root.querySelectorAll('form[action]').forEach(function (form) {
            var raw = form.getAttribute('action') || '';
            try {
                form.setAttribute('action', new URL(raw, window.location.href).href);
            } catch (err) {}
        });
    }

    function applyAdminWorkspaceActive(url) {
        document.querySelectorAll('[data-admin-card]').forEach(function (card) {
            var active = false;
            try {
                var cardUrl = new URL(card.getAttribute('href'), window.location.href);
                active = cardUrl.pathname === url.pathname;
            } catch (err) {}
            card.classList.toggle('is-active', active);
            card.setAttribute('aria-current', active ? 'page' : 'false');
        });
    }

    function closeAdminWorkspace() {
        var els = adminWorkspaceElements();
        if (els.panel) els.panel.hidden = true;
        if (els.body) els.body.innerHTML = '';
        setAdminWorkspaceStatus('', '');
        document.querySelectorAll('[data-admin-card].is-active').forEach(function (card) {
            card.classList.remove('is-active');
            card.setAttribute('aria-current', 'false');
        });
    }

    function initAdminWorkspaceContent() {
        var els = adminWorkspaceElements();
        if (!els.body) return;
        normalizeAdminWorkspaceLinks(els.body);
        executeAdminWorkspaceScripts(els.body);
        document.dispatchEvent(new CustomEvent('melonlite:page-ready', { detail: { url: window.location.href, scope: 'admin-workspace' } }));
        if (els.body.focus) els.body.focus({ preventScroll: true });
    }

    async function loadAdminWorkspace(rawUrl, title, options) {
        var url = adminWorkspaceSafeUrl(rawUrl);
        var els = adminWorkspaceElements();
        if (!url || !els.panel || !els.body) return false;
        options = options || {};

        els.panel.hidden = false;
        if (els.title) els.title.textContent = title || '관리 작업';
        if (els.subtitle) els.subtitle.textContent = '페이지 이동 없이 관리 작업을 확인합니다. 복잡한 작업은 전체 페이지로 열 수 있습니다.';
        if (els.openPage) {
            els.openPage.href = url.href;
            els.openPage.hidden = false;
        }
        els.body.innerHTML = '';
        setAdminWorkspaceStatus('불러오는 중...', 'loading');
        applyAdminWorkspaceActive(url);

        try {
            var response = await fetch(url.href, {
                method: 'GET',
                credentials: 'same-origin',
                cache: 'no-store',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-MelonLite-Admin-Workspace': '1',
                    'Cache-Control': 'no-cache'
                }
            });
            if (!response.ok) throw new Error('HTTP ' + response.status);
            var text = await response.text();
            var doc = new DOMParser().parseFromString(text, 'text/html');
            var content = doc.getElementById('app-content') || doc.querySelector('[data-pjax-root]') || doc.querySelector('.content-body');
            if (!content) throw new Error('content root not found');
            els.body.innerHTML = content.innerHTML;
            setAdminWorkspaceStatus('', '');
            initAdminWorkspaceContent();
            els.panel.scrollIntoView({ behavior: options.smooth === false ? 'auto' : 'smooth', block: 'start' });
            return true;
        } catch (err) {
            setAdminWorkspaceStatus('관리 화면을 불러오지 못했습니다. 전체 페이지로 열어 확인해 주세요.', 'error');
            if (window.showToast) window.showToast('관리 화면을 불러오지 못했습니다.', 'warning');
            return true;
        }
    }

    function bindAdminWorkspace() {
        var els = adminWorkspaceElements();
        if (!els.panel) return;
        if (els.panel.dataset.bound !== '1') els.panel.dataset.bound = '1';
        if (window.__MELON_LITE_ADMIN_WORKSPACE_BOUND) return;
        window.__MELON_LITE_ADMIN_WORKSPACE_BOUND = true;

        document.addEventListener('click', function (event) {
            var closeButton = event.target.closest && event.target.closest('#admin-workspace-close');
            if (closeButton) {
                closeAdminWorkspace();
                return;
            }

            var menuCard = event.target.closest && event.target.closest('[data-admin-card]');
            if (menuCard) {
                var url = adminWorkspaceSafeUrl(menuCard.getAttribute('href'));
                if (!url) return;
                event.preventDefault();
                loadAdminWorkspace(url.href, menuCard.getAttribute('data-admin-panel-title') || menuCard.textContent.trim());
                return;
            }

            var workspaceLink = event.target.closest && event.target.closest('#admin-workspace-body a[href]');
            if (!workspaceLink || workspaceLink.target || workspaceLink.hasAttribute('download') || workspaceLink.dataset.noPjax !== undefined) return;
            var workspaceUrl = adminWorkspaceSafeUrl(workspaceLink.getAttribute('href'));
            if (!workspaceUrl) return;
            event.preventDefault();
            loadAdminWorkspace(workspaceUrl.href, workspaceLink.textContent.trim() || '관리 작업');
        });

        document.addEventListener('submit', function (event) {
            var form = event.target && event.target.closest ? event.target.closest('#admin-workspace-body form') : null;
            if (!form || String(form.getAttribute('method') || 'GET').toUpperCase() !== 'GET') return;
            var fallbackAction = (els.openPage && els.openPage.href) ? els.openPage.href : window.location.href;
            var url = adminWorkspaceSafeUrl(form.getAttribute('action') || fallbackAction);
            if (!url) return;
            event.preventDefault();
            var data = new FormData(form);
            var params = new URLSearchParams();
            data.forEach(function (value, key) {
                if (value !== null && value !== undefined && String(value) !== '') params.append(key, String(value));
            });
            url.search = params.toString();
            loadAdminWorkspace(url.href, els.title ? els.title.textContent : '관리 작업', { smooth: false });
        });

    }

    window.MelonLiteInitAdminCenter = function () {
        bindAdminCenterSearch();
        bindAdminWorkspace();
    };
    window.MelonLiteInitAdminCenter();

    if (!window.__MELON_LITE_ADMIN_CENTER_SEARCH_READY) {
        window.__MELON_LITE_ADMIN_CENTER_SEARCH_READY = true;
        document.addEventListener('melonlite:page-ready', function () {
            if (window.MelonLiteInitAdminCenter) window.MelonLiteInitAdminCenter();
        });
    }
})();
</script>
<?php renderFooter(); ?>
