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

$data = json_decode(file_get_contents('php://input'), true);
$username = $data['username'] ?? '';
$item = $data['item'] ?? '';
$color = $data['color'] ?? null;

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

try {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT loyalty_points, chat_color FROM fans WHERE name = ?");
    $stmt->execute([$username]);
    $fan = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$fan) {
        echo json_encode(['success' => false, 'error' => 'Usuario no encontrado']);
        exit;
    }

    $points = $fan['loyalty_points'];
    $current_color = $fan['chat_color'];

    if ($item === 'god_mode') {
        $cost = 500;
        if ($points < $cost) {
            echo json_encode(['success' => false, 'error' => "Puntos insuficientes ($points/$cost)"]);
            exit;
        }
        
        $new_color = $color ?: '#ffd700'; // Gold default
        $stmt = $pdo->prepare("UPDATE fans SET loyalty_points = loyalty_points - ?, chat_color = ? WHERE name = ?");
        $stmt->execute([$cost, $new_color, $username]);
        
        echo json_encode(['success' => true, 'message' => '¡Modo Dios activado! Ahora tienes un color exclusivo.']);
    } elseif ($item === 'dj_day') {
        $cost = 2000;
        if ($points < $cost) {
            echo json_encode(['success' => false, 'error' => "Puntos insuficientes ($points/$cost)"]);
            exit;
        }
        
        $stmt = $pdo->prepare("UPDATE fans SET loyalty_points = loyalty_points - ?, dj_day_until = DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE name = ?");
        $stmt->execute([$cost, $username]);
        
        echo json_encode(['success' => true, 'message' => '¡Eres DJ por un día! Tu nombre destacará en toda la sala.']);
    } elseif ($item === 'vip_jump') {
        $cost = 500;
        $artist = $data['artist'] ?? '';
        $song = $data['song'] ?? '';
        
        if (empty($artist) || empty($song)) {
            echo json_encode(['success' => false, 'error' => 'Falta artista o canción para el Salto VIP']);
            exit;
        }

        if ($points < $cost) {
            echo json_encode(['success' => false, 'error' => "Puntos insuficientes ($points/$cost)"]);
            exit;
        }
        
        $pdo->beginTransaction();
        try {
            // Deduct points
            $stmt = $pdo->prepare("UPDATE fans SET loyalty_points = loyalty_points - ? WHERE name = ?");
            $stmt->execute([$cost, $username]);

            // Insert priority request
            $stmt = $pdo->prepare("INSERT INTO song_requests (artist, song, requester, source, is_priority) VALUES (?, ?, ?, 'vip_jump', 1)");
            $stmt->execute([$artist, $song, $username]);

            // Announce in chat
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
            $ip = explode(',', $ip)[0];
            $announcement = "🚀 ¡ATENCIÓN! **$username** ha usado sus puntos VIP para que suene **$artist - $song** ¡AHORA MISMO! 🔥🎧";
            
            $stmt = $pdo->prepare("INSERT INTO messages (username, ip_address, message, type) VALUES (?, ?, ?, ?)");
            $stmt->execute(['Lili Bot 🤖', $ip, $announcement, 'text']);

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => '¡Salto VIP exitoso! Tu canción sonará a continuación.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            throw $e;
        }
    } elseif ($item === 'change_color') {
        // If they already have god mode, changing color might be cheaper or free?
        // Let's say 100 points to change color if already bought, or free if we want.
        if (!$current_color) {
            echo json_encode(['success' => false, 'error' => 'Primero debes desbloquear el Modo Dios']);
            exit;
        }
        $cost = 50;
        if ($points < $cost) {
            echo json_encode(['success' => false, 'error' => "Puntos insuficientes ($points/$cost)"]);
            exit;
        }
        $stmt = $pdo->prepare("UPDATE fans SET loyalty_points = loyalty_points - ?, chat_color = ? WHERE name = ?");
        $stmt->execute([$cost, $color, $username]);
        echo json_encode(['success' => true, 'message' => '¡Color actualizado!']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Ítem no reconocido']);
    }

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