<?php
declare(strict_types=1);
require_once __DIR__ . '/db/config.php';

$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Lili Records Radio - Historial de canciones.';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? 'assets/pasted-20260215-164611-6d2aee42.png';

$db = db();
$stmt = $db->query("SELECT * FROM song_history WHERE played_at > DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY played_at DESC LIMIT 50");
$history = $stmt->fetchAll();
?>
<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Historial - Lili Records Radio</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

    <style>
        :root {
            --accent-color: #00c853;
            --primary-color: #38bdf8;
            --bg-overlay: rgba(0, 0, 0, 0.4);
            --glass-bg: rgba(255, 255, 255, 0.03);
            --glass-border: rgba(255, 255, 255, 0.2);
            --text-color: #ffffff;
        }

        [data-theme="light"] {
            --bg-overlay: rgba(255, 255, 255, 0.6);
            --glass-bg: rgba(255, 255, 255, 0.8);
            --glass-border: rgba(0, 0, 0, 0.1);
            --text-color: #1a1a1a;
        }

        body, html {
            margin: 0;
            padding: 0;
            width: 100%;
            min-height: 100%;
            font-family: 'Inter', sans-serif;
            color: var(--text-color);
            background: #111;
            transition: color 0.3s ease;
        }

        .background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('assets/images/background.jpg') center/cover no-repeat;
            z-index: -1;
        }

        .background::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: var(--bg-overlay);
        }

        .app-container {
            display: flex;
            flex-direction: column;
            width: 100%;
            min-height: 100vh;
            align-items: center;
            padding: 2rem 1.5rem;
            box-sizing: border-box;
        }

        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border: 1px solid var(--glass-border);
            border-radius: 32px;
            padding: 2.5rem;
            width: 100%;
            max-width: 600px;
            box-shadow: 0 15px 45px rgba(0, 0, 0, 0.4);
        }

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 2rem;
        }

        .header h1 {
            font-size: 1.8rem;
            font-weight: 800;
            margin: 0;
            background: linear-gradient(to right, #fff, var(--primary-color));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .back-btn {
            color: var(--text-color);
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
            opacity: 0.8;
            transition: opacity 0.2s;
        }

        .back-btn:hover {
            opacity: 1;
        }

        .history-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .history-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 16px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: transform 0.2s;
        }

        .history-item:hover {
            transform: translateX(10px);
            background: rgba(255, 255, 255, 0.1);
        }

        .history-item img {
            width: 50px;
            height: 50px;
            border-radius: 8px;
            object-fit: cover;
        }

        .history-info {
            flex: 1;
            overflow: hidden;
        }

        .history-title {
            font-weight: 700;
            font-size: 1rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: block;
        }

        .history-artist {
            font-size: 0.85rem;
            opacity: 0.7;
            color: var(--primary-color);
        }

        .history-time {
            font-size: 0.7rem;
            opacity: 0.5;
            text-align: right;
        }

        .theme-toggle {
            background: var(--glass-bg);
            border: 1px solid var(--glass-border);
            color: var(--text-color);
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            backdrop-filter: blur(5px);
            transition: all 0.3s;
        }

        .controls-row {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .search-container {
            flex: 1;
            position: relative;
        }

        .search-container i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            opacity: 0.5;
        }

        .search-input {
            width: 100%;
            background: var(--glass-bg);
            border: 1px solid var(--glass-border);
            padding: 0.8rem 1rem 0.8rem 2.8rem;
            border-radius: 12px;
            color: var(--text-color);
            font-family: inherit;
            box-sizing: border-box;
            outline: none;
            transition: all 0.3s;
        }

        .search-input:focus {
            border-color: var(--primary-color);
            background: rgba(255, 255, 255, 0.08);
        }

        [data-theme="light"] .search-input:focus {
            background: #fff;
        }

        .download-btn {
            background: var(--primary-color);
            color: #fff;
            border: none;
            padding: 0 1.2rem;
            border-radius: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
            transition: all 0.3s;
            white-space: nowrap;
        }

        .download-btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
    </style>
</head>
<body data-theme="dark">
    <div class="background"></div>

    <div class="app-container">
        <div class="glass-card">
            <div class="header">
                <a href="index.php" class="back-btn">
                    <i class="bi bi-arrow-left"></i> VOLVER
                </a>
                <h1>HISTORIAL</h1>
                <button onclick="toggleTheme()" id="theme-toggle" class="theme-toggle">
                    <i class="bi bi-moon-fill"></i>
                </button>
            </div>

            <div class="controls-row">
                <div class="search-container">
                    <i class="bi bi-search"></i>
                    <input type="text" id="search-input" class="search-input" placeholder="Buscar canción o artista..." onkeyup="filterHistory()">
                </div>
                <button onclick="downloadHistory()" class="download-btn">
                    <i class="bi bi-download"></i> GUARDAR
                </button>
            </div>

            <div class="history-list" id="history-list">
                <?php if (empty($history)): ?>
                    <div style="text-align: center; opacity: 0.5; padding: 2rem;">No hay canciones registradas en las últimas 24 horas.</div>
                <?php else: ?>
                    <?php foreach ($history as $track): ?>
                        <div class="history-item">
                            <img src="<?= htmlspecialchars($track['cover'] ?: './assets/pasted-20260215-163754-def41f49.png') ?>" alt="Cover">
                            <div class="history-info">
                                <span class="history-title"><?= htmlspecialchars($track['title']) ?></span>
                                <span class="history-artist"><?= htmlspecialchars($track['artist']) ?></span>
                            </div>
                            <div class="history-time">
                                <?= date('H:i', strtotime($track['played_at'])) ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        function toggleTheme() {
            const body = document.body;
            const currentTheme = body.getAttribute('data-theme');
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            const themeBtn = document.getElementById('theme-toggle').querySelector('i');
            
            body.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            
            if (newTheme === 'light') {
                themeBtn.classList.remove('bi-moon-fill');
                themeBtn.classList.add('bi-sun-fill');
            } else {
                themeBtn.classList.remove('bi-sun-fill');
                themeBtn.classList.add('bi-moon-fill');
            }
        }

        // Initialize Theme
        (function() {
            const savedTheme = localStorage.getItem('theme') || 'dark';
            if (savedTheme === 'light') {
                document.body.setAttribute('data-theme', 'light');
                const themeBtn = document.getElementById('theme-toggle').querySelector('i');
                themeBtn.classList.remove('bi-moon-fill');
                themeBtn.classList.add('bi-sun-fill');
            }
        })();

        function filterHistory() {
            const input = document.getElementById('search-input');
            const filter = input.value.toLowerCase();
            const list = document.getElementById('history-list');
            const items = list.getElementsByClassName('history-item');

            for (let i = 0; i < items.length; i++) {
                const titleElement = items[i].querySelector('.history-title');
                const artistElement = items[i].querySelector('.history-artist');
                
                if (!titleElement || !artistElement) continue;

                const title = titleElement.innerText.toLowerCase();
                const artist = artistElement.innerText.toLowerCase();
                
                if (title.includes(filter) || artist.includes(filter)) {
                    items[i].style.display = "";
                } else {
                    items[i].style.display = "none";
                }
            }
        }

        function downloadHistory() {
            const list = document.getElementById('history-list');
            const items = list.getElementsByClassName('history-item');
            let content = "Lili Records Radio - Historial de Canciones\n";
            content += "========================================\n\n";

            let count = 0;
            for (let i = 0; i < items.length; i++) {
                if (items[i].style.display !== "none") {
                    const titleElement = items[i].querySelector('.history-title');
                    const artistElement = items[i].querySelector('.history-artist');
                    const timeElement = items[i].querySelector('.history-time');

                    if (!titleElement || !artistElement || !timeElement) continue;

                    const title = titleElement.innerText;
                    const artist = artistElement.innerText;
                    const time = timeElement.innerText;
                    content += `[${time}] ${title} - ${artist}\n`;
                    count++;
                }
            }

            if (count === 0) {
                alert("No hay canciones para descargar.");
                return;
            }

            const blob = new Blob([content], { type: 'text/plain' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            const date = new Date().toISOString().split('T')[0];
            
            a.setAttribute('hidden', '');
            a.setAttribute('href', url);
            a.setAttribute('download', `historial-radio-${date}.txt`);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    </script>
</body>
</html>
