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

$method = $_SERVER['REQUEST_METHOD'];
$db = db();

if ($method === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        $id = (int)($_POST['id'] ?? 0);

        if ($id <= 0) {
            echo json_encode(['success' => false, 'error' => 'ID inválido']);
            exit;
        }

        try {
            if ($action === 'mark_played') {
                $username = trim($_POST['username'] ?? '');
                
                // Get request info before updating
                $stmt = $db->prepare("SELECT is_priority, created_at, artist, song FROM song_requests WHERE id = ?");
                $stmt->execute([$id]);
                $req = $stmt->fetch();

                $stmt = $db->prepare("UPDATE song_requests SET status = 'played' WHERE id = ?");
                $stmt->execute([$id]);
                
                $bonus = false;
                if ($req && $req['is_priority'] == 1 && !empty($username)) {
                    $createdAt = strtotime($req['created_at']);
                    $now = time();
                    $diff = $now - $createdAt;
                    
                    // Award bonus if handled in less than 5 minutes (300 seconds)
                    if ($diff <= 300) {
                        require_once __DIR__ . '/../includes/points_helper.php';
                        awardLoyaltyPoints($username, 100);
                        
                        // Announce bonus
                        $chatMsg = "⚡ ¡BONO DE EFICIENCIA! El DJ **$username** ha atendido un Salto VIP en récord (" . floor($diff/60) . "m " . ($diff%60) . "s). ¡Ha ganado **+100 LP**! 🎧👑";
                        $db->prepare("INSERT INTO messages (username, message, type) VALUES ('Sistema', ?, 'dj_power')")->execute([$chatMsg]);
                        $bonus = true;
                    }
                }
                
                echo json_encode(['success' => true, 'bonus_awarded' => $bonus, 'was_priority' => ($req && $req['is_priority'] == 1)]);
            } 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');
    $source = trim($_POST['source'] ?? 'web');

    if (empty($artist) || empty($song)) {
        echo json_encode(['success' => false, 'error' => 'Falta artista o canción']);
        exit;
    }

    try {
        // Check for duplicates
        // 1. Check if it's already in the pending queue
        $stmt = $db->prepare("SELECT id FROM song_requests WHERE artist = ? AND song = ? AND status = 'pending' LIMIT 1");
        $stmt->execute([$artist, $song]);
        if ($stmt->fetch()) {
            echo json_encode(['success' => false, 'error' => 'Esta canción ya está en la cola de espera.']);
            exit;
        }

        // 2. Check if it was played in the last 30 minutes (to avoid repetition)
        // We skip this check for priority requests or if the DJ is adding it
        if ($source !== 'admin') {
            $stmt = $db->prepare("SELECT id FROM song_requests WHERE artist = ? AND song = ? AND status = 'played' AND created_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE) LIMIT 1");
            $stmt->execute([$artist, $song]);
            if ($stmt->fetch()) {
                echo json_encode(['success' => false, 'error' => 'Esta canción se ha reproducido recientemente. ¡Prueba con otra!']);
                exit;
            }
        }

        // All requests start as pending. The automation.php script (called by clients) 
        // will handle moving them to 'played' status atomically.
        $initialStatus = 'pending';

        $stmt = $db->prepare("INSERT INTO song_requests (artist, song, requester, source, status, duration) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$artist, $song, $requester, $source, $initialStatus, 240]);
        $requestId = $db->lastInsertId();

        // Award points for song request
        if ($requester !== 'Anónimo') {
            require_once __DIR__ . '/../includes/points_helper.php';
            awardPoints($requester, 25);
            
            if ($source === 'whatsapp') {
                announceWhatsAppRequest($requester, $artist, $song);
            } else {
                announceSongRequest($requester, $artist, $song);
            }
        }

        // Send Email Notification
        try {
            require_once __DIR__ . '/../mail/MailService.php';
            $subject = "Nueva Petición de Canción: $artist - $song";
            $htmlBody = "
                <h3>Nueva Petición de Canción</h3>
                <p><strong>De:</strong> $requester</p>
                <p><strong>Artista:</strong> $artist</p>
                <p><strong>Canción:</strong> $song</p>
                <p><strong>Fuente:</strong> $source</p>
                <p><strong>Fecha:</strong> " . date('Y-m-d H:i:s') . "</p>
            ";
            MailService::sendMail(null, $subject, $htmlBody);
        } catch (Exception $e) {
            // Silently fail email but log it
            error_log("Email request failed: " . $e->getMessage());
        }

        // Check if this user is now the #1 listener of the week
        $topStmt = $db->query("
            SELECT requester, COUNT(*) as total_requests 
            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 total_requests DESC 
            LIMIT 1
        ");
        $topListener = $topStmt->fetch();
        
        $isNewTop = false;
        if ($topListener && $topListener['requester'] === $requester) {
            $isNewTop = true;
        }

        echo json_encode([
            'success' => true, 
            'is_top' => $isNewTop, 
            'top_name' => $topListener['requester'] ?? ''
        ]);
    } 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();

            // Visitor locations (last 10 minutes)
            $stmt = $db->query("SELECT country, country_code, lat, lon, COUNT(*) as count FROM visitor_logs WHERE last_activity > DATE_SUB(NOW(), INTERVAL 10 MINUTE) GROUP BY country_code");
            $locations = $stmt->fetchAll();

            // Total requests today
            $stmt = $db->query("SELECT COUNT(*) FROM song_requests WHERE DATE(created_at) = CURDATE()");
            $requests_today = $stmt->fetchColumn();

            echo json_encode([
                'success' => true,
                'top_artists' => $top_artists,
                'top_songs' => $top_songs,
                'volume_stats' => $volume_stats,
                'locations' => $locations,
                'requests_today' => $requests_today
            ]);
        } 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';
        $source = $_GET['source'] ?? null;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
        
        $query = "SELECT * FROM song_requests WHERE 1=1";
        $params = [];
        
        if ($status !== 'all') {
            $query .= " AND status = ?";
            $params[] = $status;
        }
        
        if ($source) {
            $query .= " AND source = ?";
            $params[] = $source;
        }
        
        $query .= " ORDER BY is_priority DESC, created_at DESC LIMIT $limit";
        
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        
        $requests = $stmt->fetchAll();
        echo json_encode(['success' => true, 'requests' => $requests]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'requests' => [], 'error' => $e->getMessage()]);
    }
    exit;
}

