<?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';
requirePermission('music_scan');

$pdo = getDBConnection();
$scanPath = getScanPathSetting();
$winScanPath = toWinPath($scanPath);
$dirExists = is_dir($winScanPath);

$totalSongs = (int)$pdo->query("SELECT COUNT(*) FROM songs WHERE is_missing = 0")->fetchColumn();
$allScannedSongs = (int)$pdo->query("SELECT COUNT(*) FROM songs")->fetchColumn();
$missingFiles = (int)$pdo->query("SELECT COUNT(*) FROM songs WHERE is_missing = 1")->fetchColumn();
$metadataMissing = (int)$pdo->query("
    SELECT COUNT(*) FROM songs
    WHERE is_missing = 0 AND (
        title IS NULL OR TRIM(title) = ''
        OR artist IS NULL OR TRIM(artist) = ''
        OR album IS NULL OR TRIM(album) = ''
        OR genre IS NULL OR TRIM(genre) = ''
        OR year IS NULL OR TRIM(year) = ''
        OR duration IS NULL OR duration <= 0
        OR cover_hash IS NULL OR TRIM(cover_hash) = ''
    )
")->fetchColumn();

$lastScanStmt = $pdo->query("
    SELECT * FROM scan_logs
    WHERE scan_finished_at IS NOT NULL
    ORDER BY id DESC LIMIT 1
");
$lastScan = $lastScanStmt->fetch();
$recentLogs = $pdo->query("SELECT * FROM scan_logs ORDER BY id DESC LIMIT 10")->fetchAll();

$errorLogs = [];
$logFilePath = dirname(__DIR__) . '/storage/logs/scan.log';
if (file_exists($logFilePath)) {
    $logLines = file($logFilePath);
    if ($logLines) {
        foreach (array_reverse($logLines) as $line) {
            if (strpos($line, '[WARNING]') !== false || strpos($line, '[ERROR]') !== false) {
                $errorLogs[] = trim($line);
                if (count($errorLogs) >= 8) break;
            }
        }
    }
}

$shouldAutoScan = false;
$secondsSinceLastScan = 999999;
if ($dirExists) {
    $autoScanEnabled = settingBool('scan_auto_enabled', true);
    $autoScanIntervalSeconds = settingInt('scan_auto_interval_minutes', 10, 1, 1440) * 60;
    if (!$lastScan) {
        $shouldAutoScan = $autoScanEnabled;
    } else {
        $secondsSinceLastScan = time() - strtotime($lastScan['scan_finished_at']);
        $shouldAutoScan = $autoScanEnabled && $secondsSinceLastScan >= $autoScanIntervalSeconds;
    }
}

renderHeader('관리자 스캔', 'scan');
?>
<div class="admin-dashboard">
    <div class="page-title-section">
        <h1 class="page-main-title">음악 라이브러리 스캔 관리</h1>
        <p class="page-subtitle">음악 저장소를 스캔하고 누락 파일과 메타데이터 상태를 확인합니다.</p>
    </div>

    <?php if (!$dirExists): ?>
        <div class="alert-box alert-danger">
            <div class="alert-icon"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="alert-content">
                <h3>설정된 음악 폴더를 찾을 수 없습니다.</h3>
                <p><code>config/config.php</code>의 <strong>MUSIC_SCAN_PATH</strong> 값을 확인하세요.</p>
                <p class="current-path-info">현재 설정값: <span><?php echo h($scanPath); ?></span></p>
            </div>
        </div>
    <?php else: ?>
        <?php if ($shouldAutoScan): ?>
            <div class="alert-box alert-info" id="auto-scan-banner">
                <div class="alert-icon"><i class="fas fa-magic spinner-icon"></i></div>
                <div class="alert-content">
                    <h3>자동 스캔 실행 중</h3>
                    <p>설정된 자동 스캔 간격이 지나 자동으로 스캔을 시작합니다.</p>
                </div>
            </div>
        <?php endif; ?>

        <div class="dashboard-grid">
            <div class="stats-card">
                <div class="card-icon"><i class="fas fa-folder-open"></i></div>
                <div class="card-info">
                    <span class="card-label">스캔 대상 폴더</span>
                    <span class="card-value path-value" title="<?php echo h($scanPath); ?>"><?php echo h($scanPath); ?></span>
                </div>
            </div>
            <div class="stats-card">
                <div class="card-icon"><i class="fas fa-music"></i></div>
                <div class="card-info">
                    <span class="card-label">현재 존재하는 파일 수</span>
                    <span class="card-value"><?php echo number_format($totalSongs); ?> 곡</span>
                </div>
            </div>
            <div class="stats-card">
                <div class="card-icon"><i class="fas fa-database"></i></div>
                <div class="card-info">
                    <span class="card-label">전체 스캔된 곡 수</span>
                    <span class="card-value"><?php echo number_format($allScannedSongs); ?> 곡</span>
                </div>
            </div>
            <div class="stats-card">
                <div class="card-icon"><i class="fas fa-link-slash"></i></div>
                <div class="card-info">
                    <span class="card-label">파일이 사라진 곡 수</span>
                    <span class="card-value"><?php echo number_format($missingFiles); ?> 곡</span>
                </div>
            </div>
            <a class="stats-card stats-card-link" href="metadata.php">
                <div class="card-icon"><i class="fas fa-triangle-exclamation"></i></div>
                <div class="card-info">
                    <span class="card-label">메타데이터 누락 곡 수</span>
                    <span class="card-value"><?php echo number_format($metadataMissing); ?> 곡</span>
                </div>
            </a>
            <div class="stats-card">
                <div class="card-icon"><i class="fas fa-clock"></i></div>
                <div class="card-info">
                    <span class="card-label">최근 스캔 시간</span>
                    <span class="card-value"><?php echo $lastScan ? h($lastScan['scan_finished_at']) : '기록 없음'; ?></span>
                </div>
            </div>
        </div>

        <div class="scan-action-section">
            <div class="scan-status-summary">
                <h3>최근 스캔 결과</h3>
                <p class="scan-msg"><?php echo $lastScan ? h($lastScan['message']) : '아직 스캔 기록이 없습니다.'; ?></p>
            </div>
            <div class="scan-button-group">
                <button type="button" class="btn btn-primary" id="btn-manual-scan">
                    <i class="fas fa-sync-alt btn-icon"></i>
                    <span id="btn-scan-text">수동 스캔 시작</span>
                </button>
                <?php if (!$shouldAutoScan && $lastScan): ?>
                    <span class="scan-countdown-info">
                        <i class="fas fa-info-circle"></i>
                        다음 자동 스캔까지 약 <strong><?php echo max(1, ceil(($autoScanIntervalSeconds - $secondsSinceLastScan) / 60)); ?>분</strong>
                    </span>
                <?php endif; ?>
            </div>
        </div>

        <div class="logs-section">
            <h2 class="section-title"><i class="fas fa-list-alt title-icon"></i> 최근 스캔 기록</h2>
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>ID</th><th>시작</th><th>완료</th><th>발견</th><th>신규</th><th>갱신</th><th>파일 없음</th><th>메시지</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($recentLogs)): ?>
                            <tr><td colspan="8" class="text-center">최근 스캔 기록이 없습니다.</td></tr>
                        <?php else: ?>
                            <?php foreach ($recentLogs as $log): ?>
                                <tr>
                                    <td><?php echo h($log['id']); ?></td>
                                    <td><?php echo h($log['scan_started_at']); ?></td>
                                    <td><?php echo h($log['scan_finished_at'] ?? '-'); ?></td>
                                    <td><?php echo h($log['total_found']); ?></td>
                                    <td class="text-success"><?php echo h($log['new_count']); ?></td>
                                    <td class="text-info"><?php echo h($log['updated_count']); ?></td>
                                    <td class="text-warning"><?php echo h($log['deleted_count']); ?></td>
                                    <td class="log-message-td"><?php echo h($log['message']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="logs-section">
            <h2 class="section-title"><i class="fas fa-exclamation-circle title-icon"></i> 최근 스캔 오류</h2>
            <div class="error-log-console">
                <?php if (empty($errorLogs)): ?>
                    <p class="empty-text">최근 스캔 오류가 없습니다.</p>
                <?php else: ?>
                    <?php foreach ($errorLogs as $err): ?>
                        <div><?php echo h($err); ?></div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const btnScan = document.getElementById('btn-manual-scan');
    const btnText = document.getElementById('btn-scan-text');

    function runScan() {
        if (btnScan) {
            btnScan.disabled = true;
            btnScan.classList.add('loading');
        }
        if (btnText) btnText.innerText = '스캔 진행 중...';

        fetch('../scan.php', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'X-CSRF-Token': window.APP_CSRF_TOKEN || ''
            }
        })
            .then(response => {
                if (!response.ok) throw new Error('HTTP 오류 ' + response.status);
                return response.json();
            })
            .then(data => {
                alert((data.success ? '스캔 완료' : '스캔 실패') + '\n' + (data.message || ''));
                location.reload();
            })
            .catch(error => {
                console.error('Scan Error:', error);
                alert('스캔 처리 중 오류가 발생했습니다: ' + error.message);
                location.reload();
            });
    }

    if (btnScan) {
        btnScan.addEventListener('click', function() {
            if (confirm('음악 폴더를 다시 스캔할까요? 파일이 많으면 시간이 걸릴 수 있습니다.')) {
                runScan();
            }
        });
    }

    <?php if ($shouldAutoScan && $dirExists): ?>
    setTimeout(runScan, 500);
    <?php endif; ?>
});
</script>
<?php renderFooter(); ?>
