<?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));
    }
    /**
     * 用户归属渠道变更时，同步分渠道日统计（RecordPlatformData），并尽力同步 LogOnLineCountSum（若表含 Channel 列）。
     *
     * @param  int|string      $orgChannel  原渠道
     * @param  int|string      $newChannel  新渠道
     * @param  string|null     $dateId      统计日期 Ymd（应用注册日）；null 则当前服务器日，兼容旧调用
     */
    static function changePlatformData($orgChannel, $newChannel, $dateId = null)
    {
        $org = (int) $orgChannel;
        $nw = (int) $newChannel;
        if ($org === $nw) {
            return false;
        }

        $dateId = $dateId ?: date('Ymd');

        DB::connection('write')->table(TableName::QPRecordDB() . 'RecordPlatformData')
            ->where('DateID', $dateId)
            ->where('Channel', $org)
            ->update(['RegPeple' => DB::raw('RegPeple-1')]);

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

        //self::syncLogOnLineCountSumRegisterByChannel($org, $nw, $dateId);
        return true;
    }

    /**
     * 若 QPRecordDB.dbo.LogOnLineCountSum 存在 Channel、RegisterCount 且按日聚合，则在渠道迁移时调整分渠道新增注册数。
     * 若库表无 Channel 列或结构与假设不符，静默跳过（记录 debug 日志）。
     */
    private static function syncLogOnLineCountSumRegisterByChannel(int $orgChannel, int $newChannel, string $dateId): void
    {
        if (!preg_match('/^\d{8}$/', $dateId)) {
            return;
        }
        $dateStr = substr($dateId, 0, 4) . '-' . substr($dateId, 4, 2) . '-' . substr($dateId, 6, 2);
        try {
            $tbl = TableName::QPRecordDB() . 'LogOnLineCountSum';
            DB::connection('write')->update(
                'UPDATE ' . $tbl . ' SET RegisterCount = CASE WHEN RegisterCount > 0 THEN RegisterCount - 1 ELSE 0 END '
                . 'WHERE CAST(InsertDateTime AS DATE) = CAST(? AS DATE) AND Channel = ?',
                [$dateStr, $orgChannel]
            );
            DB::connection('write')->update(
                'UPDATE ' . $tbl . ' SET RegisterCount = RegisterCount + 1 '
                . 'WHERE CAST(InsertDateTime AS DATE) = CAST(? AS DATE) AND Channel = ?',
                [$dateStr, $newChannel]
            );
        } catch (\Throwable $e) {
            Log::debug('LogOnLineCountSum RegisterCount sync skipped (schema mismatch or no Channel)', [
                'message' => $e->getMessage(),
                'org' => $orgChannel,
                'new' => $newChannel,
                'dateId' => $dateId,
            ]);
        }
    }
    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){
                $userAcc = AccountsInfo::find($UserID);
                if (!$userAcc) {
                    return;
                }
                $orgChannel = $userAcc->Channel;
                $newChannel = AccountsInfo::find($SpreaderID)->Channel;
                $registerDateId = $userAcc->RegisterDate ? date('Ymd', strtotime($userAcc->RegisterDate)) : date('Ymd');
                $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, $registerDateId);
                }
            }
            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();


                    $userAcc = AccountsInfo::find($UserID);
                    if (!$userAcc) {
                        return;
                    }
                    $orgChannel = $userAcc->Channel;
                    $newChannel = AccountsInfo::find($agentInfo->UserID)->Channel;
                    $registerDateId = $userAcc->RegisterDate ? date('Ymd', strtotime($userAcc->RegisterDate)) : date('Ymd');

                    $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, $registerDateId);
                    }




                }
            }
        }
    }

    /**
     * 获取点击统计数据（可添加权限控制）
     */
    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
        ]);
    }
}
