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

ensureTagTables();
$pdo = getDBConnection();

function smartCount($sql, $params = []) {
    try {
        $stmt = getDBConnection()->prepare($sql);
        $stmt->execute($params);
        return (int)$stmt->fetchColumn();
    } catch (Throwable $e) {
        if (function_exists('writeAppLog')) writeAppLog('error', 'db_error', 'Smart organize count failed', ['error' => $e->getMessage()]);
        return 0;
    }
}

$totalSongs = smartCount("SELECT COUNT(*) FROM songs");
$missingTitle = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(NULLIF(TRIM(title), ''), '') = ''");
$missingArtist = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(NULLIF(TRIM(artist), ''), '') = '' OR LOWER(TRIM(artist)) IN ('unknown', '알 수 없음', '미상')");
$missingAlbum = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(NULLIF(TRIM(album), ''), '') = '' OR LOWER(TRIM(album)) IN ('unknown', '알 수 없음', '미상')");
$missingGenre = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(NULLIF(TRIM(genre), ''), '') = '' OR LOWER(TRIM(genre)) = 'unknown'");
$missingCover = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(has_cover, 0) = 0");
$missingFiles = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(is_missing, 0) = 1");
$manualEdited = smartCount("SELECT COUNT(*) FROM songs WHERE COALESCE(is_manual_edited, 0) = 1");
$untagged = smartCount("SELECT COUNT(*) FROM songs s LEFT JOIN song_tags st ON st.song_id = s.id WHERE st.id IS NULL");
$titleSuspicious = smartCount("SELECT COUNT(*) FROM songs WHERE title REGEXP '^[0-9]+[. -]+' OR title LIKE '%.mp3' OR title LIKE '%.flac' OR title LIKE '%.wav' OR title LIKE '%.m4a'");
$duplicateSuspects = smartCount("
    SELECT COUNT(*) FROM (
        SELECT COALESCE(NULLIF(file_hash, ''), CONCAT(file_size, ':', LOWER(TRIM(title)), ':', LOWER(TRIM(artist)))) AS marker
        FROM songs
        GROUP BY marker
        HAVING COUNT(*) > 1
    ) d
");

$artistVariants = [];
$genreSpread = [];
$recentNeeds = [];
try {
    $artistVariants = $pdo->query("
        SELECT TRIM(LOWER(artist)) AS normalized, GROUP_CONCAT(DISTINCT artist ORDER BY artist SEPARATOR ' / ') AS names, COUNT(*) AS song_count
        FROM songs
        WHERE artist IS NOT NULL AND TRIM(artist) != ''
        GROUP BY normalized
        HAVING COUNT(DISTINCT artist) > 1
        ORDER BY song_count DESC
        LIMIT 8
    ")->fetchAll();
    $genreSpread = $pdo->query("
        SELECT genre, COUNT(*) AS song_count
        FROM songs
        WHERE genre IS NOT NULL AND TRIM(genre) != ''
        GROUP BY genre
        ORDER BY song_count ASC, genre ASC
        LIMIT 12
    ")->fetchAll();
    $recentNeeds = $pdo->query("
        SELECT id, title, artist, album, genre, folder_name, relative_path, is_manual_edited
        FROM songs
        WHERE COALESCE(is_missing, 0) = 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) = '')
        ORDER BY id DESC
        LIMIT 12
    ")->fetchAll();
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) writeAppLog('error', 'db_error', 'Smart organize list failed', ['error' => $e->getMessage()]);
}

$cards = [
    ['label' => '전체 등록 곡', 'value' => $totalSongs, 'href' => '../index.php?view=all'],
    ['label' => '제목 누락', 'value' => $missingTitle, 'href' => 'metadata.php?filter=missing_title'],
    ['label' => '아티스트 누락', 'value' => $missingArtist, 'href' => 'metadata.php?filter=missing_artist'],
    ['label' => '앨범 누락', 'value' => $missingAlbum, 'href' => 'metadata.php?filter=missing_album'],
    ['label' => '장르 누락', 'value' => $missingGenre, 'href' => 'metadata.php?filter=missing_genre'],
    ['label' => '앨범아트 없음', 'value' => $missingCover, 'href' => 'metadata.php?filter=no_cover'],
    ['label' => '파일 없음', 'value' => $missingFiles, 'href' => 'missing_files.php'],
    ['label' => '중복 의심', 'value' => $duplicateSuspects, 'href' => 'duplicates.php'],
    ['label' => '제목 정리 의심', 'value' => $titleSuspicious, 'href' => 'metadata_quality.php?filter=title_suspicious'],
    ['label' => '태그 없는 곡', 'value' => $untagged, 'href' => 'tag_manage.php'],
    ['label' => '수동 수정 보호', 'value' => $manualEdited, 'href' => 'metadata.php?filter=manual'],
];

renderHeader('스마트 정리', 'smart_organize');
?>
<div class="smart-organize-page">
    <div class="page-title-section">
        <h1 class="page-main-title">스마트 정리</h1>
        <p class="page-subtitle">파일명, 폴더명, 기존 DB 값을 기준으로 정리가 필요한 보관함 항목을 모아봅니다.</p>
    </div>

    <section class="home-section">
        <p class="settings-muted">getID3 미설치 상태에서는 내부 태그 분석이 제한되며, 현재 화면은 파일명/폴더명/DB 값 기반 제안을 사용합니다.</p>
    </section>

    <div class="smart-card-grid">
        <?php foreach ($cards as $card): ?>
            <a class="smart-summary-card" href="<?php echo h($card['href']); ?>">
                <span><?php echo h($card['label']); ?></span>
                <strong><?php echo number_format((int)$card['value']); ?></strong>
            </a>
        <?php endforeach; ?>
    </div>

    <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="metadata_quality.php">제안 보기</a></div>
            <div class="admin-log-list">
                <?php if (empty($recentNeeds)): ?>
                    <p class="empty-text">정리할 항목이 없습니다.</p>
                <?php else: foreach ($recentNeeds as $song): $suggest = smartMetadataSuggestion($song); ?>
                    <div class="admin-log-row">
                        <strong><?php echo h($song['title'] ?: '(제목 없음)'); ?></strong>
                        <span><?php echo h($song['artist'] ?: '아티스트 없음'); ?> / <?php echo h($song['album'] ?: '앨범 없음'); ?></span>
                        <p>제안: <?php echo h($suggest['artist'] ?: '-'); ?> - <?php echo h($suggest['title'] ?: '-'); ?><?php echo !empty($song['is_manual_edited']) ? ' / 수동 보호' : ''; ?></p>
                        <a class="btn btn-secondary btn-sm" href="../song_edit.php?id=<?php echo h($song['id']); ?>">수정</a>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </section>

        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">아티스트 표기 차이 의심</h2><a class="section-more-link" href="name_merge.php?field=artist">통합 도구</a></div>
            <div class="admin-log-list">
                <?php if (empty($artistVariants)): ?>
                    <p class="empty-text">표기 차이 의심 항목이 없습니다.</p>
                <?php else: foreach ($artistVariants as $row): ?>
                    <div class="admin-log-row">
                        <strong><?php echo h($row['names']); ?></strong>
                        <span><?php echo number_format((int)$row['song_count']); ?>곡</span>
                    </div>
                <?php endforeach; endif; ?>
            </div>
        </section>

        <section class="home-section">
            <div class="section-heading-row"><h2 class="section-title">작게 흩어진 장르</h2><a class="section-more-link" href="name_merge.php?field=genre">장르 통합</a></div>
            <div class="tag-cloud">
                <?php if (empty($genreSpread)): ?>
                    <p class="empty-text">장르 데이터가 부족합니다.</p>
                <?php else: foreach ($genreSpread as $genre): ?>
                    <span class="tag-badge"><?php echo h($genre['genre']); ?> (<?php echo number_format((int)$genre['song_count']); ?>)</span>
                <?php endforeach; endif; ?>
            </div>
        </section>
    </div>
</div>
<?php renderFooter(); ?>
