<?php

// 🔥 CONFIGURAR ZONA HORARIA A PERU (UTC-5)
date_default_timezone_set('America/Lima');

$token = "8542076830:AAG0SV8O9oY99q-szQW58MAptuvGqXhgzk0";
$api = "https://api.telegram.org/bot".$token;

$update = json_decode(file_get_contents("php://input"), true);

// USERNAMES
$canalUsername = "@fiufiu7";
$grupoUsername = "https://t.me/+NEpOMAJZYbhjNDFh";

// LINKS
$canalLink = "https://t.me/fiufiu7";
$grupoLink = "https://t.me/+NEpOMAJZYbhjNDFh";
$whatsappLink = "https://whatsapp.com/channel/0029VbBQ5HP6LwHbqKYIbn25";

// 🔥 NUEVOS LINKS
$grupoWhatsappLink = "https://chat.whatsapp.com/F0ys3edLrAY7WBzidIxBuS";
$webOficialLink = "https://7fiufiu.com/";

// ==========================
// USUARIOS BLOQUEADOS (case-insensitive)
// ==========================
$usuariosBloqueados = ["Elmexinegro", "jeize2333", "Lamuerte333", "vipfiufiu", "jent25x", "jent25x", "Alexzonasur", "NuxLeander", "ExCazadordePajeros", "jot4j", "Joseanto97", "mayzon777", "GatubeloVip", "shelby_G96", "Elposho45", "ice6669", "selder32444", "Kochorashvil1", "Trrr1054", "Tuyyopw", "mano7013", "yyrrgccgh", "Kwslwoel", "Chinaski94", "Cris2112o", "cvjkhb_77", "elioparedespaucar", "Rafito92", "Lelouch2317", "Fabizzz0", "Usuarionoenco", "Calvz123", "flax0v", "jorgetorres303", "Floxk300", "Pingon01", "evin888", "Carlos27199", "Dulce02kalessy27", "NoobNoob64", "adrianx666", "TeanAntiCP", "Fabian_king7", "JoseO2706", "solocupodeporte", "rusbel_kfc_26", "JeffHardythebest", "Lucho2324", "darell_26_m", "dibujito231", "dukemod100", "Laykado", "ladiablitq", "Fabian_king1", "satanassisi", "Pqpito14", "suertx", "nomellores", "jhusitop", "EL_mas_conosido", "miklobish", "josuex7", "morganaofc1", "Ruusoss", "Roig500", "bycasst", "IamScams", "masacrandote"];

// ==========================
// FUNCIONES
// ==========================

function guardarUsuario($chatId){
    $archivo = "usuarios.txt";
    $usuarios = file_exists($archivo) ? file($archivo, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    if(!in_array($chatId, $usuarios)){
        file_put_contents($archivo, $chatId.PHP_EOL, FILE_APPEND | LOCK_EX);
    }
}

function esAdmin($chatId, $userId, $api){
    $url = $api."/getChatMember?chat_id=".$chatId."&user_id=".$userId;
    $result = json_decode(file_get_contents($url), true);
    if(isset($result["result"]["status"])){
        $status = $result["result"]["status"];
        if($status == "administrator" || $status == "creator"){
            return true;
        }
    }
    return false;
}

function enviarContenidoFinal($chatId, $api, $canalLink, $grupoLink, $whatsappLink, $username = ""){
    global $webOficialLink, $update;
    
    $userId = $update["message"]["from"]["id"] ?? 0;
    $estaExpulsado = estaExpulsadoDelGrupo($userId);
    
    $foto = "https://legendarycloud.space/fotodescripcion7fiufiu.jpg";

    // 🔥 CONSTRUIR BOTONES SEGÚN EL ESTADO DEL USUARIO
    $inlineKeyboard = [];
    
    // Botón GRUPO (si está expulsado, usa callback en lugar de url)
    if($estaExpulsado){
        $inlineKeyboard[] = [
            ["text" => "👥 GRUPO 7FIUFIU OFICIAL", "callback_data" => "alert_grupo"]
        ];
    } else {
        $inlineKeyboard[] = [
            ["text" => "👥 GRUPO 7FIUFIU OFICIAL", "url" => $grupoLink]
        ];
    }
    
    // Botón CANAL (siempre url normal)
    $inlineKeyboard[] = [
        ["text" => "📢 CANAL DEL 7FIUFIU", "url" => $canalLink]
    ];
    
    // Botón WEB (siempre url normal)
    $inlineKeyboard[] = [
        ["text" => "🌐 WEB OFICIAL 7FIUFIU", "url" => $webOficialLink]
    ];

    $keyboard = ["inline_keyboard" => $inlineKeyboard];
    $username = $username ?: "Usuario";

    $mensaje = "¡Hola @$username!Bienvenido(a) a 7fiufiu el más alarako de la plataforma 🔥\n\n";
    $mensaje .= "✅Aquí podrás acceder a nuestro Grupo y Canal Oficial.\n\n";
    $mensaje .= "⚠️ Importante\n";
    $mensaje .= "No bloquees ni elimines el chat del bot.\n";
    $mensaje .= "Si lo haces, el sistema se bloqueará automáticamente y perderás el contacto con nosotros.\n\n";
    $mensaje .= "⭐Para empezar primero suscribete a estos chats⤵️";

    $data = [
        'chat_id' => $chatId,
        'photo' => $foto,
        'caption' => $mensaje,
        'reply_markup' => json_encode($keyboard),
        'parse_mode' => 'HTML'
    ];

    file_get_contents($api."/sendPhoto?".http_build_query($data));
    guardarUsuario($chatId);
}

// ==========================
// GUARDAR EXPULSADO (CON HORA PERU) + LISTA NEGRA
// ==========================
function guardarExpulsado($userId, $username, $razon, $expulsadoPor, $api, $chatId = null){
    // 1. Guardar en expulsados.txt (registro detallado)
    $archivo = "expulsados.txt";
    
    // Obtener nombre completo del expulsado
    $nombre = "Desconocido";
    if($chatId){
        $url = $api."/getChatMember?chat_id=".$chatId."&user_id=".$userId;
        $result = json_decode(file_get_contents($url), true);
        if(isset($result["result"]["user"]["first_name"])){
            $nombre = $result["result"]["user"]["first_name"];
            if(isset($result["result"]["user"]["last_name"])){
                $nombre .= " " . $result["result"]["user"]["last_name"];
            }
        }
    }
    
    $username = $username ?: "sin_username";
    $fecha = date("Y-m-d H:i:s");
    
    $linea = "========================================\n";
    $linea .= "Fecha: {$fecha}\n";
    $linea .= "ID: {$userId}\n";
    $linea .= "Usuario: @{$username}\n";
    $linea .= "Nombre: {$nombre}\n";
    $linea .= "Razon: {$razon}\n";
    $linea .= "Expulsado por: {$expulsadoPor}\n";
    $linea .= "========================================\n\n";
    
    file_put_contents($archivo, $linea, FILE_APPEND | LOCK_EX);
    
    // 🔥 NUEVO: Guardar en lista negra del grupo (para bloquear en privado)
    $archivoNegra = "expulsados_grupo.txt";
    $lineaNegra = $userId . "\n";
    file_put_contents($archivoNegra, $lineaNegra, FILE_APPEND | LOCK_EX);
}

// ==========================
// VERIFICAR SI USUARIO FUE EXPULSADO DEL GRUPO
// ==========================
function estaExpulsadoDelGrupo($userId){
    $archivo = "expulsados_grupo.txt";
    if(!file_exists($archivo)){
        return false;
    }
    $expulsados = file($archivo, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    return in_array($userId, $expulsados);
}

// ==========================
// FUNCIÓN PARA EXPULSAR Y ELIMINAR
// ==========================
function expulsarYEliminar($chatId, $userId, $messageId, $api, $razon = "Spam"){
    global $update;
    
    // Obtener datos del expulsado
    $username = $update["message"]["from"]["username"] ?? "sin_username";
    
    // Guardar registro detallado (también guarda en lista negra)
    guardarExpulsado($userId, $username, $razon, "Bot (automatico)", $api, $chatId);
    
    // 1. ELIMINAR mensaje
    $dataDelete = [
        'chat_id' => $chatId,
        'message_id' => $messageId
    ];
    $deleteResult = file_get_contents($api."/deleteMessage?".http_build_query($dataDelete));
    
    // 2. EXPULSAR al usuario
    $kickData = [
        'chat_id' => $chatId,
        'user_id' => $userId
    ];
    $kickResult = file_get_contents($api."/kickChatMember?".http_build_query($kickData));
}

// ==========================
// DETECTAR SPAM DE STICKERS, FOTOS Y VIDEOS
// ==========================
function detectarSpamMultimedia($chatId, $userId, $api){
    global $update;
    
    // Si es admin, ignorar
    if(esAdmin($chatId, $userId, $api)){
        return false;
    }
    
    // Verificar si el mensaje es foto, video o sticker
    $esFoto = isset($update["message"]["photo"]);
    $esVideo = isset($update["message"]["video"]);
    $esSticker = isset($update["message"]["sticker"]);
    
    // Si no es foto, video ni sticker, ignorar
    if(!$esFoto && !$esVideo && !$esSticker){
        return false;
    }
    
    $archivo = "spam_multimedia_log.txt";
    
    // Cargar datos actuales
    $datos = [];
    if(file_exists($archivo)){
        $contenido = file_get_contents($archivo);
        if($contenido){
            $datos = json_decode($contenido, true) ?: [];
        }
    }
    
    $clave = $chatId . "_" . $userId;
    $ahora = time();
    
    // Inicializar si no existe
    if(!isset($datos[$clave])){
        $datos[$clave] = ['tiempos' => []];
    }
    
    // 🔥 FILTRAR: Eliminar tiempos de hace más de 24 horas (86400 segundos)
    $datos[$clave]['tiempos'] = array_filter($datos[$clave]['tiempos'], function($timestamp) use ($ahora) {
        return ($ahora - $timestamp) <= 86400; // 24 horas
    });
    
    // Agregar tiempo actual
    $datos[$clave]['tiempos'][] = $ahora;
    
    // Contar stickers, fotos y videos en el período (máximo 24 horas)

    $total = count($datos[$clave]['tiempos']);
    
    // Guardar datos actualizados
    file_put_contents($archivo, json_encode($datos));
    
    // 🔥 Si supera 15, EXPULSAR
    if($total > 15){
        $username = $update["message"]["from"]["username"] ?? "sin_username";
        
        // Determinar qué tipo de spam fue
        $tipo = "";
        if($esSticker) $tipo = "stickers";
        if($esFoto) $tipo = "fotos";
        if($esVideo) $tipo = "videos";
        if($esSticker && $esFoto) $tipo = "stickers/fotos";
        if($esSticker && $esVideo) $tipo = "stickers/videos";
        
        // Calcular tiempo total desde el primer mensaje
        $primerTimestamp = min($datos[$clave]['tiempos']);
        $tiempoTotal = $ahora - $primerTimestamp;
        $tiempoMostrar = "";
        if($tiempoTotal < 60){
            $tiempoMostrar = $tiempoTotal . " segundos";
        } elseif($tiempoTotal < 3600){
            $tiempoMostrar = round($tiempoTotal / 60) . " minutos";
        } elseif($tiempoTotal < 86400){
            $tiempoMostrar = round($tiempoTotal / 3600) . " horas";
        } else {
            $tiempoMostrar = round($tiempoTotal / 86400) . " dias";
        }
        
        // Guardar en expulsados.txt (también guarda en lista negra)
        guardarExpulsado($userId, $username, "Spam de {$tipo} (mas de 15 en {$tiempoMostrar})", "Bot (automatico)", $api, $chatId);
        
        // Eliminar mensaje
        $messageId = $update["message"]["message_id"] ?? 0;
        if($messageId){
            $dataDelete = ['chat_id' => $chatId, 'message_id' => $messageId];
            file_get_contents($api."/deleteMessage?".http_build_query($dataDelete));
        }
        
        // Expulsar usuario
        $kickData = ['chat_id' => $chatId, 'user_id' => $userId];
        file_get_contents($api."/kickChatMember?".http_build_query($kickData));
        
        // Resetear contador después de expulsar
        unset($datos[$clave]);
        file_put_contents($archivo, json_encode($datos));
        
        return true;
    }
    
    return false;
}

// ==========================
// REGISTRAR NUEVOS USUARIOS QUE SE UNEN AL GRUPO (NUEVA FUNCIÓN)
// ==========================
function registrarNuevoUsuario($update, $api){
    // Verificar si hay nuevos miembros en el grupo
    if(!isset($update["message"]["new_chat_members"])){
        return;
    }
    
    $chatId = $update["message"]["chat"]["id"];
    $chatTitle = $update["message"]["chat"]["title"] ?? "Grupo Desconocido";
    
    // Recorrer todos los nuevos miembros
    foreach($update["message"]["new_chat_members"] as $nuevoMiembro){
        $userId = $nuevoMiembro["id"];
        $username = $nuevoMiembro["username"] ?? "sin_username";
        $nombre = $nuevoMiembro["first_name"] ?? "Desconocido";
        if(isset($nuevoMiembro["last_name"])){
            $nombre .= " " . $nuevoMiembro["last_name"];
        }
        
        $fecha = date("Y-m-d H:i:s");
        
        // Guardar en archivo
        $archivo = "usuarios_nuevos.txt";
        $linea = "========================================\n";
        $linea .= "Fecha: {$fecha}\n";
        $linea .= "ID: {$userId}\n";
        $linea .= "Usuario: @{$username}\n";
        $linea .= "Nombre: {$nombre}\n";
        $linea .= "Grupo: {$chatTitle}\n";
        $linea .= "========================================\n\n";
        
        file_put_contents($archivo, $linea, FILE_APPEND | LOCK_EX);
    }
}

// ==========================
// DETECTAR NUEVOS MIEMBROS BLOQUEADOS
// ==========================
function detectarNuevoMiembro($update, $api, $usuariosBloqueados){
    if(isset($update["message"]["new_chat_members"])){
        $chatId = $update["message"]["chat"]["id"];
        
        foreach($update["message"]["new_chat_members"] as $nuevoMiembro){
            $username = $nuevoMiembro["username"] ?? "sin_username";
            $userId = $nuevoMiembro["id"];
            
            if(in_array(strtolower($username), array_map('strtolower', $usuariosBloqueados))){
                // Guardar registro detallado (también guarda en lista negra)
                guardarExpulsado($userId, $username, "Lista negra (al unirse)", "Bot (automatico)", $api, $chatId);
                
                // Expulsar al usuario bloqueado
                $kickData = [
                    'chat_id' => $chatId,
                    'user_id' => $userId
                ];
                file_get_contents($api."/kickChatMember?".http_build_query($kickData));
            }
        }
    }
}

// ==========================
// DETECTAR CUANDO UN ADMIN EXPULSA A ALGUIEN
// ==========================
function detectarExpulsionAdmin($update, $api){
    if(isset($update["message"]["left_chat_member"])){
        $chatId = $update["message"]["chat"]["id"];
        $expulsado = $update["message"]["left_chat_member"];
        $userId = $expulsado["id"];
        $username = $expulsado["username"] ?? "sin_username";
        
        if(isset($update["message"]["from"]["id"])){
            $adminId = $update["message"]["from"]["id"];
            $botId = "8542076830"; // ID de tu bot
            
            // Obtener nombre del admin que expulsó
            $adminNombre = "Administrador";
            $url = $api."/getChatMember?chat_id=".$chatId."&user_id=".$adminId;
            $result = json_decode(file_get_contents($url), true);
            if(isset($result["result"]["user"]["first_name"])){
                $adminNombre = $result["result"]["user"]["first_name"];
                if(isset($result["result"]["user"]["last_name"])){
                    $adminNombre .= " " . $result["result"]["user"]["last_name"];
                }
                if(isset($result["result"]["user"]["username"])){
                    $adminNombre .= " (@{$result["result"]["user"]["username"]})";
                }
            }
            
            // Solo guardar si NO fue el bot (evitar duplicados)
            if($adminId != $botId){
                // Guardar expulsado (también guarda en lista negra)
                guardarExpulsado($userId, $username, "Expulsado por administrador", $adminNombre, $api, $chatId);
            }
        }
    }
}

// ==========================
// MANEJO DE BOTONES (CALLBACK QUERY)
// ==========================
if(isset($update["callback_query"])){
    
    $callbackId = $update["callback_query"]["id"];
    $dataCallback = $update["callback_query"]["data"];
    $chatId = $update["callback_query"]["message"]["chat"]["id"];
    $userId = $update["callback_query"]["from"]["id"];
    $username = $update["callback_query"]["from"]["username"] ?? "";
    
    // 🔥 Si el botón es "alert_grupo" (usuario expulsado)
    if($dataCallback == "alert_grupo"){
        $alertData = [
            "callback_query_id" => $callbackId,
            "text" => "Este grupo no se puede mostrar porque violó los términos de servicio de Telegram.",
            "show_alert" => true
        ];
        file_get_contents($api."/answerCallbackQuery?".http_build_query($alertData));
        exit;
    }
}

// ==========================
// MANEJO MENSAJES
// ==========================
if(isset($update["message"])){

    // 🔥 REGISTRAR NUEVOS USUARIOS (NUEVO)
    registrarNuevoUsuario($update, $api);

    $chatType = $update["message"]["chat"]["type"];
    $chatId = $update["message"]["chat"]["id"];
    $messageId = $update["message"]["message_id"];
    $texto = $update["message"]["text"] ?? "";
    $userId = $update["message"]["from"]["id"];

    // Manejo de grupos (anti-spam)
    if($chatType == "group" || $chatType == "supergroup"){

        // 🔥 DETECTAR EXPULSIONES DE ADMINISTRADORES
        detectarExpulsionAdmin($update, $api);

        // 🔥 DETECTAR NUEVOS MIEMBROS BLOQUEADOS
        global $usuariosBloqueados;
        detectarNuevoMiembro($update, $api, $usuariosBloqueados);

        // 🔥 DETECTAR SPAM DE STICKERS, FOTOS Y VIDEOS
        if(detectarSpamMultimedia($chatId, $userId, $api)){
            return;
        }

        if(esAdmin($chatId, $userId, $api)){
            return;
        }

        if(isset($update["message"]["forward_date"])){
            expulsarYEliminar($chatId, $userId, $messageId, $api, "Reenvio de mensaje");
            return;
        }

        $palabrasProhibidas = ["@", "http", "https", "t.me", ".com", ".es", "www.", ".co"];

        foreach($palabrasProhibidas as $palabra){
            if(stripos($texto, $palabra) !== false){
                expulsarYEliminar($chatId, $userId, $messageId, $api, "Palabra prohibida: {$palabra}");
                return;
            }
        }

        return;
    }

    // Solo mensajes privados
    if($chatType != "private"){
        return;
    }

    $usuario = $update["message"]["from"]["username"] ?? "";
    $userId = $update["message"]["from"]["id"];

    // Verificar si el usuario fue expulsado del grupo (NO lo bloqueamos, solo usamos para los botones)
    $estaExpulsado = estaExpulsadoDelGrupo($userId);

    // Verificar usuario bloqueado (lista negra manual)
    global $usuariosBloqueados;
    if(in_array(strtolower($usuario), array_map('strtolower', $usuariosBloqueados))){
        // Para estos sí mostramos mensaje de "bot roto"
        $mensaje = "😞 Lo sentimos @$usuario, este bot está roto y dejó de funcionar.";
        $data = [
            'chat_id' => $chatId,
            'text' => $mensaje,
            'parse_mode' => 'HTML'
        ];
        file_get_contents($api."/sendMessage?".http_build_query($data));
        return;
    }

    // ✅ Enviar mensaje normal con botones (el botón GRUPO cambia si está expulsado)
    enviarContenidoFinal($chatId, $api, $canalLink, $grupoLink, $whatsappLink, $usuario);
}

?>
