<?php
/**
 * 최근 재생 목록 페이지
 */

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

$pdo = getDBConnection();

$search = isset($_GET['search']) ? trim((string)$_GET['search']) : '';
$params = [];

$sql = "
    SELECT
        s.id,
        s.title,
        s.artist,
        s.album,
        s.genre,
        s.duration,
        s.extension,
        s.play_count,
        MAX(h.played_at) AS last_played_at,
        COUNT(h.id) AS history_count,
        IF(l.id IS NOT NULL, 1, 0) AS is_liked
    FROM play_history h
    INNER JOIN songs s ON h.song_id = s.id
    LEFT JOIN liked_songs l ON s.id = l.song_id
    WHERE s.is_missing = 0
";

if ($search !== '') {
    $sql .= " AND (s.title LIKE :search1 OR s.artist LIKE :search2 OR s.album LIKE :search3)";
    $params[':search1'] = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
    $params[':search3'] = '%' . $search . '%';
}

$sql .= "
    GROUP BY s.id, s.title, s.artist, s.album, s.genre, s.duration, s.extension, s.play_count, l.id
    ORDER BY last_played_at DESC
    LIMIT 50
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$songs = $stmt->fetchAll();

$pageTitle = '최근 재생';
if ($search !== '') {
    $pageTitle = '최근 재생 검색 결과';
}

renderHeader($pageTitle, 'recent');
?>

<div class="music-list-page recent-history-page">
    <div class="page-title-section">
        <h1 class="page-main-title"><?php echo h($pageTitle); ?></h1>
        <p class="page-subtitle">
            <?php if ($search !== ''): ?>
                "<?php echo h($search); ?>" 검색어로 최근 재생 기록을 찾았습니다. 총 <?php echo number_format(count($songs)); ?>곡입니다.
            <?php else: ?>
                최근 들은 음악을 최신순으로 정리했습니다. 중복 기록은 곡별 최신 재생 기준으로 묶어 보여줍니다.
            <?php endif; ?>
        </p>
    </div>

    <div class="recent-history-toolbar" data-recent-history-toolbar>
        <div>
            <strong>최근 재생 정리</strong>
            <span>개별 곡을 지우거나 전체 최근 재생 기록을 비울 수 있습니다.</span>
        </div>
        <button type="button" class="btn btn-secondary btn-sm recent-clear-all-btn" data-recent-clear-all <?php echo empty($songs) ? 'disabled' : ''; ?>>
            <i class="fa-regular fa-trash-can"></i> 전체 삭제
        </button>
    </div>

    <?php renderSongList($songs, [
        'show_recent_remove' => true,
    ]); ?>
</div>

<?php
renderFooter();
?>
