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

$pdo = getDBConnection();
$filter = isset($_GET['type']) ? $_GET['type'] : 'all';
$message = isset($_GET['message']) ? trim($_GET['message']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : 'success';

$missingTypes = [
    'title' => ['label' => '제목 없음', 'sql' => "s.title IS NULL OR TRIM(s.title) = ''"],
    'artist' => ['label' => '아티스트 없음', 'sql' => "s.artist IS NULL OR TRIM(s.artist) = ''"],
    'album' => ['label' => '앨범 없음', 'sql' => "s.album IS NULL OR TRIM(s.album) = ''"],
    'genre' => ['label' => '장르 없음', 'sql' => "s.genre IS NULL OR TRIM(s.genre) = ''"],
    'year' => ['label' => '연도 없음', 'sql' => "s.year IS NULL OR TRIM(s.year) = ''"],
    'cover' => ['label' => '앨범아트 없음', 'sql' => "COALESCE(s.has_cover, 0) = 0 AND (s.cover_hash IS NULL OR TRIM(s.cover_hash) = '')"],
    'duration' => ['label' => '재생시간 없음', 'sql' => "s.duration IS NULL OR s.duration <= 0"],
    'error' => ['label' => '분석 오류', 'sql' => "s.metadata_error IS NOT NULL AND TRIM(s.metadata_error) != ''"],
    'manual' => ['label' => '수동 보호', 'sql' => "s.is_manual_edited = 1"],
    'filename' => ['label' => '파일명 fallback', 'sql' => "s.metadata_source = 'filename' OR s.metadata_source = 'mixed'"],
    'missing_file' => ['label' => '파일 없음', 'sql' => "s.is_missing = 1"],
];

$missingOnly = array_slice($missingTypes, 0, 7);
$allMissingSql = implode(' OR ', array_map(function ($row) { return '(' . $row['sql'] . ')'; }, $missingOnly));
$where = 's.is_missing = 0 AND (' . $allMissingSql . ')';
if (isset($missingTypes[$filter])) {
    $where = ($filter === 'missing_file' ? '1 = 1' : 's.is_missing = 0') . ' AND (' . $missingTypes[$filter]['sql'] . ')';
}

$stmt = $pdo->prepare("
    SELECT s.id, s.title, s.artist, s.album, s.genre, s.year, s.duration, s.cover_hash,
           s.has_cover, s.cover_mime, s.extension, s.play_count, s.metadata_source, s.metadata_error,
           s.is_manual_edited, s.metadata_updated_at, s.last_metadata_scan_at, s.file_mtime, s.is_missing
    FROM songs s
    WHERE $where
    ORDER BY s.id DESC
    LIMIT 300
");
$stmt->execute();
$songs = $stmt->fetchAll();

renderHeader('메타데이터 관리', 'metadata');
?>
<div class="admin-dashboard">
    <div class="page-title-section">
        <h1 class="page-main-title">메타데이터 관리</h1>
        <p class="page-subtitle">파일 내부 태그 우선 재분석, 누락 항목 확인, 수동 수정 보호를 관리합니다.</p>
    </div>

    <?php if ($message !== ''): ?>
        <div class="alert-box <?php echo $status === 'error' ? 'alert-danger' : 'alert-info'; ?>">
            <div class="alert-icon"><i class="fas fa-circle-info"></i></div>
            <div class="alert-content"><p><?php echo h($message); ?></p></div>
        </div>
    <?php endif; ?>

    <section class="settings-card metadata-tools">
        <h2>메타데이터 재분석</h2>
        <form action="metadata_action.php" method="POST" class="maintenance-actions">
            <?php echo csrfInput(); ?>
            <button name="action" value="reanalyze_missing" class="btn btn-secondary" onclick="return confirm('누락 곡을 파일 내부 태그 기준으로 다시 읽을까요?');">누락 곡 재분석</button>
            <button name="action" value="reanalyze_errors" class="btn btn-secondary" onclick="return confirm('오류 발생 곡을 다시 분석할까요?');">오류 곡 재분석</button>
            <button name="action" value="reanalyze_non_manual" class="btn btn-secondary" onclick="return confirm('수동 보호 곡을 제외하고 최대 100곡을 재분석할까요?');">수동 보호 제외 재분석</button>
            <button name="action" value="reanalyze_all" class="btn btn-secondary" onclick="return confirm('최대 100곡을 재분석합니다. 계속할까요?');">전체 재분석</button>
            <button name="action" value="reanalyze_cover" class="btn btn-secondary" onclick="return confirm('앨범아트만 다시 추출할까요?');">앨범아트만 재추출</button>
            <button name="action" value="reanalyze_technical" class="btn btn-secondary" onclick="return confirm('재생시간/비트레이트 등 기술 정보만 다시 분석할까요?');">기술 정보만 재분석</button>
            <button name="action" value="reanalyze_force" class="btn btn-danger" onclick="return confirm('수동 수정값도 파일 내부 태그로 덮어쓸 수 있습니다. 계속할까요?');">강제 재분석</button>
        </form>
        <p class="settings-muted">대량 작업은 한 번에 최대 100곡까지만 처리합니다.</p>
    </section>

    <div class="filter-left metadata-filter-tabs">
        <a href="metadata.php" class="filter-tab <?php echo $filter === 'all' ? 'active' : ''; ?>">전체</a>
        <?php foreach ($missingTypes as $key => $type): ?>
            <a href="metadata.php?type=<?php echo h($key); ?>" class="filter-tab <?php echo $filter === $key ? 'active' : ''; ?>"><?php echo h($type['label']); ?></a>
        <?php endforeach; ?>
    </div>

    <form action="metadata_action.php" method="POST" id="metadata-selected-form"><?php echo csrfInput(); ?></form>
    <div class="metadata-bulk-actions">
        <button form="metadata-selected-form" name="action" value="reanalyze_selected" class="btn btn-secondary btn-sm" onclick="return confirm('선택한 곡을 재분석할까요?');">선택 곡 재분석</button>
    </div>
    <div class="table-container metadata-table-container">
        <table class="data-table metadata-table">
            <thead>
                <tr>
                    <th class="text-center">선택</th>
                    <th>곡</th>
                    <th>아티스트</th>
                    <th>앨범</th>
                    <th>누락/상태</th>
                    <th>소스</th>
                    <th>관리</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($songs)): ?>
                    <tr><td colspan="7" class="text-center">표시할 메타데이터 항목이 없습니다.</td></tr>
                <?php else: ?>
                    <?php foreach ($songs as $song): ?>
                        <?php
                        $badges = [];
                        if (trim((string)$song['title']) === '') $badges[] = '제목';
                        if (trim((string)$song['artist']) === '') $badges[] = '아티스트';
                        if (trim((string)$song['album']) === '') $badges[] = '앨범';
                        if (trim((string)$song['genre']) === '') $badges[] = '장르';
                        if (trim((string)$song['year']) === '') $badges[] = '연도';
                        if (empty($song['has_cover']) && trim((string)$song['cover_hash']) === '') $badges[] = '앨범아트';
                        if (empty($song['duration'])) $badges[] = '재생시간';
                        if (!empty($song['metadata_error'])) $badges[] = '오류';
                        if (!empty($song['is_manual_edited'])) $badges[] = '수동 보호';
                        if (($song['metadata_source'] ?? '') === 'filename') $badges[] = '파일명';
                        if (($song['metadata_source'] ?? '') === 'mixed') $badges[] = '혼합';
                        if (!empty($song['is_missing'])) $badges[] = '파일 없음';
                        ?>
                        <tr>
                            <td class="text-center"><input form="metadata-selected-form" type="checkbox" name="song_ids[]" value="<?php echo h($song['id']); ?>"></td>
                            <td><a href="../song.php?id=<?php echo h($song['id']); ?>" class="song-title-link"><?php echo h(metaValue($song['title'], '제목 없음')); ?></a></td>
                            <td><?php echo h(metaValue($song['artist'], '-')); ?></td>
                            <td><?php echo h(metaValue($song['album'], '-')); ?></td>
                            <td>
                                <?php foreach ($badges as $badge): ?>
                                    <span class="metadata-badge"><?php echo h($badge); ?></span>
                                <?php endforeach; ?>
                                <?php if (!empty($song['metadata_error'])): ?>
                                    <small class="metadata-error"><?php echo h($song['metadata_error']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo h(metaValue($song['metadata_source'], '-')); ?><br>
                                <small>갱신: <?php echo h($song['metadata_updated_at']); ?></small><br>
                                <small>스캔: <?php echo h($song['last_metadata_scan_at']); ?></small>
                            </td>
                            <td>
                                <div class="song-action-group">
                                    <a href="../song_edit.php?id=<?php echo h($song['id']); ?>" class="btn btn-secondary btn-sm">수정</a>
                                    <form action="metadata_action.php" method="POST" class="inline-action-form">
                                        <?php echo csrfInput(); ?>
                                        <input type="hidden" name="song_id" value="<?php echo h($song['id']); ?>">
                                        <button name="action" value="reanalyze_one" class="btn btn-secondary btn-sm">다시 읽기</button>
                                        <?php if (!empty($song['is_manual_edited'])): ?>
                                            <button name="action" value="manual_off" class="btn btn-secondary btn-sm">보호 해제</button>
                                        <?php else: ?>
                                            <button name="action" value="manual_on" class="btn btn-secondary btn-sm">보호 설정</button>
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="metadata-card-list">
        <?php foreach ($songs as $song): ?>
            <article class="metadata-mobile-card">
                <strong><?php echo h(metaValue($song['title'], '제목 없음')); ?></strong>
                <span><?php echo h(metaValue($song['artist'], '-')); ?> · <?php echo h(metaValue($song['album'], '-')); ?></span>
                <small>출처: <?php echo h(metaValue($song['metadata_source'], '-')); ?> · 스캔: <?php echo h($song['last_metadata_scan_at'] ?: '-'); ?></small>
                <?php if (!empty($song['metadata_error'])): ?><p class="metadata-error"><?php echo h($song['metadata_error']); ?></p><?php endif; ?>
                <div class="song-action-group">
                    <a href="../song_edit.php?id=<?php echo h($song['id']); ?>" class="btn btn-secondary btn-sm">수정</a>
                    <form action="metadata_action.php" method="POST" class="inline-action-form">
                        <?php echo csrfInput(); ?>
                        <input type="hidden" name="song_id" value="<?php echo h($song['id']); ?>">
                        <button name="action" value="reanalyze_one" class="btn btn-secondary btn-sm">다시 읽기</button>
                    </form>
                </div>
            </article>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
