<?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/diagnostics.php';
require_once dirname(__DIR__) . '/includes/stats_functions.php';
requireAdmin();

$pdo = getDBConnection();
$stats = getLibraryStats();
$adminUser = currentAdminUser();
$recentScanLogs = [];
$recentAdminLogs = [];
$recentAppLogs = [];
$diagnosticAlerts = [];
$scanErrorCount = 0;
$duplicateSuspects = 0;
$listeningSummary = getListeningSummary();

try {
    $recentScanLogs = $pdo->query("SELECT * 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 {
    $recentAdminLogs = $pdo->query("
        SELECT l.*, u.username, u.display_name
        FROM admin_logs l
        LEFT JOIN admin_users u ON u.id = l.admin_user_id
        ORDER BY l.id DESC
        LIMIT 30
    ")->fetchAll();
} catch (Exception $e) {
    $recentAdminLogs = [];
}

try {
    $recentAppLogs = $pdo->query("SELECT * FROM app_logs ORDER BY id DESC LIMIT 5")->fetchAll();
    $diagnosticAlerts = array_slice(getDiagnosticAlerts(), 0, 5);
} catch (Exception $e) {
    $recentAppLogs = [];
    $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;
}

$cards = [
    ['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' => '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' => 'metadata.php', 'icon' => 'fa-solid fa-pen-to-square', 'permission' => 'metadata_view'],
    ['title' => '일괄 수정', 'desc' => '여러 곡의 아티스트, 앨범, 장르, 연도 수정', 'href' => 'bulk_edit.php', 'icon' => 'fa-solid fa-table-list', 'permission' => 'metadata_bulk_edit'],
    ['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' => '유지보수', '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'],
];
$cards = array_values(array_filter($cards, function ($card) {
    return empty($card['permission']) || hasPermission($card['permission']);
}));

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($stats['plays'])],
    ]); ?>

    <section class="home-section">
        <div class="section-heading-row"><h2 class="section-title">관리 메뉴</h2></div>
        <div class="admin-card-grid">
            <?php foreach ($cards as $card): ?>
                <a class="admin-hub-card" href="<?php echo h($card['href']); ?>">
                    <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>
    </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($recentAppLogs)): ?>
                    <p class="empty-text">최근 앱 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentAppLogs 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($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($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></div>
            <div class="admin-log-list">
                <?php if (empty($recentAdminLogs)): ?>
                    <p class="empty-text">최근 관리자 작업 로그가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($recentAdminLogs 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($log['message']); ?></p><?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </section>
    </div>
</div>
<?php renderFooter(); ?>
