<?php

class ScriptRun
{
    private $params = [];
    private $uri = '';

    const JUMP_URLS = [
        'Qu5Ai0'    => 'https://test-h5.quaiapp.com/landing/quaiios.html?cid=13',
        'q3'        => 'https://h5.hnyimo.com/landing/ketian.html?cid=39',
        'q1'        => 'https://h5.quaiapp.com/landing/index.html?cid=13',
        'q2'        => 'https://h5.quaiapp.com/landing/quaiios.html?cid=13',
        'k1'        => 'https://h5.hnyimo.com/landing/keqin.html?cid=39',
        'k2'        => 'https://h5.hnyimo.com/landing/keqinios.html?cid=56',
        'k2_test'   => 'https://h5.hnyimo.com/landing/keqinios.html?cid=56',
        't1'        => 'https://h5.lejingwl.cn/landing/tianyu.html?cid=75',
        't2'        => 'https://h5.lejingwl.cn/landing/tianyuios.html?cid=81',
        'k2_test'   => 'https://h5.lejingwl.cn/landing/keqinios.html?cid=75',
    ];
    const DEFAULT_URL = 'https://hnyimo.com/index.html';

    const APP_MAPS = [
        'Qu5Ai0' => 'quai_ios',
        'q3' => 'ketian',
        'q1' => 'quai',
        'q2' => 'quai_ios',
        'k1' => 'ketian',
        'k2' => 'ketian',
        'k2_test' => 'ketian',
        't1' => 'tianyu',
        't2' => 'tianyu_ios',
        't1_test' => 'ketian'
    ];

    public function __construct()
    {
        $this->params = $_GET;
        $this->uri = $_SERVER['REQUEST_URI'];
        $this->run();
    }

    public function run() {
        $this->clickSmsJump();
    }

    private function clickSmsJump()
    {
        // $uri = $_SERVER['REQUEST_URI'];
        $path = trim(parse_url($this->uri, PHP_URL_PATH),'/');
        $source = $this->params['s'] ?? '';
        $jumpUrl = self::JUMP_URLS[$path] ?? self::DEFAULT_URL;
        $appKey = self::APP_MAPS[$path] ?? '';

        $this->incrClick('sms_callback_click_num:' . $appKey . ':', $source);
        $this->cacheUserClick(trim($path, '/'), $source);
        // echo $jumpUrl;
        header('Location: ' . $jumpUrl);
    }

    private function getCurrentUrl()
    {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
        $host = $_SERVER['HTTP_HOST'];
        $uri = $_SERVER['REQUEST_URI'];
        return $protocol . $host . $uri;
    }

    private function getRedis()
    {
        $t = $_GET['t'] ?? '';
        if ($t == 'ttt') {
            $redisHost = '47.112.118.120';
            $redisAuth = 'Zbw0C3Nx';
            $redisPort = 6366;
            $redisDb = 11;
        } else {
            $redisHost = 'r-wz9gkxzjjb177nflvk.redis.rds.aliyuncs.com';
            $redisAuth = 'Hw3pzBnioDGjWbZE';
            $redisPort = 6379;
            $redisDb = 11;
        }

        $redis = new Redis();
        // 连接到 Redis
        $redis->connect($redisHost, $redisPort);
        // 认证
        if ($redis->auth($redisAuth) == false) {
            // die($redis->getLastError());
            $this->sendFeishuMessage($redis->getLastError(), '', 'error');
        }
        // 选择数据库
        $redis->select($redisDb);
        return $redis;
    }

    private function incrClick($key, $s = '')
    {
        if ($s != 's') {
            return;
        }
        if ($key == '') {
            return;
        }
        $ip = $this->getUserIP();
        $redis = $this->getRedis();
        if (!$redis->set($key . $ip, 1, ['NX', 'EX' => 2])) {
            return;
        }
        $key = $key . date('Y-m-d');
        $redis->incr($key, 1);
        if ($redis->ttl($key) < 0) {
            $redis->expire($key, 86400 * 7);
        }

        if ($redis) {
            $redis->close();
        }
        // sendFeishuMessage($s,$key,$ip);
    }

    private function sendFeishuMessage($s, $p, $ip)
    {
        // 构建请求数据
        $webhookUrl = 'https://open.feishu.cn/open-apis/bot/v2/hook/9003517c-6d96-4ce7-88e9-67f388c4cf17';
        $data = [
            "msg_type" => "text",
            "content" => [
                "text" => 's=' . $s . '--p=' . $p . '--' . $ip . '的用户点击召回链接'
            ]
        ];
        // 初始化 cURL
        $ch = curl_init($webhookUrl);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen(json_encode($data))
        ]);
        // 发送请求
        $response = curl_exec($ch);
        curl_close($ch);
    }

    private function getUserIP()
    {
        // 检查是否通过代理访问
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 可能有多个 IP 地址，取第一个
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            // 检查是否通过共享互联网访问
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            // 获取直接访问的 IP 地址
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    private function cacheUserClick($path = '', $s)
    {
        //   sendFeishuMessage($path,$s,'cacheUserClick');
        if ($s != 's') {
            return;
        }
        if (empty($path)) {
            return;
        }
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $device = preg_match('/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i', $userAgent) ? 'mobile' : 'desktop';
        $osVersionStr = '';
        $osVersion = '';
        if (preg_match('/(iPhone|iPad|iPod)/i', $userAgent)) {
            preg_match('/(\d+)_(\d+)_?(\d+)?/', $userAgent, $osVersion);
            if (!empty($osVersion)) {
                $str = implode('.', array_filter([$osVersion[1], $osVersion[2], $osVersion[3]]));
                $osVersionStr = $device . '_ios_' . $str;
            }
        } elseif (preg_match('/Android/i', $userAgent)) {
            preg_match('/Android\s([\d\.]+)/', $userAgent, $osVersion);
            if (!empty($osVersion)) {
                $osVArr = explode('.', $osVersion[1]);
                $osVersionStr = $device . '_android_' . $osVArr[0];
            }
        }
        if (!empty($osVersionStr)) {
            $ip = $this->getUserIP();
            $redis = $this->getRedis();
            $strKey = $ip . '|' . $osVersionStr;
            $key = 'sms_callback_click_data:' . $strKey;
            $redis->set($key, date('Y-m-d H:i:s'), ['NX', 'EX' => 86400 * 7]);
            $this->sendFeishuMessage($key, '', 'cacheUserClick');
        }
        // 输出结果
        // 输出结果
        // echo "设备类型: $device\n";
        // echo "操作系统版本: $osVersionStr\n";
        if ($redis) {
            $redis->close();
        }
    }
}

(new ScriptRun)->run();