<?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);

// ==========================
// ?? MANEJO DE SOLICITUDES DE INGRESO (NUEVO)
// ==========================
if(isset($update["chat_join_request"])){
    manejarSolicitudIngreso($update, $api, $usuariosBloqueados);
    exit;
}

// ==========================
// ?? PROCESAR SOLICITUDES PENDIENTES (CRON)
// ==========================
procesarSolicitudesPendientes($api);

// USERNAMES
$canalUsername = "@fiufiu7";
$grupoUsername = "@El7culoss";

// LINKS
$canalLink = "https://t.me/fiufiu7";
$grupoLink = "https://t.me/El7culoss";
$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
// ==========================

// ?? NUEVAS FUNCIONES PARA APROBACIÓN
function manejarSolicitudIngreso($update, $api, $usuariosBloqueados){
    if(!isset($update["chat_join_request"])){
        return;
    }
    
    $solicitud = $update["chat_join_request"];
    $userId = $solicitud["from"]["id"];
    $username = $solicitud["from"]["username"] ?? "sin_username";
    $nombre = $solicitud["from"]["first_name"] ?? "Desconocido";
    if(isset($solicitud["from"]["last_name"])){
        $nombre .= " " . $solicitud["from"]["last_name"];
    }
    $chatId = $solicitud["chat"]["id"];
    $fecha = date("Y-m-d H:i:s");
    
    $estaBloqueado = in_array(strtolower($username), array_map('strtolower', $usuariosBloqueados));
    
    if(!$estaBloqueado){
        $archivoNegra = "expulsados_grupo.txt";
        if(file_exists($archivoNegra)){
            $expulsados = file($archivoNegra, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if(in_array($userId, $expulsados)){
                $estaBloqueado = true;
            }
        }
    }
    
    if($estaBloqueado){
        $approveData = ['chat_id' => $chatId, 'user_id' => $userId];
        file_get_contents($api."/approveChatJoinRequest?".http_build_query($approveData));
        
        $kickData = ['chat_id' => $chatId, 'user_id' => $userId];
        file_get_contents($api."/kickChatMember?".http_build_query($kickData));
        
        $archivoExpulsados = "expulsados.txt";
        $lineaExpulsion = "========================================\n";
        $lineaExpulsion .= "Fecha: {$fecha}\n";
        $lineaExpulsion .= "ID: {$userId}\n";
        $lineaExpulsion .= "Usuario: @{$username}\n";
        $lineaExpulsion .= "Nombre: {$nombre}\n";
        $lineaExpulsion .= "Razon: Lista negra (aprobado y expulsado)\n";
        $lineaExpulsion .= "Expulsado por: Bot (automatico)\n";
        $lineaExpulsion .= "========================================\n\n";
        file_put_contents($archivoExpulsados, $lineaExpulsion, FILE_APPEND | LOCK_EX);
        return;
    }
    
    $archivoPendientes = "solicitudes_pendientes.txt";
    $timestamp = time();
    $lineaPendiente = $userId . "|" . $chatId . "|" . $timestamp . "|" . $username . "|" . $nombre . "\n";
    file_put_contents($archivoPendientes, $lineaPendiente, FILE_APPEND | LOCK_EX);
    
    $mensajeConfirmacion = "? Hemos recibido tu solicitud para unirte al grupo.\n\n";
    $mensajeConfirmacion .= "? Tu solicitud será procesada en aproximadamente 1 minuto.\n";
    $mensajeConfirmacion .= "?? Recibirás una notificación cuando seas aceptado.\n\n";
    $mensajeConfirmacion .= "?? Si eres un bot o una cuenta automatizada, serás expulsado automáticamente.";
    
    $dataMensaje = [
        'chat_id' => $userId,
        'text' => $mensajeConfirmacion,
        'parse_mode' => 'HTML'
    ];
    file_get_contents($api."/sendMessage?".http_build_query($dataMensaje));
    
    $archivoSolicitudes = "solicitudes_de_ingreso.txt";
    $linea = "========================================\n";
    $linea .= "Fecha: {$fecha}\n";
    $linea .= "ID: {$userId}\n";
    $linea .= "Usuario: @{$username}\n";
    $linea .= "Nombre: {$nombre}\n";
    $linea .= "Estado: Pendiente de aprobación (1 minuto)\n";
    $linea .= "========================================\n\n";
    file_put_contents($archivoSolicitudes, $linea, FILE_APPEND | LOCK_EX);
}

function procesarSolicitudesPendientes($api){
    $archivoPendientes = "solicitudes_pendientes.txt";
    if(!file_exists($archivoPendientes)){
        return;
    }
    
    $lineas = file($archivoPendientes, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if(empty($lineas)){
        return;
    }
    
    $nuevasLineas = [];
    $tiempoEspera = 60;
    $ahora = time();
    
    foreach($lineas as $linea){
        $datos = explode("|", $linea);
        if(count($datos) < 3){
            continue;
        }
        
        $userId = $datos[0];
        $chatId = $datos[1];
        $timestamp = intval($datos[2]);
        $username = $datos[3] ?? "sin_username";
        $nombre = $datos[4] ?? "Desconocido";
        
        if(($ahora - $timestamp) >= $tiempoEspera){
            $approveData = ['chat_id' => $chatId, 'user_id' => $userId];
            $response = file_get_contents($api."/approveChatJoinRequest?".http_build_query($approveData));
            
            if($response !== false){
                $archivoAprobados = "solicitudes_aprobadas.txt";
                $fecha = date("Y-m-d H:i:s");
                $lineaAprobado = "========================================\n";
                $lineaAprobado .= "Fecha: {$fecha}\n";
                $lineaAprobado .= "ID: {$userId}\n";
                $lineaAprobado .= "Usuario: @{$username}\n";
                $lineaAprobado .= "Nombre: {$nombre}\n";
                $lineaAprobado .= "Estado: APROBADA AUTOMÁTICAMENTE (1 minuto)\n";
                $lineaAprobado .= "========================================\n\n";
                file_put_contents($archivoAprobados, $lineaAprobado, FILE_APPEND | LOCK_EX);
                
                $mensajeBienvenida = "?? ¡Bienvenido @{$username} al grupo 7FIUFIU!\n\n";
                $mensajeBienvenida .= "? Tu solicitud ha sido aprobada.\n";
                $mensajeBienvenida .= "?? Ya puedes participar en el grupo.\n\n";
                $mensajeBienvenida .= "?? Recuerda seguir las normas del grupo.";
                
                $dataMensaje = [
                    'chat_id' => $userId,
                    'text' => $mensajeBienvenida,
                    'parse_mode' => 'HTML'
                ];
                file_get_contents($api."/sendMessage?".http_build_query($dataMensaje));
            } else {
                $nuevasLineas[] = $linea;
            }
        } else {
            $nuevasLineas[] = $linea;
        }
    }
    
    file_put_contents($archivoPendientes, implode("\n", $nuevasLineas));
}

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";

    $inlineKeyboard = [];
    
    if($estaExpulsado){
        $inlineKeyboard[] = [
            ["text" => "?? GRUPO 7FIUFIU OFICIAL", "callback_data" => "alert_grupo"]
        ];
    } else {
        $inlineKeyboard[] = [
            ["text" => "?? GRUPO 7FIUFIU OFICIAL", "url" => $grupoLink]
        ];
    }
    
    $inlineKeyboard[] = [
        ["text" => "?? CANAL DEL 7FIUFIU", "url" => $canalLink]
    ];
    
    $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){
    $archivo = "expulsados.txt";
    
    $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);
    
    $archivoNegra = "expulsados_grupo.txt";
    $lineaNegra = $userId . "\n";
    file_put_contents($archivoNegra, $lineaNegra, FILE_APPEND | LOCK_EX);
}

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);
}

function expulsarYEliminar($chatId, $userId, $messageId, $api, $razon = "Spam"){
    global $update;
    
    $username = $update["message"]["from"]["username"] ?? "sin_username";
    
    guardarExpulsado($userId, $username, $razon, "Bot (automatico)", $api, $chatId);
    
    $dataDelete = [
        'chat_id' => $chatId,
        'message_id' => $messageId
    ];
    file_get_contents($api."/deleteMessage?".http_build_query($dataDelete));
    
    $kickData = [
        'chat_id' => $chatId,
        'user_id' => $userId
    ];
    file_get_contents($api."/kickChatMember?".http_build_query($kickData));
}

function detectarSpamMultimedia($chatId, $userId, $api){
    global $update;
    
    if(esAdmin($chatId, $userId, $api)){
        return false;
    }
    
    $esFoto = isset($update["message"]["photo"]);
    $esVideo = isset($update["message"]["video"]);
    $esSticker = isset($update["message"]["sticker"]);
    
    if(!$esFoto && !$esVideo && !$esSticker){
        return false;
    }
    
    $archivo = "spam_multimedia_log.txt";
    
    $datos = [];
    if(file_exists($archivo)){
        $contenido = file_get_contents($archivo);
        if($contenido){
            $datos = json_decode($contenido, true) ?: [];
        }
    }
    
    $clave = $chatId . "_" . $userId;
    $ahora = time();
    
    if(!isset($datos[$clave])){
        $datos[$clave] = ['tiempos' => []];
    }
    
    $datos[$clave]['tiempos'] = array_filter($datos[$clave]['tiempos'], function($timestamp) use ($ahora) {
        return ($ahora - $timestamp) <= 86400;
    });
    
    $datos[$clave]['tiempos'][] = $ahora;
    $total = count($datos[$clave]['tiempos']);
    
    file_put_contents($archivo, json_encode($datos));
    
    if($total > 15){
        $username = $update["message"]["from"]["username"] ?? "sin_username";
        
        $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";
        
        $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";
        }
        
        guardarExpulsado($userId, $username, "Spam de {$tipo} (mas de 15 en {$tiempoMostrar})", "Bot (automatico)", $api, $chatId);
        
        $messageId = $update["message"]["message_id"] ?? 0;
        if($messageId){
            $dataDelete = ['chat_id' => $chatId, 'message_id' => $messageId];
            file_get_contents($api."/deleteMessage?".http_build_query($dataDelete));
        }
        
        $kickData = ['chat_id' => $chatId, 'user_id' => $userId];
        file_get_contents($api."/kickChatMember?".http_build_query($kickData));
        
        unset($datos[$clave]);
        file_put_contents($archivo, json_encode($datos));
        
        return true;
    }
    
    return false;
}

function registrarNuevoUsuario($update, $api){
    if(!isset($update["message"]["new_chat_members"])){
        return;
    }
    
    $chatId = $update["message"]["chat"]["id"];
    $chatTitle = $update["message"]["chat"]["title"] ?? "Grupo Desconocido";
    
    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");
        
        $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);
    }
}

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))){
                guardarExpulsado($userId, $username, "Lista negra (al unirse)", "Bot (automatico)", $api, $chatId);
                
                $kickData = [
                    'chat_id' => $chatId,
                    'user_id' => $userId
                ];
                file_get_contents($api."/kickChatMember?".http_build_query($kickData));
            }
        }
    }
}

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";
            
            $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"]})";
                }
            }
            
            if($adminId != $botId){
                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"] ?? "";
    
    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"])){

    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"];

    if($chatType == "group" || $chatType == "supergroup"){

        detectarExpulsionAdmin($update, $api);
        global $usuariosBloqueados;
        detectarNuevoMiembro($update, $api, $usuariosBloqueados);

        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;
    }

    if($chatType != "private"){
        return;
    }

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

    $estaExpulsado = estaExpulsadoDelGrupo($userId);

    global $usuariosBloqueados;
    if(in_array(strtolower($usuario), array_map('strtolower', $usuariosBloqueados))){
        $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;
    }

    enviarContenidoFinal($chatId, $api, $canalLink, $grupoLink, $whatsappLink, $usuario);
}

?>