<?php
/**
 * 음악 상세 정보 보기 페이지 (song.php)
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/functions_tags.php';
require_once __DIR__ . '/includes/functions_notes.php';
require_once __DIR__ . '/includes/layout.php';

$pdo = getDBConnection();
$songId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($songId <= 0) {
    renderHeader('오류');
    ?>
    <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>잘못된 곡 ID 파라미터가 수신되었습니다.</p>
        </div>
    </div>
    <a href="index.php" class="btn btn-secondary">홈으로 돌아가기</a>
    <?php
    renderFooter();
    exit;
}

// 1. 곡 상세 정보 조회 (좋아요 여부 조인 포함)
$sql = "
    SELECT s.*, IF(l.id IS NOT NULL, 1, 0) AS is_liked
    FROM songs s
    LEFT JOIN liked_songs l ON s.id = l.song_id
    WHERE s.id = :id AND s.is_missing = 0
";
$stmt = $pdo->prepare($sql);
$stmt->execute([':id' => $songId]);
$song = $stmt->fetch();

if (!$song) {
    renderHeader('곡 정보 없음');
    ?>
    <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>존재하지 않는 곡이거나 스캔 디렉토리에서 소실되어 제외 상태입니다.</p>
        </div>
    </div>
    <a href="index.php" class="btn btn-secondary">홈으로 돌아가기</a>
    <?php
    renderFooter();
    exit;
}

// 2. 최근 재생 50곡 리스트에 포함되어 있는지 판단
$recentCheckStmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM (
        SELECT song_id 
        FROM play_history 
        GROUP BY song_id 
        ORDER BY MAX(played_at) DESC 
        LIMIT 50
    ) tmp 
    WHERE tmp.song_id = :song_id
");
$recentCheckStmt->execute([':song_id' => $songId]);
$isRecentlyPlayed = $recentCheckStmt->fetchColumn() > 0;

// 3. 가사 데이터 조회
$lyricsText = '';
$lyricsQuery = $pdo->prepare("SELECT lyrics_text FROM lyrics WHERE song_id = :song_id");
$lyricsQuery->execute([':song_id' => $songId]);
$lyricsRow = $lyricsQuery->fetch();
if ($lyricsRow) {
    $lyricsText = $lyricsRow['lyrics_text'];
}

$songTags = getSongTags($songId);
$popularTags = getPopularTags(12);
$songNote = getSongNote($songId);
$songRating = getSongRating($songId);

// 바이트 크기 포맷팅 로컬 함수
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

renderHeader($song['title'] . ' 정보', 'all');
?>

<div class="song-detail-page">
    <div class="page-title-section">
        <h1 class="page-main-title">곡 상세 정보</h1>
        <p class="page-subtitle">선택하신 음악 파일의 수집된 태그 메타데이터 및 통계를 확인합니다.</p>
    </div>

    <!-- 상세 보기 반응형 레이아웃 카드 -->
    <div class="song-detail-container" style="display: flex; gap: 32px; flex-wrap: wrap; margin-bottom: 30px;">
        <!-- 좌측: 대형 앨범아트 카드 -->
        <div class="song-detail-art-card" style="flex: 1; min-width: 280px; max-width: 360px; background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 20px;">
            <div class="album-art-large" style="width: 220px; height: 220px; border-radius: 12px; overflow: hidden; border: 2px solid var(--border-color); box-shadow: 0 8px 24px rgba(0,0,0,0.5);">
                <img src="cover.php?id=<?php echo $song['id']; ?>" alt="Cover" width="320" height="320" style="width:100%; height:100%; object-fit:cover;" onerror="this.onerror=null;this.src='assets/img/default-cover.svg';">
            </div>
            
            <div class="song-art-meta">
                <h3 style="font-size: 18px; font-weight: 700; margin-bottom: 6px; white-space: normal; word-break: break-all;"><?php echo h($song['title']); ?></h3>
                <p style="color: var(--text-secondary); font-size: 14px;"><?php echo h($song['artist'] ?? '알 수 없는 아티스트'); ?></p>
            </div>
            
            <!-- 하단 빠른 조작 인터랙션 버튼 행 (song-item 데이터 속성 바인딩을 통해 플레이어 JS 및 비동기 좋아요 기능 연동 가능) -->
            <div class="song-item" 
                 data-id="<?php echo $song['id']; ?>" 
                 data-title="<?php echo h($song['title']); ?>" 
                 data-artist="<?php echo h($song['artist'] ?? '-'); ?>" 
                 data-duration="<?php echo $song['duration'] ?? 0; ?>"
                 data-liked="<?php echo $song['is_liked']; ?>"
                 style="display: flex; gap: 10px; width: 100%; justify-content: center; align-items: center; margin-top: 10px;">
                
                <button type="button" class="btn btn-primary play-row-btn" style="flex: 2; border-radius: 8px; height: 40px; font-size: 14px;">
                    <i class="fas fa-play"></i> 바로 재생
                </button>
                
                <button type="button" class="btn btn-secondary like-btn <?php echo $song['is_liked'] ? 'liked' : ''; ?>" 
                        style="width: 40px; height: 40px; border-radius: 8px; font-size: 18px; display: inline-flex; justify-content: center; align-items: center;"
                        title="<?php echo $song['is_liked'] ? '좋아요 취소' : '좋아요'; ?>">
                    <i class="<?php echo $song['is_liked'] ? 'fas fa-heart' : 'far fa-heart'; ?>"></i>
                </button>
                
                <button type="button" class="btn btn-secondary add-playlist-btn" 
                        style="width: 40px; height: 40px; border-radius: 8px; font-size: 18px; display: inline-flex; justify-content: center; align-items: center;"
                        title="플레이리스트에 추가">
                    <i class="fas fa-plus"></i>
                </button>
            </div>
        </div>

        <!-- 우측: 메타데이터 상세 표 카드 -->
        <div class="song-detail-info-card" style="flex: 2; min-width: 320px; background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
            <h3 style="font-size: 18px; font-weight: 700; margin-bottom: 20px; border-bottom: 1px solid var(--border-color); padding-bottom: 10px;">
                <i class="fas fa-info-circle" style="color: var(--accent-color);"></i> 상세 스펙 시트
            </h3>
            
            <table class="data-table" style="background:none; border:none; width: 100%; font-size: 14px;">
                <tbody>
                    <tr style="background:none;">
                        <td style="width: 140px; color: var(--text-secondary); font-weight: 600; padding: 12px 0;">곡 제목</td>
                        <td style="padding: 12px 0; color: #fff; font-weight: 600;"><?php echo h($song['title']); ?></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">아티스트</td>
                        <td style="padding: 12px 0;"><?php echo h($song['artist'] ?? '알 수 없는 아티스트'); ?></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">수록 앨범</td>
                        <td style="padding: 12px 0; color: var(--text-secondary);"><?php echo h($song['album'] ?? '정보 없음'); ?></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">음악 장르</td>
                        <td style="padding: 12px 0;"><?php echo h($song['genre'] ?? '정보 없음'); ?></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">발매 연도</td>
                        <td style="padding: 12px 0;"><?php echo h($song['year'] ?? '정보 없음'); ?></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">트랙 번호</td>
                        <td style="padding: 12px 0;"><?php echo $song['track_no'] !== null ? $song['track_no'] . '번 트랙' : '정보 없음'; ?></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">재생 시간</td>
                        <td style="padding: 12px 0;"><?php echo formatDuration($song['duration']); ?> (<?php echo number_format($song['duration'] ?? 0); ?>초)</td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">파일 형식</td>
                        <td style="padding: 12px 0;"><span style="background-color: var(--bg-tertiary); padding: 2px 8px; border-radius: 4px; text-transform: uppercase; font-size: 11px; font-weight: 700; color: var(--text-secondary);"><?php echo h($song['extension']); ?></span></td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">파일 크기</td>
                        <td style="padding: 12px 0; color: var(--text-muted);"><?php echo formatBytes($song['file_size']); ?> (<?php echo number_format($song['file_size']); ?> 바이트)</td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">누적 재생수</td>
                        <td style="padding: 12px 0; font-weight: 600; color: var(--accent-color);"><?php echo number_format($song['play_count']); ?>회</td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">선호 여부</td>
                        <td style="padding: 12px 0; color: <?php echo $song['is_liked'] ? '#ff3b30' : 'var(--text-muted)'; ?>;">
                            <i class="fas fa-heart"></i> <?php echo $song['is_liked'] ? '좋아요 등록됨' : '좋아요 누르지 않음'; ?>
                        </td>
                    </tr>
                    <tr style="background:none; border-top: 1px solid var(--border-color);">
                        <td style="color: var(--text-secondary); font-weight: 600; padding: 12px 0;">최근 감상 여부</td>
                        <td style="padding: 12px 0; color: <?php echo $isRecentlyPlayed ? 'var(--accent-color)' : 'var(--text-muted)'; ?>;">
                            <i class="fas fa-clock"></i> <?php echo $isRecentlyPlayed ? '최근 50곡 내 감상함' : '최근 감상 이력 없음'; ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 가사 보기 및 편집 카드 (3차/4차 가사 연동) -->
    <section class="home-section metadata-status-summary">
        <div class="section-heading-row">
            <h2 class="section-title">메타데이터 상태</h2>
            <a class="section-more-link" href="song_edit.php?id=<?php echo h($song['id']); ?>">수정</a>
        </div>
        <div class="metadata-status-panel">
            <span>출처: <?php echo h(metaValue($song['metadata_source'] ?? '', 'unknown')); ?></span>
            <span>수동 수정 보호: <?php echo !empty($song['is_manual_edited']) ? '켜짐' : '꺼짐'; ?></span>
            <span>마지막 스캔: <?php echo h($song['last_metadata_scan_at'] ?? '-'); ?></span>
            <span>앨범아트: <?php echo !empty($song['has_cover']) ? '있음' : '없음'; ?><?php echo !empty($song['cover_mime']) ? ' (' . h($song['cover_mime']) . ')' : ''; ?></span>
            <?php if (!empty($song['metadata_error'])): ?><p class="metadata-error"><?php echo h($song['metadata_error']); ?></p><?php endif; ?>
        </div>
    </section>

    <section class="home-section tag-editor-card">
        <div class="section-heading-row">
            <h2 class="section-title">태그</h2>
            <a class="section-more-link" href="tags.php">태그 탐색</a>
        </div>
        <div class="song-tags-box" data-song-id="<?php echo h($song['id']); ?>">
            <?php renderTagBadges($songTags, './', $song['id']); ?>
        </div>
        <form class="song-tag-form" data-song-id="<?php echo h($song['id']); ?>">
            <input type="text" name="tag_name" maxlength="100" placeholder="예: 드라이브, 밤에 듣기, 운동">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fa-solid fa-plus"></i> 태그 추가</button>
        </form>
        <?php if (!empty($popularTags)): ?>
            <div class="tag-suggestion-row">
                <?php foreach ($popularTags as $tag): ?>
                    <button type="button" class="tag-suggestion-btn" data-tag-name="<?php echo h($tag['name']); ?>"><?php echo h($tag['name']); ?></button>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>

    <section class="home-section listening-note-card">
        <div class="section-heading-row">
            <h2 class="section-title">별점과 개인 메모</h2>
            <a class="section-more-link" href="listening_notes.php">감상 노트</a>
        </div>
        <div class="rating-panel">
            <span class="settings-muted">내 별점</span>
            <?php renderRatingStars($songRating, $song['id'], true); ?>
        </div>
        <div class="note-view-text" data-song-id="<?php echo h($song['id']); ?>">
            <?php if ($songNote && trim((string)$songNote['note_text']) !== ''): ?>
                <div class="note-text-block"><?php echo nl2br(h($songNote['note_text'])); ?></div>
            <?php else: ?>
                <p class="empty-text">작성된 메모가 없습니다.</p>
            <?php endif; ?>
        </div>
        <form class="song-note-form" data-song-id="<?php echo h($song['id']); ?>">
            <textarea name="note_text" maxlength="10000" placeholder="이 곡에 대한 개인 메모를 남겨보세요."><?php echo h($songNote['note_text'] ?? ''); ?></textarea>
            <div class="note-action-row">
                <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-save"></i> 메모 저장</button>
                <button type="button" class="btn btn-secondary btn-sm note-delete-btn" data-song-id="<?php echo h($song['id']); ?>"><i class="fas fa-trash-alt"></i> 메모 삭제</button>
            </div>
        </form>
    </section>

    <div style="background-color: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; margin-bottom: 30px;">
        <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border-color); padding-bottom: 12px; margin-bottom: 20px;">
            <h3 style="font-size: 18px; font-weight: 700; margin: 0;">
                <i class="fas fa-music" style="color: var(--accent-color);"></i> 가사
            </h3>
            <a href="lyrics_edit.php?song_id=<?php echo $song['id']; ?>" class="btn btn-secondary btn-sm" style="border-radius: 6px; padding: 6px 12px;">
                <i class="fas fa-edit"></i> 가사 등록/수정
            </a>
        </div>
        
        <div class="lyrics-container" style="font-size: 15px; line-height: 2.2; color: #fff; text-align: center; max-height: 400px; overflow-y: auto; padding: 10px 0;">
            <?php if (empty($lyricsText)): ?>
                <p style="color: var(--text-muted); font-style: italic;">등록된 가사가 없습니다. 가사 등록/수정 버튼을 눌러 첫 가사를 등록해 보세요!</p>
            <?php else: ?>
                <div><?php echo nl2br(h($lyricsText)); ?></div>
            <?php endif; ?>
        </div>
    </div>
    
    <div style="margin-top: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
        <a href="song_edit.php?id=<?php echo $song['id']; ?>" class="btn btn-primary" style="border-radius: 8px;"><i class="fas fa-edit"></i> 곡 정보 수정</a>
        <a href="index.php" class="btn btn-secondary" style="border-radius: 8px;"><i class="fas fa-arrow-left"></i> 음악 목록으로 가기</a>
    </div>
</div>

<?php
renderFooter();
?>
