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

$pdo = getDBConnection();
$groups = [];
$seen = [];
$criteria = [
    'hash' => [
        'label' => '같은 파일 해시',
        'sql' => "SELECT file_hash AS group_key, COUNT(*) AS cnt FROM songs WHERE file_hash IS NOT NULL AND file_hash != '' GROUP BY file_hash HAVING cnt > 1 LIMIT 20",
        'where' => 's.file_hash = :group_key',
    ],
    'size_title_artist' => [
        'label' => '같은 크기 + 제목 + 아티스트',
        'sql' => "SELECT CONCAT(file_size, '||', COALESCE(title,''), '||', COALESCE(artist,'')) AS group_key, COUNT(*) AS cnt FROM songs WHERE file_size > 0 AND title IS NOT NULL AND title != '' GROUP BY group_key HAVING cnt > 1 LIMIT 20",
        'where' => "CONCAT(s.file_size, '||', COALESCE(s.title,''), '||', COALESCE(s.artist,'')) = :group_key",
    ],
    'title_artist_duration' => [
        'label' => '같은 제목 + 아티스트 + 재생시간',
        'sql' => "SELECT CONCAT(COALESCE(title,''), '||', COALESCE(artist,''), '||', COALESCE(duration,0)) AS group_key, COUNT(*) AS cnt FROM songs WHERE title IS NOT NULL AND title != '' AND duration > 0 GROUP BY group_key HAVING cnt > 1 LIMIT 20",
        'where' => "CONCAT(COALESCE(s.title,''), '||', COALESCE(s.artist,''), '||', COALESCE(s.duration,0)) = :group_key",
    ],
    'filename' => [
        'label' => '같은 파일명',
        'sql' => "SELECT SUBSTRING_INDEX(REPLACE(file_path, '\\\\', '/'), '/', -1) AS group_key, COUNT(*) AS cnt FROM songs GROUP BY group_key HAVING cnt > 1 LIMIT 20",
        'where' => "SUBSTRING_INDEX(REPLACE(s.file_path, '\\\\', '/'), '/', -1) = :group_key",
    ],
];

foreach ($criteria as $type => $criterion) {
    foreach ($pdo->query($criterion['sql'])->fetchAll() as $row) {
        $groupKey = (string)$row['group_key'];
        if ($groupKey === '') continue;
        $seenKey = $type . '|' . $groupKey;
        if (isset($seen[$seenKey])) continue;
        $seen[$seenKey] = true;

        $stmt = $pdo->prepare(baseSongSelectSql() . " WHERE " . $criterion['where'] . " ORDER BY s.folder_name ASC, s.title ASC LIMIT 30");
        $stmt->execute([':group_key' => $groupKey]);
        $songs = $stmt->fetchAll();
        if (count($songs) > 1) {
            $groups[] = [
                'type' => $criterion['label'],
                'count' => count($songs),
                'songs' => $songs,
            ];
        }
    }
}

renderHeader('중복곡 관리', 'duplicates');
?>
<div class="admin-dashboard duplicates-page">
    <div class="page-title-section">
        <h1 class="page-main-title">중복곡 관리</h1>
        <p class="page-subtitle">같은 파일이거나 같은 곡으로 보이는 항목을 확인합니다. 안전을 위해 실제 파일 삭제는 하지 않습니다.</p>
    </div>

    <?php if (empty($groups)): ?>
        <section class="home-section"><p class="empty-text">중복 의심 그룹이 없습니다.</p></section>
    <?php else: ?>
        <?php foreach ($groups as $group): ?>
            <section class="home-section duplicate-group">
                <div class="section-heading-row">
                    <h2 class="section-title"><?php echo h($group['type']); ?> · <?php echo number_format($group['count']); ?>곡</h2>
                </div>
                <?php renderSongList($group['songs'], ['show_play_actions' => true, 'queue_context' => 'duplicates']); ?>
            </section>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
