<?php


namespace App\Services;


use App\Facade\TableName;
use App\Notification\TelegramBot;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class IpCheck
{
    public $lastLocation = null;

    // 检测是否是巴西IP
    public function ipCheck($ip, $PackageName = "com.ouro777.play", $v = 1, $go404 = false)
    {



        $origin = @$_SERVER['HTTP_HOST'];
        $stats = Redis::get("serversOriginStat");
        if (!$stats) {
            $stats = [];
        } else {
            $stats = json_decode($stats, true);
        }
        if (!isset($stats[$origin])) $stats[$origin] = 0;
        $stats[$origin]++;
        Redis::set('serversOriginStat', json_encode($stats));

        $agent = strtolower(@$_SERVER['HTTP_USER_AGENT']);
//        $ios = 0;
//        if ( strstr( $agent, 'iphone' ) || strstr( $agent, 'ipad' ) ) {
//            $ios = 1;
//        }
//        if($ios){
//        }
//        return false;
        return true;


        // split3[0] * 1000000000 + split3[1] * 1000000 + split3[2] * 1000 + parseInt(split3[3]);
        $explode = explode('.', $ip);
        if (count($explode) < 4) {
            return false;
        }

        $valueN = $explode[0] * 1000000 + $explode[1] * 1000 + (int)$explode[2];

        $value = $explode[0] * 1000000000 + $explode[1] * 1000000 + $explode[2] * 1000 + (int)$explode[3];

        return true;
        //调试加白区
        if ($ip == '92.98.30.151') {
            return 'BR';
        }
        //mysg home  $valueN==117020154 starhub sg
        if ($ip == '116.87.197.194' || $ip == '183.192.138.113' || $ip == '8.222.157.68' || $valueN == 117020154) {
//            return "MXX";
            return 'BR';
        }
        if ($ip == '47.237.107.111') {
            return 'BR';
        }

        if ($ip == '172.233.20.45') {
            return 'CO';
        }

        $closeApks = ["com.fortuna.sol.slots", "com.lucky.athena.boa", "com.niubility.pg.tig", "com.lendario.game.slots", "com.glorygame.slotwin", "com.wtmdjsg.hapfun", "com.golden777.redstorm", "iam.thebest.tiger", "com.coins777.ouro", "com.wildwestduals.slot777", "com.wildwestduals.slot888", "com.fortuna.sol.slots", "com.luckygame.ate"];
        if (in_array($PackageName, $closeApks)) {
            Util::WriteLog('inreview', $this->saveToIpBlack($valueN, $ip, 'close' . $PackageName . "_$v"));
            if ($go404) {
                http_response_code(404);
                exit();
            } else {
                return 0;
            }
        }


        //针对审核的逻辑

        if (Redis::exists("InReview_{$PackageName}")) {
            $InReview = Redis::get("InReview_{$PackageName}");
        } else {
            $app = DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
                ->where('PackageName', $PackageName)->select("InReview")->first();
            if (!isset($app) || empty($app)) {
                if (!Redis::exists("IpCheck_Error_{$ip}")) {
                    $result = $this->getIpLocation($ip);
                    $agent = @$_SERVER['HTTP_USER_AGENT'] ?? "";
                    $refer = @$_SERVER["HTTP_REFERER"] ?? "";
                    $locale = @$_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? "";
                    $url = @$_SERVER['HTTP_HOST'] . @$_SERVER['REQUEST_URI'];
                    TelegramBot::getDefault()->sendProgramNotify("CheckIP", "$PackageName not found", compact('url', 'locale', 'result', 'agent', 'refer'));
                }
                Redis::set("IpCheck_Error_{$ip}", $ip);
                Redis::expire("IpCheck_Error_{$ip}", 3600);
//                $InReview=1;
            } else {
                $InReview = $app->InReview;
                Redis::set("InReview_{$PackageName}", $InReview);
                Redis::expire("InReview_{$PackageName}", 3600);
            }
        }
        $InReview = intval($InReview);
        if ($InReview == 1 || in_array($PackageName, [])) {
            Util::WriteLog('inreview', $this->saveToIpBlack($valueN, $ip, 'review' . $PackageName . "_$v"));
            return 0;
        }


        //特殊号段屏蔽
        if (in_array($explode[0] . '.' . $explode[1], ["45.133", "66.102"])) {
            Util::WriteLog("ipblocked", $this->saveToIpBlack($valueN, $ip, 'review' . $PackageName . "_$v"));
            if ($go404) {
                http_response_code(404);
                exit();
            } else {
                return 0;
            }
        }

        //先进行黑名单检查
        $blacklist = DB::table(TableName::QPAccountsDB() . 'CheckIPBlack')->where('IP', $valueN)->exists();
        if ($blacklist) {
            Util::WriteLog("ipblocked", $this->saveToIpBlack($valueN, $ip, 'review' . $PackageName . "_$v"));//compact('valueN','ip','PackageName','v'));
            if ($go404) {
                http_response_code(404);
                exit();
            } else {
                return false;
            }
        }


//        $mxPackages=["com.game.dream.snake","com.game.dream.snake2","com.secggplcheck.ott","com.west.frzyapp","com.halloween.appwin","com.candle.abyssalapex","com.candlegamesprime.basketball"];

        //本地数据库搜索
        $result = @DB::table(TableName::QPAccountsDB() . 'CheckIP')->where('IP', $valueN)->select("Country")->first();
        $existCountry = $result->Country ?? null;
        //判断巴西
        if (in_array($existCountry, self::$validCountries)) {
            return $existCountry;
        }


        //{"ip":"45.233.55.215","ip_number":"770258903","ip_version":4,"country_name":"Brazil","country_code2":"BR","isp":"Fox Net Provedor de Acesso Ltda ME","response_code":"200","response_message":"OK"}
        //不存在库中开始搜索
        $ipsearchs = [];
        try {
            $result = $this->getIpLocation($ip);
            $ipsearchs[] = $result;
            //入库
            if (isset($result['country_name'])) {

                $this->saveToIpDatabase($valueN, $result['country_code2'], $result['isp']);
                //m247 必杀
                if (strstr($result['isp'], "M247") || strstr($result['isp'], "Google") || strstr($result['isp'], "YouTube") || strstr($result['isp'], "Apple")) {
                    Util::WriteLog("ipblocked", $this->saveToIpBlack($valueN, $ip, 'm247_' . $PackageName . "_$v"));
                    return false;
                }


                if (in_array($result['country_code2'], self::$validCountries)) {
                    return $result['country_code2'];
                } else if (in_array($result['isp'], ['OVH US LLC', 'Oneclick Hosting', 'OVH Hosting Inc.', 'OVH SAS', 'Oracle Corporation'])) {
                    $this->saveToIpDatabase($valueN, 'BR', $result['isp']);
                    return 'BR';
                }

                Log::channel('ip')->info($result);

                //手动证明的补充信息
                if (in_array($explode[0] . '.' . $explode[1], ["148.78", "15.235", "135.148", "149.56"])) {
                    $this->saveToIpDatabase($valueN, 'BR', $result['isp']);
                    //OVH SAS
                    return 'BR';
                }

            }


        } catch (\Exception $e) {
            Log::channel('ip')->info($ip);
            Log::channel('ip')->info($e->getMessage());
        }
        try {
            //二叉
            $result = $this->iplogger($ip);
            $result = $result['result'];
            $ipsearchs[] = $result;
            if (isset($result['country_name'])) {

                $this->saveToIpDatabase($valueN, $result['country'], $result['isp']);

                if (strstr($result['isp'], "M247") || strstr($result['isp'], "Google") || strstr($result['isp'], "YouTube")) {
                    Util::WriteLog("ipblocked", $this->saveToIpBlack($valueN, $ip, 'm247_' . $PackageName . "_$v"));
                    return false;
                }
                if (in_array($result['country'], self::$validCountries)) {
                    return $result['country'];
                }
            }

        } catch (\Exception $e) {
            Log::channel('ip')->info($ip);
            Log::channel('ip')->info($e->getMessage());
        }

        if(strstr($PackageName,'com.ouro777.ares')){
            return 'BR';
        }


        Util::WriteLog("ipblocked", $ipsearchs);

        //////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////
//        $ipLibrary = config('ipCheck');
//        $data = collect(json_decode($ipLibrary, true));

//        $r = $data
//            ->where('start', '<=', $value)
//            ->where('end', '>=', $value)
//            ->first();

//        if (empty($r)) {
//            Util::WriteLog("ipblocked",$ipsearchs);
//            return false;
//        }else{
//            Util::WriteLog("findbyconfig",$ipsearchs);
//        }
//        Util::WriteLog("ipblocked", $this->saveToIpBlack($valueN, $ip, 'notknow' . $PackageName . "_$v"));
        return true;
    }

    private function saveToIpDatabase($valueN, $countryCode, $isp)
    {
        DB::table(TableName::QPAccountsDB() . 'CheckIP')->updateOrInsert(['IP' => $valueN], ['IP' => $valueN, 'Country' => strtoupper($countryCode), 'isp' => $isp]);
    }

    private function saveToIpBlack($valueN, $ip, $reason)
    {
        $result = $this->getIpLocation($ip);
        $agent = @$_SERVER['HTTP_USER_AGENT'] ?? "";
        //入库
//        DB::table(TableName::QPAccountsDB() . 'CheckIPBlack')->updateOrInsert(['IP' => $valueN], ['IP' => $valueN, 'Country' => strtoupper($result['country_code2']??''), 'isp' => $result['isp']??'', 'reason' => $reason,'date'=>date('Y-m-d H:i:s')]);
        $arr = ['IP' => $valueN, 'Country' => strtoupper($result['country_code2'] ?? ''), 'isp' => $result['isp'] ?? '', 'reason' => $reason, 'date' => date('Y-m-d H:i:s'), 'agent' => $agent];
        $record = DB::table(TableName::QPAccountsDB() . 'CheckIPBlack')->select("IP", "reason", "agent")->orderByDesc("id")->first();

        $record = (array)$record;
        if (isset($record) && $record['IP'] == $arr['IP'] && $record['agent'] == $arr['agent'] && $record['reason'] == $arr['reason']) {

        } else {
            DB::table(TableName::QPAccountsDB() . 'CheckIPBlack')->insert($arr);
        }

        return $result;
    }

    /**
     * @param $ip
     * @return {"result":{"ip":"192.99.235.224","timezone":"America\/Sao_Paulo","offset":"UTC -03:00","localtime":"June 1, 2023 at 5:11 AM","eu":false,"continent":"sa","continent_name":"South America","country":"br","country_name":"Brazil","city":"Inhapim","state":"Minas Gerais","district":"Inhapim","zipcode":"- - -","latitude":-19.5492,"longitude":-42.12,"isp":"OVH Hosting","organization":"OVH SAS","connection":"Corporate","weather_station":"BRXX0568"},"timezone":"Asia\/Shanghai","language":"us","balance":9997}
     */
    public function iplogger($ip)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.iplogger.org/ip/main/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'X-token: api_0viCf5BdhjzKlZT2E2JywrpbCY1BLJSl',
            'Content-Type: multipart/form-data'
        ]);
        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'ip' => $ip
        ]);

        $res = curl_exec($ch);
        curl_close($ch);

        $res = trim($res);
//        Log::channel('ip')->info('iplogger:'.$res);

        $res = \GuzzleHttp\json_decode($res, true);
        $this->lastLocation = $res;
        return $res;


    }

    public function getIpLocation($ip)
    {
        $result = [];
        try {
            $data = file_get_contents("https://api.iplocation.net/?ip=" . $ip);
            $result = \GuzzleHttp\json_decode($data, true);

        } catch (\Exception $e) {
            Log::channel('ip')->info($ip);
            Log::channel('ip')->info($e->getMessage());
        }
        $this->lastLocation = $result;
        return $result;
    }
    public static function getGeoLocation($ip)
    {
        $ipcheck = new IpCheck();
        $result = $ipcheck->iplogger($ip);
        $insert=[];
        if (isset($result) && isset($result['isp'])) {
            $insert['isp'] = $result['isp'];
            $insert['country'] = $result['country'];
            $insert['city'] = $result['city'];
        } else {
            $result = $ipcheck->getIpLocation($ip);

            if (isset($result) && isset($result['isp'])) {
                $insert['isp'] = $result['isp'];
                $insert['country'] = $result['country_code2'];
                $insert['city'] = '';
            }
        }
        return $insert;
    }

    public static $validCountries = ['BR','BD', 'MX', 'CO', 'AR', 'PE', 'CL','PK','US'];
    public static $countries = [
        'BD' => [
            'country'          => 'Bangladesh',
            'phone_code'       => '880',
            'population'       => 16400, // 16400万
            'currency_symbol'  => '৳',
            'currency_code'    => 'BDT',
            'usd_exchange_rate'=> 80,
            'language_code'    => 'bn-BD',
            'phone_length'     => '10,11'
        ],
        'PK' => [

            'country'           => 'Pakistan',
            'phone_code'        => '92',
            'population'        => 23100, // 23100万
            'currency_symbol'   => 'Rs',
            'currency_code'     => 'PKR',
            'usd_exchange_rate' => 280,
            'language_code'     => 'ur-PK',
            'phone_length'      => '10,11'
        ],
        'US' => [
            'country'          => 'United States',
            'phone_code'       => '1',
            'population'       => 33200, // 33200万
            'currency_symbol'  => '$',
            'currency_code'    => 'USD',
            'usd_exchange_rate'=> 1,
            'language_code'    => 'en-US',
            'phone_length'     => '10'
        ],
        'BR' => [
            'country'          => 'Brazil',
            'phone_code'       => '55',
            'population'       => 21400, // 21400万
            'currency_symbol'  => 'R$',
            'currency_code'    => 'BRL',
            'usd_exchange_rate'=> 5,
            'language_code'    => 'pt-BR',
            'phone_length'     => '10,11'
        ],
        'MX' => [
            'country'          => 'Mexico',
            'phone_code'       => '52',
            'population'       => 13000, // 13000万
            'currency_symbol'  => 'M$',
            'currency_code'    => 'MXN',
            'usd_exchange_rate'=> 18,
            'language_code'    => 'es-MX',
            'phone_length'     => '10'
        ],
        'CO' => [
            'country'          => 'Colombia',
            'phone_code'       => '57',
            'population'       => 5100, // 5100万
            'currency_symbol'  => 'COL$',
            'currency_code'    => 'COP',
            'usd_exchange_rate'=> 4000,
            'language_code'    => 'es-CO',
            'phone_length'     => '10'
        ],
        'AR' => [
            'country'          => 'Argentina',
            'phone_code'       => '54',
            'population'       => 4500, // 4500万
            'currency_symbol'  => '$',
            'currency_code'    => 'ARS',
            'usd_exchange_rate'=> 350,
            'language_code'    => 'es-AR',
            'phone_length'     => '7,10'
        ],
        'CA' => [
            'country'          => 'Canada',
            'phone_code'       => '1',
            'population'       => 3800, // 3800万
            'currency_symbol'  => 'C$',
            'currency_code'    => 'CAD',
            'usd_exchange_rate'=> 1.3,
            'language_code'    => 'en-CA',
            'phone_length'     => '10'
        ],
        'PE' => [
            'country'          => 'Peru',
            'phone_code'       => '51',
            'population'       => 3300, // 3300万
            'currency_symbol'  => 'S/.',
            'currency_code'    => 'PEN',
            'usd_exchange_rate'=> 4,
            'language_code'    => 'es-PE',
            'phone_length'     => '9'
        ],
        'VE' => [
            'country'          => 'Venezuela',
            'phone_code'       => '58',
            'population'       => 2800, // 2800万
            'currency_symbol'  => 'Bs.',
            'currency_code'    => 'VES',
            'usd_exchange_rate'=> 25,
            'language_code'    => 'es-VE',
            'phone_length'     => '10'
        ],
        'CL' => [
            'country'          => 'Chile',
            'phone_code'       => '56',
            'population'       => 1900, // 1900万
            'currency_symbol'  => '$',
            'currency_code'    => 'CLP',
            'usd_exchange_rate'=> 850,
            'language_code'    => 'es-CL',
            'phone_length'     => '9'
        ],
        'GT' => [
            'country'          => 'Guatemala',
            'phone_code'       => '502',
            'population'       => 1800, // 1800万
            'currency_symbol'  => 'Q',
            'currency_code'    => 'GTQ',
            'usd_exchange_rate'=> 8,
            'language_code'    => 'es-GT',
            'phone_length'     => '8'
        ],
        'EC' => [
            'country'          => 'Ecuador',
            'phone_code'       => '593',
            'population'       => 1800, // 1800万
            'currency_symbol'  => '$',
            'currency_code'    => 'USD',
            'usd_exchange_rate'=> 1,
            'language_code'    => 'es-EC',
            'phone_length'     => '9'
        ],
        'BO' => [
            'country'          => 'Bolivia',
            'phone_code'       => '591',
            'population'       => 1200, // 1200万
            'currency_symbol'  => 'Bs.',
            'currency_code'    => 'BOB',
            'usd_exchange_rate'=> 7,
            'language_code'    => 'es-BO',
            'phone_length'     => '8'
        ],
        // 添加其他国家的数据...
    ];

}
