<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';

try {
    $db = db();
    
    // Check for a local "played" song that is currently within its duration
    $stmt = $db->query("SELECT artist, song, requester, youtube_url, duration, UNIX_TIMESTAMP(created_at) as started_at FROM song_requests WHERE status = 'played' ORDER BY created_at DESC LIMIT 1");
    $override = $stmt->fetch();
    
    if ($override) {
        $duration = (int)($override['duration'] ?? 240);
        $startedAt = $override['started_at'];
        $endAt = $startedAt + $duration;
        $remaining = $endAt - time();
        
        if ($remaining > 0) {
            // Find next track for local requests
            $stmtNext = $db->query("SELECT id, artist, song FROM song_requests WHERE status = 'pending' ORDER BY is_priority DESC, created_at ASC LIMIT 1");
            $nextTrack = $stmtNext->fetch();
            $nextInfo = null;
            if ($nextTrack) {
                $nextInfo = ['artist' => $nextTrack['artist'], 'title' => $nextTrack['song']];
                
                // Server-side warning logic: if 30s left and warning not sent
                if ($remaining <= 35 && $remaining > 15) {
                    $stmtCheck = $db->prepare("SELECT warning_sent FROM song_requests WHERE id = ?");
                    $stmtCheck->execute([$nextTrack['id']]);
                    $wSent = $stmtCheck->fetchColumn();
                    
                    if (!$wSent) {
                        $chatMsg = "⏭️ **Próxima canción:** {$nextTrack['artist']} - {$nextTrack['song']} 🎶 (en 30 seg aprox)";
                        $db->prepare("INSERT INTO messages (username, message, type) VALUES ('Sistema', ?, 'dj_power')")->execute([$chatMsg]);
                        $db->prepare("UPDATE song_requests SET warning_sent = 1 WHERE id = ?")->execute([$nextTrack['id']]);
                    }
                }
            }

            echo json_encode([
                'success' => true,
                'source' => 'local_request',
                'artist' => $override['artist'],
                'title' => $override['song'],
                'requester' => $override['requester'],
                'youtube_url' => $override['youtube_url'],
                'duration' => $duration,
                'started_at' => date('c', $startedAt),
                'end_at' => date('c', $endAt),
                'remaining' => $remaining,
                'next_track' => $nextInfo,
                'cover' => './assets/pasted-20260215-163754-def41f49.png'
            ]);
            exit;
        }
    }
    
    // Fallback: Proxy RadioKing metadata
    $radioKingUrl = 'https://www.radioking.com/widgets/api/v1/radio/828046/track/current';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $radioKingUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $resp = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200 && $resp) {
        $data = json_decode($resp, true);
        $duration = $data['duration'] ?? 0;
        $endAt = $data['end_at'] ?? null;
        $startedAt = null;
        
        if ($endAt && $duration) {
            $startedAt = date('c', strtotime($endAt) - $duration);
            $remainingRadio = strtotime($endAt) - time();
            
            // If RadioKing song has ~30s left and there's a local pending request
            if ($remainingRadio <= 35 && $remainingRadio > 15) {
                $stmtNext = $db->query("SELECT id, artist, song FROM song_requests WHERE status = 'pending' ORDER BY is_priority DESC, created_at ASC LIMIT 1");
                $localNext = $stmtNext->fetch();
                if ($localNext) {
                    $stmtCheck = $db->prepare("SELECT warning_sent FROM song_requests WHERE id = ?");
                    $stmtCheck->execute([$localNext['id']]);
                    $wSent = $stmtCheck->fetchColumn();
                    
                    if (!$wSent) {
                        $chatMsg = "⏭️ **Próxima canción:** {$localNext['artist']} - {$localNext['song']} 🎶 (en 30 seg aprox)";
                        $db->prepare("INSERT INTO messages (username, message, type) VALUES ('Sistema', ?, 'dj_power')")->execute([$chatMsg]);
                        $db->prepare("UPDATE song_requests SET warning_sent = 1 WHERE id = ?")->execute([$localNext['id']]);
                    }
                }
            }
        }

        // For RadioKing source, check if there's a pending local request (it will be next)
        $nextInfo = $data['next_track'] ?? null;
        $stmtNext = $db->query("SELECT id, artist, song FROM song_requests WHERE status = 'pending' ORDER BY is_priority DESC, created_at ASC LIMIT 1");
        $localNext = $stmtNext->fetch();
        if ($localNext) {
            $nextInfo = ['artist' => $localNext['artist'], 'title' => $localNext['song']];
        }

        echo json_encode([
            'success' => true,
            'source' => 'radioking',
            'artist' => $data['artist'] ?? 'Lili Records',
            'title' => $data['title'] ?? 'La mejor música',
            'cover' => $data['cover'] ?? './assets/pasted-20260215-163754-def41f49.png',
            'duration' => $duration,
            'started_at' => $startedAt,
            'end_at' => $endAt,
            'next_track' => $nextInfo
        ]);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
