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

$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
    $data = $_POST;
}

$username = $data['username'] ?? '';
$action = $data['action'] ?? '';
$requestId = $data['request_id'] ?? null;

if (empty($username) || empty($action)) {
    echo json_encode(['success' => false, 'error' => 'Datos incompletos']);
    exit;
}

try {
    $db = db();
    
    // Verify Guest DJ status
    $stmt = $db->prepare("SELECT dj_day_until FROM fans WHERE name = ?");
    $stmt->execute([$username]);
    $dj_day_until = $stmt->fetchColumn();
    
    $isGuestDj = $dj_day_until && (strtotime($dj_day_until) > time());
    
    if (!$isGuestDj) {
        echo json_encode(['success' => false, 'error' => 'No tienes permisos de DJ Invitado activos']);
        exit;
    }

    if ($action === 'skip') {
        // Log skip action
        $stmt = $db->prepare("INSERT INTO radio_actions (action_type, performed_by, details) VALUES ('skip', ?, ?)");
        $stmt->execute([$username, "El DJ Invitado ha solicitado saltar la canción"]);
        
        // Announce in chat
        $chatMsg = "🚨 [DJ INVITADO] **$username** ha usado su poder para SALTAR la canción actual. ⏭️";
        $stmt = $db->prepare("INSERT INTO messages (username, message, type) VALUES ('Sistema', ?, 'dj_power')");
        $stmt->execute([$chatMsg]);
        
        echo json_encode(['success' => true, 'message' => 'Acción de saltar ejecutada y anunciada']);
        
    } elseif ($action === 'prioritize') {
        if (!$requestId) {
            echo json_encode(['success' => false, 'error' => 'ID de petición faltante']);
            exit;
        }
        
        $stmt = $db->prepare("UPDATE song_requests SET is_priority = 1 WHERE id = ?");
        $stmt->execute([$requestId]);
        
        // Get request details for announcement
        $stmt = $db->prepare("SELECT artist, song FROM song_requests WHERE id = ?");
        $stmt->execute([$requestId]);
        $req = $stmt->fetch();
        
        if ($req) {
            $chatMsg = "🔥 [DJ INVITADO] **$username** ha PRIORIZADO la canción: **{$req['artist']} - {$req['song']}**. ¡Sonará muy pronto! 🎵";
            $stmt = $db->prepare("INSERT INTO messages (username, message, type) VALUES ('Sistema', ?, 'dj_power')");
            $stmt->execute([$chatMsg]);
        }
        
        echo json_encode(['success' => true, 'message' => 'Petición priorizada con éxito']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Acción no válida']);
    }

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