<?php
if(!defined('ABSPATH'))exit;
class baiduseo_cron_zhizhu{

    public function init(){
        if (!wp_next_scheduled('baiduseo_five_minute_task_hook')) {
            wp_schedule_event(current_time('timestamp',1), 'baiduseo_every_five_minute', 'baiduseo_five_minute_task_hook');
        }
        add_action('baiduseo_five_minute_task_hook', [$this,'baiduseo_my_minute_task']);
    }

    public function baiduseo_my_minute_task() {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        WP_Filesystem();
        global $wp_filesystem, $wpdb;

        $old_transient_data = $this->baiduseo_read_old_transient();
        
        $old_log_content = $this->baiduseo_read_old_log($wp_filesystem);
        $this->baiduseo_clear_old_data($wp_filesystem);

        $this->baiduseo_process_old_data($old_transient_data, $old_log_content, $wpdb);
        $baiduseo_wyc = get_option('baiduseo_liuliang');
        
        if(isset($baiduseo_wyc['diyu']) && $baiduseo_wyc['diyu']){
            $this->baiduseo_diyu();
        }
        $this->baiduseo_long();
        $this->baiduseo_clear();
        $this->baiduseo_tongbu2();
       
    }
    public function baiduseo_tongbu2(){
        global $wpdb;
        $data =  baiduseo_common::baiduseo_url(0);
        $url = "https://api.seoceo.cn/api/tongbu/kp_log?url={$data}";
        $defaults = array(
            'timeout' => 4000,
            'connecttimeout'=>4000,
            'redirection' => 3,
            'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
            'sslverify' => FALSE,
        );
        $result = wp_remote_get($url,$defaults);
        if(!is_wp_error($result)){
            $content = wp_remote_retrieve_body($result);
            $content = json_decode($content,true);
            if(isset($content['data'])){
                $content = $content['data'];
                
                foreach($content as $key=>$val){
                    $res = $wpdb->get_results($wpdb->prepare(' select * from  '.$wpdb->prefix.'baiduseo_kp_log where orderno=%s ',sanitize_text_field($val['orderno'])),ARRAY_A);
                    if(!empty($res)){
                         $wpdb->update($wpdb->prefix . 'baiduseo_kp_log',['num'=>sanitize_text_field($val['num']),'time'=>sanitize_text_field($val['time']),'remark'=>sanitize_text_field($val['remark']),'type'=>(int)$val['type']],['id'=>$val['id']]);
                    }else{
                         $wpdb->insert($wpdb->prefix."baiduseo_kp_log",['num'=>sanitize_text_field($val['num']),'time'=>sanitize_text_field($val['time']),'remark'=>sanitize_text_field($val['remark']),'orderno'=>sanitize_text_field($val['orderno']),'type'=>(int)$val['type']]);
                    }
                }
            }
            
        }
    }

    public function baiduseo_long(){
        global $wpdb;
        $post = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix ."baiduseo_long  where link is null ",ARRAY_A);
       
        if(!empty($post)){
            $data =  baiduseo_common::baiduseo_url(0);
            $url = "https://api.seoceo.cn/api/tongbu/long?url={$data}";
            $defaults = array(
                'timeout' => 4000,
                'connecttimeout'=>4000,
                'redirection' => 3,
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
                'sslverify' => FALSE,
            );
            $result = wp_remote_get($url,$defaults);
            if(!is_wp_error($result)){
                $content = wp_remote_retrieve_body($result);
                $content = json_decode($content,true);
                
                if(isset($content['data'])){
                    $content = $content['data'];
                    $current_timestamp = current_time('timestamp');

                       
                        $seven_days_later_timestamp = $current_timestamp + 7 * 24 * 60 * 60;
                        
                        
                        $seven_days_later = gmdate('Y-m-d H:i:s', $seven_days_later_timestamp);
                    foreach($content as $key=>$val){
                        $res = $wpdb->get_results($wpdb->prepare(' select * from  '.$wpdb->prefix.'baiduseo_long where keywords=%s and link is null ',sanitize_text_field($val['keywords'])),ARRAY_A);
                        
                        if(!empty($res)){
                             $wpdb->update($wpdb->prefix . 'baiduseo_long',['link'=>sanitize_text_field($val['link']),'guo'=>$seven_days_later,'size'=>(int)$val['size']],['id'=>$res[0]['id']]);
                        }
                    }
                }
               
                
            }
        }
    }
    public function baiduseo_clear(){
        $baiduseo_clear = get_option('baiduseo_clear');
        if(!$baiduseo_clear || (isset($baiduseo_clear['time']) && $baiduseo_clear['time']<time()) ){
            
            $data =  baiduseo_common::baiduseo_url(0);
            
            
        	$url = "https://api.seoceo.cn/api/baiduseo/index1?url={$data}&type=1";
            
        	$defaults = array(
                'timeout' => 4000,
                'connecttimeout'=>4000,
                'redirection' => 3,
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
                'sslverify' => FALSE,
            );
            $result = wp_remote_get($url,$defaults);
            if(!is_wp_error($result)){
                $result = wp_remote_retrieve_body($result);
                 $baiduseo_wzt_log = get_option('baiduseo_wzt_log');
                if($baiduseo_wzt_log!=$result){
                    delete_option('baiduseo_wzt_token3');
                    delete_option('baiduseo_wzt_token2');
                    delete_option('baiduseo_wzt_token1');
                }
            }
            if($baiduseo_clear!==false){
                update_option('baiduseo_clear',['time'=>time()+3*3600*24]);
            }else{
                add_option('baiduseo_clear',['time'=>time()+3*3600*24]);
            }
        }
    }
    public function baiduseo_diyu(){
       
        global $wpdb;
        $jifen = baiduseo_kp::get_jifen();
       
              
        if(!$jifen){
            $baiduseo_liuliang_diyu_jifen = get_option('baiduseo_liuliang_diyu_jifen');
            if($baiduseo_liuliang_diyu_jifen>=2){
                 $baiduseo_wyc = get_option('baiduseo_liuliang');
                 $baiduseo_wyc['diyu'] = 0;
                 update_option('baiduseo_liuliang',$baiduseo_wyc);
                 update_option('baiduseo_liuliang_diyu_jifen',0);
            }    
            if($baiduseo_liuliang_diyu_jifen!==false){
               update_option('baiduseo_liuliang_diyu_jifen',$baiduseo_liuliang_diyu_jifen+1);
            }else{
               add_option('baiduseo_liuliang_diyu_jifen',1);
            }
            
            return;
        }
     
        
        // 1. 获取需要处理的IP（省份为空、IP有效、去重，限制100条）
        $to_process_ips = $wpdb->get_results(
            
                "SELECT DISTINCT ip 
                 FROM ".$wpdb->prefix . "baiduseo_liuliang
                 WHERE sheng IS NULL 
                   AND ip != '' 
                   AND ip != 'unknown' 
                 LIMIT 5"
            ,
            ARRAY_A
        );
        $ips = [];
        // 2. 遍历处理每个待处理IP
        foreach ($to_process_ips as $row) {
            $ip = $row['ip'];
            
            // 验证是否为有效的IP地址
            if (!filter_var($ip, FILTER_VALIDATE_IP)) {
                // 非IP标记为异常
                $wpdb->update(
                    $wpdb->prefix . "baiduseo_liuliang",
                    ['sheng' => '异常ip地址'],
                    ['ip' => $ip]
                );
                continue;
            }
            
            // 3. 按需查询：该IP是否已有有效的省份信息（避免加载全量数据）
            $existing_sheng = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT sheng 
                     FROM ".$wpdb->prefix . "baiduseo_liuliang
                     WHERE ip = %s 
                       AND sheng IS NOT NULL 
                       AND sheng != '异常ip地址' 
                     LIMIT 1", // 只取一条有效记录即可
                    $ip
                )
            );
            
            // 4. 如果存在已有省份，同步更新所有相同IP的记录
            if ($existing_sheng !== null) {
                $wpdb->update(
                    $wpdb->prefix . "baiduseo_liuliang",
                    ['sheng' => $existing_sheng],
                    ['ip' => $ip] // 更新该IP的所有记录
                );
            } else {
                $ips[] = $ip;
            }
        }
        
        if(!empty($ips)){
            $ur=  baiduseo_common::baiduseo_url(0);
    	    $url = 'https://api.seoceo.cn/api/tag/getaddress1?url='.$ur;
            $defaults = array(
                'timeout' => 4000,
                'redirection' => 4000,
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
                'sslverify' => FALSE,
            );
    	    $result = wp_remote_post($url,['body'=>['data'=>json_encode($ips)]]);
    	    if(!is_wp_error($result)){
    	        $result = wp_remote_retrieve_body($result);
    	        
    	        
    	        $result = json_decode($result,true);
    	       
            
    	        if(isset($result['data'])){
    	            $result = $result['data'];
    	            $baiduseo_liuliang_diyu = get_option('baiduseo_liuliang_diyu');
                    if($baiduseo_liuliang_diyu!==false){
                       update_option('baiduseo_liuliang_diyu',$baiduseo_liuliang_diyu+count($result));
                    }else{
                       add_option('baiduseo_liuliang_diyu',count($result));
                    }
        	        foreach($result as $key=>$val){
        	            if($val){
        	                $wpdb->update($wpdb->prefix . 'baiduseo_liuliang',['sheng'=>$val],['ip'=>$key]);
        	            }
        	           
        	        }
    	        }
    	    }
        	    
        }
    }

    /**
     * 读取transient中的旧数据
     */
    private function baiduseo_read_old_transient() {
        $transient_data = get_transient('baiduseo_zhizhu_cache');
        // 返回原始数据（空则返回空数组）
        return $transient_data ?$transient_data: [];
    }

    /**
     * 读取日志文件中的旧内容
     */
    private function baiduseo_read_old_log($wp_filesystem) {
        $log_path = $this->get_log_path();
        if ($wp_filesystem->exists($log_path)) {
            return $wp_filesystem->get_contents($log_path);
        }
        return ''; // 日志不存在则返回空
    }

    /**
     * 清理旧数据（transient和日志），为新数据腾出空间
     */
    private function baiduseo_clear_old_data($wp_filesystem) {
        // 清理transient（旧数据已读取，新数据会重新set）
        delete_transient('baiduseo_zhizhu_cache');

        // 清理日志文件（旧内容已读取，清空后新日志从头写入）
        $log_path = $this->get_log_path();
        if ($wp_filesystem->exists($log_path)) {
            $wp_filesystem->put_contents($log_path, '', FS_CHMOD_FILE); // 写入空内容清空
        }
    }

    /**
     * 处理已读取的旧数据（解析并写入数据库）
     */
    private function baiduseo_process_old_data($transient_data, $log_content, $wpdb) {
        // 解析transient数据为标准数组
        $parsed_transient = $this->parse_transient($transient_data);
        // 解析日志内容为标准数组
        $parsed_log = $this->parse_log($log_content);
        // 合并所有待处理数据
        $all_old_data = array_merge($parsed_transient, $parsed_log);

        // 写入数据库（遵循jieduan1逻辑）
        $this->save_to_database($all_old_data, $wpdb);
    }

    /**
     * 解析transient数据（确保格式统一）
     */
    private function parse_transient($data) {
        if (empty($data)) {
            return [];
        }
        // 支持单条数据或数组，统一转为数组
        return is_array($data) ? $data : [$data];
    }

    /**
     * 解析日志内容（按日志格式提取字段）
     */
    private function parse_log($content) {
        if (empty($content)) {
            return [];
        }

        $log_lines = explode("\n", trim($content));
        $parsed = [];
        // 匹配日志格式：[time] [name] [ip] [type] [address]
        $pattern = '/^\[(.*?)\] \[(.*?)\] \[(.*?)\] \[(.*?)\] \[(.*?)\]$/';

        foreach ($log_lines as $line) {
            if (empty($line) || !preg_match($pattern, $line, $matches)) {
                continue; // 跳过空行或格式错误的行
            }

            $parsed[] = [
                'time'    => $matches[1],
                'name'    => $matches[2],
                'ip'      => $matches[3],
                'type'    => $matches[4],
                'address' => $matches[5]
            ];
        }

        return $parsed;
    }

    /**
     * 按jieduan1逻辑写入数据库
     */
    private function save_to_database($data_list, $wpdb) {
        if (empty($data_list)) {
            return; // 无数据则跳过
        }

        
        $current_time = current_time('Y/m/d H:i:s');

        foreach ($data_list as $data) {
            // 补全必要字段（默认值处理）
            $data = wp_parse_args($data, [
                'address' => '',
                'name'    => '',
                'ip'      => '',
                'type'    => '',
                'time'    => $current_time
            ]);

            // 地址长度检查（同jieduan1：跳过空地址或过长地址）
            if (empty($data['address']) || strlen($data['address']) >= 1024) {
                continue;
            }

            // 查询重复记录（按address和name判断）
            $existing = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM ".$wpdb->prefix . "baiduseo_zhizhu WHERE address = %s AND name = %s",
                    $data['address'],
                    $data['name']
                ),
                ARRAY_A
            );

            // 404特殊处理（同jieduan1：跳过404且URI为空/根目录的记录）
            $is_404 = ($data['type'] == '404');
            $request_uri = wp_parse_url($data['address'], PHP_URL_PATH) ?? '';
            if ($is_404 && ($request_uri == '/' || $request_uri == '')) {
                continue;
            }

            // 存在重复记录则更新（num+1，更新时间和状态）
            if (!empty($existing[0])) {
                $wpdb->update(
                    $wpdb->prefix . 'baiduseo_zhizhu',
                    [
                        'time' => $current_time,
                        'num'  => $existing[0]['num'] + 1,
                        'ip'   => $data['ip'],
                        'type' => $data['type']
                    ],
                    ['id' => $existing[0]['id']]
                );
            }
            // 不存在则插入新记录（num=1）
            else {
                $wpdb->insert(
                    $wpdb->prefix . 'baiduseo_zhizhu',
                    [
                        'address' => $data['address'],
                        'name'    => $data['name'],
                        'ip'      => $data['ip'],
                        'time'    => $current_time,
                        'type'    => $data['type'],
                        'num'     => 1
                    ]
                );
            }
        }
    }

    /**
     * 获取日志文件路径
     */
    private function get_log_path() {
        $plugin_dir = plugin_dir_path(__FILE__);
        $txt_dir = trailingslashit($plugin_dir . 'txt');
        return $txt_dir . 'baiduseo_zhizhu_log.txt';
    }


}