<?php
require_once __DIR__ . '/../db/config.php';

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        // Borrar fotos (tipo image) que tengan más de 5 segundos
        $stOld = db()->prepare("SELECT message FROM messages WHERE type = 'image' AND created_at < DATE_SUB(NOW(), INTERVAL 5 SECOND)");
        $stOld->execute();
        $imagesToDelete = $stOld->fetchAll(PDO::FETCH_ASSOC);

        foreach ($imagesToDelete as $img) {
            $path = __DIR__ . '/../' . $img['message'];
            if (file_exists($path) && is_file($path)) {
                unlink($path);
            }
        }
        db()->query("DELETE FROM messages WHERE (type = 'image' OR type = 'reaction' OR type = 'flash_poll') AND created_at < DATE_SUB(NOW(), INTERVAL 5 SECOND)");

        // Limpiar otros mensajes y archivos de más de 7 días
        $oldImages = db()->prepare("SELECT message FROM messages WHERE type = 'image' AND created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");
        $oldImages->execute();
        $filesToDelete = $oldImages->fetchAll(PDO::FETCH_ASSOC);

        foreach ($filesToDelete as $fileRow) {
            $filePath = __DIR__ . '/../' . $fileRow['message'];
            if (file_exists($filePath) && is_file($filePath)) {
                unlink($filePath);
            }
        }

        db()->query("DELETE FROM messages WHERE created_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");

        // Obtener el Oyente de la Semana (Top 1)
        $topStmt = db()->query("
            SELECT requester 
            FROM song_requests 
            WHERE requester IS NOT NULL AND requester != '' AND requester != 'Anónimo'
            AND created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
            GROUP BY requester 
            ORDER BY COUNT(*) DESC 
            LIMIT 1
        ");
        $topRequester = $topStmt->fetchColumn();

        $stmt = db()->prepare("SELECT m.*, f.points, f.loyalty_points, f.is_fan_of_month, f.chat_color, f.dj_day_until FROM messages m LEFT JOIN fans f ON m.username = f.name ORDER BY m.created_at DESC LIMIT 50");
        $stmt->execute();
        $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($messages as &$msg) {
            $points = $msg['points'] ?? 0;
            $loyalty = $msg['loyalty_points'] ?? 0;
            $chatColor = $msg['chat_color'] ?? null;
            $djDayUntil = $msg['dj_day_until'] ?? null;
            $isDjDay = $djDayUntil && strtotime($djDayUntil) > time();

            $msg['level_color'] = $chatColor ?: '#94a3b8';
            $msg['level_emoji'] = '';
            
            if ($msg['username'] === 'Lili Bot 🤖') {
                $msg['level_color'] = '#00e676';
                $msg['level_emoji'] = '🤖';
            } elseif ($msg['username'] === 'Sistema') {
                $msg['level_color'] = '#facc15';
                $msg['level_emoji'] = '📢';
            } elseif ($isDjDay) {
                $msg['level_color'] = '#facc15';
                $msg['level_emoji'] = '🎧';
                $msg['is_guest_dj'] = true;
            } elseif ($msg['username'] === $topRequester) {
                $msg['level_color'] = '#facc15';
                $msg['level_emoji'] = '👑';
                $msg['is_top_listener'] = true;
            } elseif ($loyalty > 0) {
                $msg['level_color'] = '#00e676'; // Neon Green for Loyalty
                $msg['level_emoji'] = $loyalty >= 500 ? '🎖️' : '🏅';
                $msg['is_loyal'] = true;
            } elseif ($msg['is_fan_of_month']) {
                $msg['level_color'] = '#facc15';
            } elseif ($points >= 2500) {
                $msg['level_color'] = '#a855f7';
                $msg['level_emoji'] = '👑';
            } elseif ($points >= 1000) {
                $msg['level_color'] = '#f97316';
                $msg['level_emoji'] = '🔥';
            } elseif ($points >= 500) {
                $msg['level_color'] = '#22c55e';
                $msg['level_emoji'] = '⭐';
            } elseif ($points >= 100) {
                $msg['level_color'] = '#3b82f6';
            }
        }

        echo json_encode(array_reverse($messages));
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $username = $input['username'] ?? 'Anónimo';
    $message = $input['message'] ?? '';
    $type = $input['type'] ?? 'text';
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
    $ip = explode(',', $ip)[0];

    if (empty($message)) {
        echo json_encode(['error' => 'Mensaje vacío']);
        exit;
    }

    try {
        $stmt = db()->prepare("INSERT INTO messages (username, ip_address, message, type) VALUES (?, ?, ?, ?)");
        $stmt->execute([$username, $ip, $message, $type]);

        // Award points to the fan based on chat activity
        require_once __DIR__ . '/../includes/points_helper.php';
        
        if ($type === 'flash_poll_response') {
            awardLoyaltyPoints($username, 10);
            $pts = 10; // Also add to general ranking
        } else {
            $pts = ($type === 'reaction') ? 1 : 5;
        }
        
        $newPoints = awardPoints($username, $pts); 

        // Auto-update Fan of the Month if this user has the highest points
        $maxPointsStmt = db()->query("SELECT MAX(points) as max_p FROM fans");
        $maxPoints = $maxPointsStmt->fetch()['max_p'];
        
        if ($newPoints >= $maxPoints) {
            db()->query("UPDATE fans SET is_fan_of_month = 0");
            db()->prepare("UPDATE fans SET is_fan_of_month = 1 WHERE name = ?")->execute([$username]);
        }

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