<?php

namespace App\Http\Controllers\Api;

use App\Facade\TableName;
use App\Http\Controllers\Controller;
use App\IpLocation;
use App\Models\AccountsInfo;
use App\Models\AgentClickLog;
use App\Models\AgentUserInfo;
use App\Models\AgentUserRecord;
use App\Services\IpCheck;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AgentClickController extends Controller
{
    /**
     * 记录链接点击信息
     */
    public function recordClickPage(Request $request)
    {
        // 获取邀请码
        $code = $request->query('code');

        if (empty($code)||strlen($code)>6) {
            return response()->json([
                'success' => false,
                'message' => 'Invitation code is required'
            ], 400);
        }

        $ip=IpLocation::getIP();
        $agent=$_SERVER['HTTP_USER_AGENT'];

        if(AgentClickLog::query()->where('client_ip',$ip)->where('user_agent',$agent)->exists()){

        }else{
            // 检查邀请码是否存在
            $agentInfo = AgentUserInfo::where('referral_code', $code)->first();
            if (!$agentInfo) {
                // 仍然记录点击，但标记为无效
                $isValid = false;
            } else {
                $isValid = true;
            }
            $res=IpCheck::getGeoLocation($ip);
            // 检测设备类型
            $deviceType = AgentClickLog::detectDeviceType($agent);

            $referrer = $_SERVER['HTTP_ORIGIN'] ??$_SERVER['HTTP_REFERER']?? '';
            // 记录点击信息
            $clickLog = new AgentClickLog();
            $clickLog->code = $code;
            $clickLog->country = $res['country'];
            $clickLog->city = $res['city'];
            $clickLog->user_agent = $agent;
            $clickLog->client_ip = $ip;
            $clickLog->referrer = $referrer;
            $clickLog->device_type = $deviceType;
            $clickLog->is_valid = $isValid ? 1 : 0;
            $clickLog->save();
        }
        return "OK";

    }
    /**
     * 记录链接点击信息
     */
    public function recordClick(Request $request)
    {
        // 获取邀请码
        $code = $request->query('code');

        if (empty($code)||strlen($code)>6) {
            return response()->json([
                'success' => false,
                'message' => 'Invitation code is required'
            ], 400);
        }

        // 检查邀请码是否存在
        $agentInfo = AgentUserInfo::where('referral_code', $code)->first();
        if (!$agentInfo) {
            // 仍然记录点击，但标记为无效
            $isValid = false;
        } else {
            $isValid = true;
        }

        // 解析add参数中的JSON数据
        $addParam = $request->query('add');
        $clickData = [];

        if (!empty($addParam)) {
            try {
                $clickData = json_decode(urldecode($addParam), true) ?: [];
            } catch (\Exception $e) {
                Log::error('Error decoding click data: ' . $e->getMessage());
                $clickData = [];
            }
        }

        // 获取客户端信息
        $userAgent = $clickData['userAgent'] ?? $request->header('User-Agent');
        $country = $clickData['country'] ?? null;
        $city = $clickData['city'] ?? null;
        $clientIp = $clickData['clientIp'] ?? $request->ip();
        $referrer = $request->header('referer');

        // 检测设备类型
        $deviceType = AgentClickLog::detectDeviceType($userAgent);

        // 记录点击信息
        $clickLog = new AgentClickLog();
        $clickLog->code = $code;
        $clickLog->country = $country;
        $clickLog->city = $city;
        $clickLog->user_agent = $userAgent;
        $clickLog->client_ip = $clientIp;
        $clickLog->referrer = $referrer;
        $clickLog->device_type = $deviceType;
        $clickLog->is_valid = $isValid ? 1 : 0;
        $clickLog->save();

        // 如果需要重定向到某个页面
        if ($request->has('redirect')) {
            return redirect($request->query('redirect'));
        }

        // 返回1x1透明GIF图像
        $gif = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        return response($gif, 200)
            ->header('Content-Type', 'image/gif')
            ->header('Content-Length', strlen($gif));
    }
    static function changePlatformData($orgChannel,$newChannel)
    {
        DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
            ->where('DateID', date('Ymd'))
            ->where('Channel', $orgChannel)
            ->update(['RegPeple'=>DB::raw('RegPeple-1'),'ActivePeple'=>DB::raw('ActivePeple-1')]);

        DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
            ->where('DateID', date('Ymd'))
            ->where('Channel', $newChannel)
            ->update(['RegPeple'=>DB::raw('RegPeple+1'),'ActivePeple'=>DB::raw('ActivePeple+1')]);


    }
    public static function checkClick($UserID)
    {

//        if(AccountsInfo::where('UserID', $UserID)->value('SpreaderID')!=0){
//            return;
//        }
        $SpreaderID=AgentUserRecord::where('UserID', $UserID)->value('SpreaderID');
        $UserSpreaderID=AccountsInfo::where('UserID', $UserID)->value('SpreaderID');
        if(intval($UserSpreaderID)){
            return;
        }
        if(intval($SpreaderID)){
            if($UserID!=$SpreaderID){
                $orgChannel=AccountsInfo::find($UserID)->Channel;
                $newChannel=AccountsInfo::find($SpreaderID)->Channel;
                $BlockInviteChannel=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$newChannel)->value('BlockInviteChannel');
                if($BlockInviteChannel==1){
                    AccountsInfo::where('UserID', $UserID)->update(['SpreaderID' => $SpreaderID]);
                }else {
                    AccountsInfo::where('UserID', $UserID)->update(['SpreaderID' => $SpreaderID, 'Channel' => $newChannel]);
                    self::changePlatformData($orgChannel, $newChannel);
                }
            }
            return;
        }

        $ip=IpLocation::getIP();
        $agent=$_SERVER['HTTP_USER_AGENT'];

        $clicks = AgentClickLog::where('client_ip', $ip)->where('is_valid', 1)->orderByDesc('id')->get();
        if($clicks) {
            $validClick = null;
            foreach ($clicks as $click) {
                if ($click->user_agent == $agent) {
                    $validClick = $click;
                    break;
                }
            }
            if (!$validClick) {
                foreach ($clicks as $click) {
                    $validClick =$click;
                    break;
                }
            }
            if($validClick) {

                $agentInfo=(new AgentController())->processReferral($UserID,$validClick->code);
                if($agentInfo) {
                    //不能是自己
                    if($agentInfo->UserID==$UserID)return;
                    $click->is_valid = 2;
                    $click->save();


                    $orgChannel=AccountsInfo::find($UserID)->Channel;
                    $newChannel=AccountsInfo::find($agentInfo->UserID)->Channel;

                    $BlockInviteChannel=DB::table('QPPlatformDB.dbo.ChannelPackageName')->where('Channel',$newChannel)->value('BlockInviteChannel');

                    if($BlockInviteChannel==1){
                        AccountsInfo::where('UserID', $UserID)->update(['SpreaderID' => $agentInfo->UserID]);
                    }else {
                        AccountsInfo::where('UserID', $UserID)->update(['SpreaderID'=>$agentInfo->UserID,'Channel'=>$newChannel]);
                        self::changePlatformData($orgChannel,$newChannel);
                    }




                }
            }
        }
    }

    /**
     * 获取点击统计数据（可添加权限控制）
     */
    public function getClickStats(Request $request)
    {
        $userId = $request->UserID;

        // 获取用户的邀请码
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
        if (!$agentInfo) {
            return apiReturnFail('Agent information not found');
        }

        $code = $agentInfo->referral_code;

        // 统计总点击数
        $totalClicks = AgentClickLog::where('code', $code)->count();

        // 按设备类型统计
        $deviceStats = AgentClickLog::where('code', $code)
            ->selectRaw('device_type, COUNT(*) as count')
            ->groupBy('device_type')
            ->get()
            ->pluck('count', 'device_type')
            ->toArray();

        // 按国家统计
        $countryStats = AgentClickLog::where('code', $code)
            ->whereNotNull('country')
            ->selectRaw('country, COUNT(*) as count')
            ->groupBy('country')
            ->orderByDesc('count')
            ->limit(10)
            ->get()
            ->toArray();

        // 按日期统计
        $dailyStats = AgentClickLog::where('code', $code)
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderByDesc('date')
            ->limit(15)
            ->get()
            ->toArray();

        return apiReturnSuc([
            'total_clicks' => $totalClicks,
            'device_stats' => $deviceStats,
            'country_stats' => $countryStats,
            'daily_stats' => $dailyStats
        ]);
    }
}
