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

$pdo = getDBConnection();
$filter = (string)($_GET['filter'] ?? 'needs_review');
$allowedFilters = [
    'needs_review' => '정리 필요',
    'title_suspicious' => '제목 의심',
    'unknown_artist' => '아티스트 미상',
    'unknown_album' => '앨범 미상',
    'missing_genre' => '장르 누락',
    'manual' => '수동 보호',
];
if (!isset($allowedFilters[$filter])) $filter = 'needs_review';

$where = ["COALESCE(is_missing, 0) = 0"];
if ($filter === 'title_suspicious') {
    $where[] = "(title REGEXP '^[0-9]+[. -]+' OR title LIKE '%.mp3' OR title LIKE '%.flac' OR title LIKE '%.wav' OR title LIKE '%.m4a')";
} elseif ($filter === 'unknown_artist') {
    $where[] = "(artist IS NULL OR TRIM(artist) = '' OR LOWER(TRIM(artist)) IN ('unknown', '알 수 없음', '미상'))";
} elseif ($filter === 'unknown_album') {
    $where[] = "(album IS NULL OR TRIM(album) = '' OR LOWER(TRIM(album)) IN ('unknown', '알 수 없음', '미상'))";
} elseif ($filter === 'missing_genre') {
    $where[] = "(genre IS NULL OR TRIM(genre) = '' OR LOWER(TRIM(genre)) = 'unknown')";
} elseif ($filter === 'manual') {
    $where[] = "COALESCE(is_manual_edited, 0) = 1";
} else {
    $where[] = "(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 title REGEXP '^[0-9]+[. -]+')";
}

$songs = [];
try {
    $sql = "
        SELECT id, title, artist, album, genre, folder_name, relative_path, file_path, is_manual_edited
        FROM songs
        WHERE " . implode(' AND ', $where) . "
        ORDER BY id DESC
        LIMIT 100
    ";
    $songs = $pdo->query($sql)->fetchAll();
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'metadata_error', 'Metadata quality query failed', ['filter' => $filter, 'error' => $e->getMessage()]);
}

renderHeader('메타데이터 품질', 'metadata_quality');
?>
<div class="metadata-quality-page">
    <div class="page-title-section">
        <h1 class="page-main-title">메타데이터 품질</h1>
        <p class="page-subtitle">getID3 없이도 파일명과 폴더명을 참고해 정리 후보를 확인합니다. 자동 덮어쓰기는 하지 않습니다.</p>
    </div>

    <section class="home-section">
        <div class="filter-tabs">
            <?php foreach ($allowedFilters as $key => $label): ?>
                <a class="filter-tab <?php echo $filter === $key ? 'active' : ''; ?>" href="metadata_quality.php?filter=<?php echo h($key); ?>"><?php echo h($label); ?></a>
            <?php endforeach; ?>
        </div>
    </section>

    <section class="home-section">
        <div class="section-heading-row">
            <h2 class="section-title"><?php echo h($allowedFilters[$filter]); ?> 목록</h2>
            <span class="settings-muted"><?php echo number_format(count($songs)); ?>곡</span>
        </div>
        <?php if (empty($songs)): ?>
            <p class="empty-text">정리 후보가 없습니다.</p>
        <?php else: ?>
            <div class="metadata-quality-list">
                <?php foreach ($songs as $song): $suggest = smartMetadataSuggestion($song); ?>
                    <article class="metadata-quality-card">
                        <div>
                            <strong><?php echo h($song['title'] ?: '(제목 없음)'); ?></strong>
                            <p><?php echo h($song['artist'] ?: '아티스트 없음'); ?> / <?php echo h($song['album'] ?: '앨범 없음'); ?> / <?php echo h($song['genre'] ?: '장르 없음'); ?></p>
                            <p class="settings-muted">폴더: <?php echo h($song['folder_name'] ?: '-'); ?><?php echo !empty($song['is_manual_edited']) ? ' / 수동 보호' : ''; ?></p>
                        </div>
                        <div class="metadata-suggestion-box">
                            <span>제안 제목: <strong><?php echo h($suggest['title'] ?: '-'); ?></strong></span>
                            <span>제안 아티스트: <strong><?php echo h($suggest['artist'] ?: '-'); ?></strong></span>
                            <span>제안 앨범: <strong><?php echo h($suggest['album'] ?: '-'); ?></strong></span>
                        </div>
                        <a class="btn btn-secondary btn-sm" href="../song_edit.php?id=<?php echo h($song['id']); ?>">직접 수정</a>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</div>
<?php renderFooter(); ?>
