false, 'error' => 'ID inválido']); exit; } try { if ($action === 'mark_played') { $stmt = $db->prepare("UPDATE song_requests SET status = 'played' WHERE id = ?"); $stmt->execute([$id]); echo json_encode(['success' => true]); } elseif ($action === 'delete') { $stmt = $db->prepare("DELETE FROM song_requests WHERE id = ?"); $stmt->execute([$id]); echo json_encode(['success' => true]); } else { echo json_encode(['success' => false, 'error' => 'Acción no reconocida']); } } catch (Exception $e) { echo json_encode(['success' => false, 'error' => $e->getMessage()]); } exit; } $artist = trim($_POST['artist'] ?? ''); $song = trim($_POST['song'] ?? ''); $requester = trim($_POST['requester'] ?? 'Anónimo'); if (empty($artist) || empty($song)) { echo json_encode(['success' => false, 'error' => 'Falta artista o canción']); exit; } try { $stmt = $db->prepare("INSERT INTO song_requests (artist, song, requester) VALUES (?, ?, ?)"); $stmt->execute([$artist, $song, $requester]); echo json_encode(['success' => true]); } catch (Exception $e) { echo json_encode(['success' => false, 'error' => $e->getMessage()]); } exit; } if ($method === 'GET') { $action = $_GET['action'] ?? 'list'; if ($action === 'stats') { try { // Top artists $stmt = $db->query("SELECT artist, COUNT(*) as count FROM song_requests GROUP BY artist ORDER BY count DESC LIMIT 5"); $top_artists = $stmt->fetchAll(); // Top songs $stmt = $db->query("SELECT artist, song, COUNT(*) as count FROM song_requests GROUP BY artist, song ORDER BY count DESC LIMIT 5"); $top_songs = $stmt->fetchAll(); // Request volume by hour (last 24 hours) $stmt = $db->query("SELECT HOUR(created_at) as hour, COUNT(*) as count FROM song_requests WHERE created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR) GROUP BY hour ORDER BY hour ASC"); $volume_stats = $stmt->fetchAll(); echo json_encode([ 'success' => true, 'top_artists' => $top_artists, 'top_songs' => $top_songs, 'volume_stats' => $volume_stats ]); } catch (Exception $e) { echo json_encode(['success' => false, 'error' => $e->getMessage()]); } exit; } try { // Auto-archive requests older than 2 hours (7200 seconds) $db->query("UPDATE song_requests SET status = 'played' WHERE status = 'pending' AND created_at < (NOW() - INTERVAL 2 HOUR)"); $status = $_GET['status'] ?? 'pending'; $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10; if ($status === 'all') { $stmt = $db->query("SELECT * FROM song_requests ORDER BY created_at DESC LIMIT $limit"); } else { $stmt = $db->prepare("SELECT * FROM song_requests WHERE status = ? ORDER BY created_at DESC LIMIT $limit"); $stmt->execute([$status]); } $requests = $stmt->fetchAll(); echo json_encode(['success' => true, 'requests' => $requests]); } catch (Exception $e) { echo json_encode(['success' => false, 'requests' => [], 'error' => $e->getMessage()]); } exit; }