<?php
if (!class_exists('PPO_Down')) {
    class PPO_Down {

        public function __construct(){
        
            add_action('wp_ajax_dd_pay_modal', array($this, 'dd_pay_modal'));
            add_action('wp_ajax_ppo_down_modal', array($this, 'ppo_down_modal'));
            add_action('wp_ajax_ppo_pwd_modal', array($this, 'ppo_pwd_modal'));
            add_action('wp_ajax_ppo_pwd_check', array($this, 'ppo_pwd_check'));   
        }

        // 支付货币图标
        public static function pay_icon($type){
            $arr = array();
            switch ($type) {
                case 'cash':
                    $icon = get_op('cash_icon','¥');
                    $name = get_op('cash_name','余额');
                    $arr = array(
                        'icon' => $icon,
                        'name' => $name,
                    );
                    break;
                
                case 'credit':
                    $icon = get_op('credit_icon','◎');
                    $name = get_op('credit_name','积分');
                    $arr = array(
                        'icon' => $icon,
                        'name' => $name,
                    );
                    break;
            }

            $pattern = '/^https?:\/\/.*\.(jpg|jpeg|png|gif|webp)$/i';
            if (preg_match($pattern, $arr['icon'])) {
                $arr['icon'] = '<img src="'.$arr['icon'].'" class="ppo-pay-icon">';
            }

            return $arr;
        }

        public static function dd_pay_type($pid){
            $meta = get_post_meta($pid,'_ppo_post_options',true);
            if(!empty($meta)){
                $data = $meta['dd_box_data'];
                $pay_type = $data['pay_type'];
                return $pay_type;
            }
        }

        //获取付费文章参数
        public static function dd_data(){
            global $post; 
            $pid = $post->ID;
            $data = get_post_meta($pid,'_ppo_post_options',true);
            return $data;
        }

        // 付费下载模块
        public static function dd_box(){
            global $post; 
            $pid = $post->ID;
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $html = '';
            $meta = self::dd_data();
            if(!empty($meta)){
            $data = $meta['dd_box_data'];
            $data['pid'] = $pid;
            $d_type = $meta['dd_type'];
            //$thum = THEME_URL.'/img/banner.jpg';

            $title = !empty($data['title']) ? $data['title'] : get_the_title($pid);
            $des = $data['des'];
            $hide_content = $data['title'];
            $pay_type = $data['pay_type'];
            $dd_pay_limits = '';
            //$sell_num = !empty($data['sell_num']) ? $data['sell_num'] : '';

            if($d_type != 'close'){
                
                if(is_array($data) && !empty($data)){ // 是否有付费数据

                    switch ($d_type) {
                        case 'read':
                            $type_text = '付费阅读';
                            break;
                        
                        case 'down':
                            $type_text = '付费下载';
                            break;

                        case 'video':
                            $type_text = '付费视频';
                            break;    

                        case 'gallary':
                            $type_text = '付费图集';
                            break;    
                    }

                    // if($d_type == 'read'){

                    // } else if($d_type == 'down'){

                    // }

                    if($pay_type == 'cash' || $pay_type == 'credit'){
                        $dd_pay_limits = self::dd_pay_limits(!empty($data['lv_allow']) ? $data['lv_allow'] : '');
                    }
                    
                    $pre_gallary = '';
                    if(!empty($data['gallery'])){
                        $pre_gallary = '<div class="left dd_thum">'.self::pre_gallary($data['gallery']).'</div>';
                        $notice_class = '';
                        $btn_class = '';
                    } else {
                        $notice_class = ' right';
                        $btn_class = ' right';
                    }
                    
                    $bought = self::check_user_bought($data);
                    $hide_info = $bought && !empty($data['hide_html']) ? '<div class="hide-info-box">'.$data['hide_html'].'</div>' : '';

                    $html = '<div class="download-box">
                             <div class="type-notice'.$notice_class.'">'.$type_text.'</div>
                                <div class="dd-box-inner">
                                    '.$pre_gallary.'
        
                                    <div class="dd_content">
                                        <div class="dd-title">'.$title.'</div>
                                        <div class="dd-des">'.$des.'</div>
                                        '.self::get_down_price($data,$user_id).'
                                        <div class="dd-vip-free-down">'.self::vip_user_downnum_box($user_id,$data).'</div>
                                        <div class="dd-limits"></div>
                                        <div class="dd-buy-btn'.$btn_class.'">'.self::dd_pay_btn($data,$user_id).'</div>
                                        <div class="bottom-tips">'.self::bottom_tips($pay_type).''.$dd_pay_limits.'</div>
                                        
                                    </div>
                                </div>
                                '.$hide_info.'
                                '.self::info($data['info']).'
                            </div>';
        
                    if($d_type == 'down'){
                        return $html;
                    }
                   
                }
            }
        }
            
        }

        // 预览图
        public static function pre_gallary($data){
            $html = '';
            $gals = explode( ',', $data );
            if(is_array($gals) && !empty($gals) && !empty($data)){
                foreach($gals as $i => $v){
                    $img = wp_get_attachment_image_src( $v, 'full' );
                    $thum = wp_get_attachment_image_src( $v, 'medium' );
                    $picked = $i == 0 ? 'picked' : 'n';
                    $html .= '<a class="dd-box-gals '.$picked.'"><img src="'.@$img[0].'"></a>';
                }

                $feature_img = wp_get_attachment_image_src( $gals[0], 'full' );
                $feature = '<a href="'.@$feature_img[0].'" class="dd-box-fea fancy-box" data-fancybox="dd-feature"><img src="'.@$feature_img[0].'"></a>';

                $output = '<div class="dd-thum-inner">
                                <div class="feature">'.$feature.'</div>
                                <div class="bt-thum">'.$html.'</div>
                            </div>';

                return $output;
            }

        }

        // 获取资源价格
        public static function get_down_price($data,$user_id){
            $type = $data['pay_type'];
            $vip_notice = '';
            $vip = PPO_Vip::check_vip_lv();
            $bought = self::check_user_bought($data);
            $down_num = self::get_user_down_num($user_id);
            $text = self::dd_rd();
            $vip_discount = isset($data['vip_discount']) ? $data['vip_discount'] : array();
            if($type == 'cash'){
                $cash_price = $data['cash_price']; // 原价
                $n_cash = $data['n_cash']; // 执行价
                $show_price = !empty($n_cash) ? $n_cash : $cash_price;
                $show_price = !empty($show_price) ? $show_price : 0;

                $price_arr = array(
                    's_price' => $cash_price,
                    'n_price' => $n_cash,
                    'vip_discount' => $vip_discount,
                );
                $vip_p = self::get_vip_price($price_arr,$vip);
                if($vip_p !== '999999' && $vip){
                    $price = '<div class="n-price line">'.self::get_price_value($show_price , $type).'</div>
                                <div class="s-price '.$vip_p.'">'.self::get_price_value($vip_p , $type).'<small>会员折扣</small></div>';
                } else {
                    if(!empty($n_cash)){
                        $price = '<div class="n-price line">'.self::get_price_value($cash_price , $type).'</div>
                                <div class="s-price">'.self::get_price_value($n_cash , $type).'<small class="red">限时优惠</small></div>';
                    } else {
                        $price = '<div class="s-price">'.self::get_price_value($show_price , $type).'</div>';
                    }
                }

                if(!$bought && !$vip){
                    $vip_notice = self::vip_notice($price_arr, $type);
                }

            } else if($type == 'credit') {
                $credit_price = $data['credit_price'];
                $show_price = !empty($credit_price) ? $credit_price : 0;
                $price_arr = array(
                    's_price' => $credit_price,
                    'n_price' => '',
                    'vip_discount' => $vip_discount,
                );
                $vip_p = self::get_vip_price($price_arr,$vip);
                if($vip_p !== '999999' && $vip){
                    $price = '<div class="n-price line">'.self::get_price_value($show_price , $type).'</div>
                                <div class="s-price">'.self::get_price_value($vip_p , $type).'<small>会员折扣</small></div>';
                } else {
                    $price = '<div class="s-price">'.self::get_price_value($show_price , $type).'</div>';
                    }
            

                if(!$bought && !$vip){
                    $vip_notice = self::vip_notice($price_arr, $type);
                }
            } else if($type == 'login'){
                $price = '<div class="login-down"><i class="ri-information-line"></i>此资源需要登录后，方可'.$text.'</div>';
            } else if($type == 'cmt'){
                $price = '<div class="cmt-down"><i class="ri-chat-3-line"></i>此资源需评论后，方可'.$text.'</div>';
            } else if($type == 'limits'){
                $price = '<div class="limits-down"><div class="t"><i class="ri-user-follow-line"></i>以下用户等级，可'.$text.'</div> '.self::dd_limits_list(@$data['limits_check']).'</div>';
            } else if($type == 'pwd'){
                $price = '<div class="pwd-down"><i class="ri-lock-password-line"></i>此资源需输入密码，方可'.$text.'</div>';
            } else {
                $price = '<div class="pass-down"><i class="ri-lock-unlock-line"></i>免费资源</div>';
            }

            if($bought){
                $price = '<div class="pass-down"><i class="ri-lock-unlock-line"></i>资源已解锁<span>，请'.$text.'</span><div class="unlock-icon"><img src="'.THEME_URL.'/img/icon/unlock.png"></div></div>';
            }

            $html = '<div class="dd-price">';
            $html .= '<div class="dd-price-inner">'.$price .'</div>';
            $html .= $vip_notice;
            $html .= '</div>';

            return $html;
        }

        // 获取会员价格
        public static function get_vip_price($data,$vip){
            if(empty($data)) return '999999';

            // 处理新的数组格式 - 包含s_price/n_price说明是完整的价格数组
            if(is_array($data) && (isset($data['s_price']) || isset($data['n_price']))){
                // 获取原价（优先使用执行价n_price，否则使用原价s_price）
                $price = !empty($data['n_price']) ? $data['n_price'] : $data['s_price'];
                if(empty($price)) return '999999';

                // 获取折扣值
                $vip_discount = null;
                if(isset($data['vip_discount']) && is_array($data['vip_discount'])){
                    if(array_key_exists($vip, $data['vip_discount'])){
                        $raw_value = $data['vip_discount'][$vip];
                        if($raw_value !== ''){
                            $vip_discount = floatval($raw_value);
                        }
                    }
                }

                if($vip_discount === null) return '999999'; // 没有设置VIP折扣
                if($vip_discount == 0) return '0'; // 免费
                if($vip_discount >= 1) return '999999'; // 折扣>=1显示原价

                // 计算折扣价：原价 × 折扣
                return floor($price * $vip_discount);
            }

            
            // 处理直接的折扣数组格式 (vip_discount字段)
            if(is_array($data)){
                // 根据用户VIP等级获取折扣值
                if(isset($data[$vip])){
                    $vip_discount = floatval($data[$vip]);
                    if($vip_discount == 0) return 0; // 免费
                    return $vip_discount; // 返回折扣值（如0.8代表8折）
                }
                return '999999'; // 没有该VIP等级的折扣设置
            }

            return '999999';
        }

        // 价格转换
        public static function get_price_value($data,$type){
            $icon = self::pay_icon($type);
            $icon = '<span class="p-icon">'.$icon['icon'].'</span>';

            if($data == 0){
                $html = '<span class="value">免费</span>';
            } else {
                $html = $icon.'<span class="value">'.$data.'</span>';
            }
            
            return $html;
        }

        // 非会员提醒开通
        public static function vip_notice($data,$type){
            //if((empty($data['n_price']) && empty($data['s_price'])) || !isset($data['vip_discount'])) return;
            $html = '';
            $lv = PPO_Vip::get_vip_lv();
            $res = $data['vip_discount'];
            $show_price = !empty($data['n_price']) ? $data['n_price'] : $data['s_price'];
            $show_price = !empty($show_price) ? $show_price : 0;
            
            foreach($res as $i => $v){
                //print_r($i);
                if($v !== ''){
                    $price = $show_price * $v;
                    $html .= '<li class="item"><span class="vip-lv">'.$lv[$i].'</span><span class="v-price">'.self::get_price_value($price,$type).'</span></li>';
                }
            }

            return '<div class="vip-notice">
                        <div class="tips">开通会员，享受更多优惠！</div>
                        <div class="vip-notice-inner"><div class="list" uk-slider>
                            <div class="uk-slider-container"><ul class="uk-slider-items uk-child-width-1-3">'.$html.'</ul></div>
                            </div>
                        <div class="buy-vip"><a href="#">开通</a></div>
                        </div>
                    </div>';
        }

        // 资源信息
        public static function info($data){
            $arr = explode("\r\n",$data);
            $html = '';
            $res= array_map(function($line) {
                return explode("|", $line);
            }, $arr);

            // 过滤空值
            $res = array_filter($res, function($v) {
                return !empty($v[0]);
            });
            
            foreach($res as $v){
                $html .= '<li class="info-item"><span>'.$v[0].' :</span>'.$v[1].'</li>';
            }

            if(!empty($data)){
                return '<div class="dd-info"><h4>资源属性</h4><div class="dd-info-inner">'.$html.'</div></div>';
            }
        }

        // 底部提示
        public static function bottom_tips($type){
            switch ($type) {
                case 'cash':
                    $tips = '此资源为付费资源';
                    break;
                
                case 'credit':
                    $tips = '此资源为积分资源';
                    break;   

                case 'login':
                    $tips = '此资源需登录查看';
                    break;   
                    
                case 'limits':
                    $tips = '此资源有等级限制，请升级后再下载(查看)';
                    break; 

                case 'cmt':
                    $tips = '此资源需评论后查看，评论后刷新页面下载(查看)';
                    break;     
                
                case 'pwd':
                    $tips = '此资源需密码查看';
                    break;     

                default:
                    $tips = '';
                    break;
            }

            return '<span>'.$tips.'</span>';
        }

        // 允许购买的用户组
        public static function dd_pay_limits($data){
            $html = '';
            if(is_array($data) && !empty($data)){
                $arr = all_lv_merge();
                foreach($data as $v){
                    $html .= '<li>'.$arr[$v].'</li>';
                }

                return '<div class="lv-allow"><a class="lv-allow-hover">以下用户可购买<i class="ri-arrow-right-s-line"></i></a>
                        <div class="allow-drop-pannel" uk-drop="mode: click;target:.bottom-tips;shift:true;animation: uk-animation-slide-top-small; animate-out: true"><ul>'.$html.'</ul></div>
                        </div>';
            }
        }

        // 等级限制模式 允许用户组列表
        public static function dd_limits_list($data){
            $html = '';
            if(is_array($data) && !empty($data)){
                $arr = all_lv_merge();
                foreach($data as $v){
                    $html .= '<li>'.$arr[$v].'</li>';
                }

                return '<div class="allow-limits-pannel"><ul>'.$html.'</ul></div>';
            }
        }

        // 下载或查看文字
        public static function dd_rd(){
            $meta = self::dd_data();
            if(!empty($meta)){
                $d_type = $meta['dd_type'];
                if($d_type == 'read'){
                    return '查看';
                } else if($d_type == 'down') {
                    return '下载';
                } else {
                    return '';
                }
            }
        }

        // 支付按钮状态
        public static function dd_pay_btn($data,$user_id){
            $html = '';
            $limits = !empty($data['lv_allow']) ? $data['lv_allow'] : '';
            $pay_type = $data['pay_type'];
            $login = is_user_logged_in();
            $bought = self::check_user_bought($data);
            $down_num = self::get_user_down_num($user_id);
            $allow_buy = self::check_user_limits($limits);
            $allow_check = self::check_user_limits(@$data['limits_check']);
            $text = self::dd_rd();
            $down_type = get_op('down_page_type','modal');
                
                switch ($pay_type) {
                    case 'cash':
                    case 'credit':    
                    if($allow_buy){
                        $html = '<a class="dd-buy-now"><i class="ri-shopping-bag-3-line"></i>立即购买</a>';
                    } else {
                        $html = '<a class="dd-buy-nolimits"><i class="ri-user-unfollow-line"></i>权限不足</a>';
                    }
                        break;
                    case 'login': 
                        $html = '<a class="dd-buy-pass '.$down_type.'"><i class="ri-download-line"></i>前往'.$text.'</a>';
                        break;

                    case 'cmt': 
                        $html = '<a href="#comments" class="dd-buy-cmt" uk-scroll><i class="ri-message-3-line"></i>评论后'.$text.'</a>';
                        break;    

                    case 'limits': 
                        $html = '<a href="'.home_url().'/vip" target="_blank" class="dd-up-vip"><i class="ri-vip-crown-2-line"></i>立即升级</a>';
                        break;     

                    case 'pwd': 
                        $html = '<a class="dd-buy-pwd"><i class="ri-lock-line"></i>密码'.$text.'</a>';
                        break;  
                        
                    case 'open': 
                        return '<a class="dd-buy-pass '.$down_type.'"><i class="ri-download-line"></i>前往'.$text.'</a>';
                        break;     

                }

                if(!$login){
                    return '<a class="dd-buy-login need-login"><i class="ri-user-follow-line"></i>登录后'.$text.'</a>';
                } else {
                    if($bought){
                        return '<a class="dd-buy-pass '.$down_type.'"><i class="ri-download-line"></i>前往'.$text.'</a>';
                    }

                    return $html;
                }

            
        }

        // 获取用户剩余下载次数
        public static function get_user_down_num($user_id){
            $count = get_user_meta($user_id,'user_down_num',true);
            if(empty($count)){ //如果没有剩余次数，则更新
                $arr = get_user_down_num_arr($user_id);
                $count = update_user_meta($user_id,'user_down_num',$arr);
                return $arr;
            }

            return $count;
        }

        // VIP用户下载次数提示
        public static function vip_user_downnum_box($user_id,$ob){
            $data = self::get_user_down_num($user_id);
            $_data = get_user_down_num_arr($user_id);
            $bought = self::check_user_bought($ob);
            $text = '';
            $vip = get_user_meta( $user_id, 'ppo_vip', true );
            
            if($bought){
                $text = '您每天可下载付费资源为<span>'.$_data['down_num'].'</span>次,今日剩余<span>'.$data['down_num'].'</span>次';

                if($_data['down_num'] >= 9999) {
                    $text = '您每天可下载额度为<span>无限</span>次';
                }
            }
           

            $html = '<div class="vip_downnum_box">
                        <div class="inner">'.$text.'</div>
                    </div>';

            if($text) {
                return $html;
            }
        }


        // 检查用户权限
        public static function check_user_limits($data){
            $vip = PPO_Vip::check_vip_lv();
            if(!empty($data) && in_array($vip,$data)){
                return true;
            }
        }

        // 检查用户是否已购买此资源
        public static function check_user_bought($data){
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $login = is_user_logged_in();
            $pid = $data['pid'];
            $type = $data['pay_type'];

            if($type == 'cash' || $type == 'credit'){
                /* $bought_list = get_post_meta($pid,'bought_user',true);
                $bought = $bought_list ? $bought_list : array();
                if(in_array($user_id,$bought)){
                    return true;
                } */
                $PixOrder = new PixOrder();
                $order = $PixOrder->get_user_post_order($pid,$user_id);
                if(!empty($order) && $order->status == '1'){
                    return true;
                }


            } else if($type == 'cmt') {
                $res = self::user_has_commented($user_id,$pid);
                if($res){
                    return true;
                }
            } else if($type == 'limits'){

                $allow_check = self::check_user_limits(@$data['limits_check']);
                if($allow_check) return true;

            } else if($type == 'login' && $login){

                return true;

            } else if($type == 'pwd') {
                $_pwd = $data['down_pwd'];

                if(isset($_COOKIE['pwd_down_'.$pid])) {
                    $pd_data = unserialize(stripslashes($_COOKIE['pwd_down_'.$pid]));
                    if($pid == $pd_data['post_id'] && $_pwd == $pd_data['code']){
                        return true;
                    } 
                }
                

            } else if($type == 'open'){
                return true;
            } else {
                return false;
            }
        
        }

        // 更新用户文章购买
        public static function update_bought_user($data){
            $post_id = $data['data_id'];
            $user_id = $data['user_id'];
            $bought_user = get_post_meta($post_id,'bought_user',true);
            $bought_user = is_array($bought_user) ? $bought_user : array();
            
            $bought_user[] = $user_id;
            $bought_user = array_values(array_unique(array_map('intval', $bought_user)));
            $update_bought_user = update_post_meta($post_id,'bought_user',$bought_user);
        }

        // 用户是否评论过文章
        public static function user_has_commented($user_id,$pid){
            $WHERE = '';
            if ($user_id > 0) {
                $WHERE = "`user_id`={$user_id}";
            } elseif (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) {
                $email = str_replace('%40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]);
                $WHERE = "`comment_author_email`='{$email}'";
            } else {
                return false;
            }

            global $wpdb;
            $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$pid} and `comment_approved`='1' and $WHERE LIMIT 1";
            return $wpdb->get_var($query);
        }



        // ajax支付弹窗
        public static function dd_pay_modal(){
            $wallet = THEME_URL.'/img/icon/wallet.png';
            $pid = $_POST['pid'];
            $uid = $_POST['uid'];
            $user = get_userdata($uid);
            $user_email = $user ? $user->user_email : '';
            $meta = get_post_meta($pid,'_ppo_post_options',true);
            $credit = get_user_meta($uid,'ppo_credit',true);
            $credit = !empty($credit) ? (int)$credit : 0;
            $credit_info = '';
            $title = !empty($data['title']) ? $data['title'] : get_the_title( $pid );
            if(!empty($meta)){
                $data = $meta['dd_box_data'];
                $pay_type = $data['pay_type'];
                $icon = self::pay_icon($pay_type);
                if($pay_type == 'cash'){
                    $text = '支付金额';
                    $pp = '<div class="price-info cash"><span class="icon">'.$icon['icon'].'</span><span class="price">'.self::dd_pay_data($pid)['total_amount'].'</span></div>';
                } else if($pay_type == 'credit') {
                    $credit_info = '<div class="credit-info"><div class="value">您当前的'.$icon['name'].'为'.$icon['icon'].$credit.'</div><a class="charge">前往充值</a></div>';
                    $text = $icon['name'].'支付';
                    $pp = '<div class="price-info credit"><span class="icon">'.$icon['icon'].'</span><span class="price">'.self::dd_pay_data($pid)['total_amount'].'</span></div>';
                }

                $html = '<div class="dd-pay-modal uk-animation-fade uk-animation-fast">
                            <div class="dd-pay-title">购买结算</div>
                            <div class="pay-info">
                            <div class="top-icon"><img class="icon" src="'.$wallet.'"></div>
                                <div class="pt-title">'.$title.'</div>
                                <div class="need-pay"><div class="need-price">'.$text.'</div>
                                '.$pp.'
                                </div>
                            </div>
                            <div class="pay-email">
                                <i class="ri-mail-line"></i>
                                <input type="email" id="order-email" class="order-email-input" value="'.esc_attr($user_email).'" placeholder="请输入邮箱地址" required>
                            </div>
                            '.$credit_info.'
                            '.PPO_Pay::dd_pay_btn($pay_type,$uid).'
                        </div>';
    
                wp_send_json(array('html'=> $html));
            }

        }

        // 获取文章支付数据
        public static function dd_pay_data($pid){
            $meta = get_post_meta($pid,'_ppo_post_options',true);

            if(empty($meta)){
                return false;
            }

            $data = $meta['dd_box_data'];
            $d_type = $meta['dd_type'];
            $pay_type = $data['pay_type'];
            
            // 获取用户VIP等级
            $vip = PPO_Vip::check_vip_lv();

            if($pay_type == 'cash'){
                $price_arr = array(
                    's_price' => $data['cash_price'],
                    'n_price' => $data['n_cash'],
                    'vip_discount' => $data['vip_discount'],
                );
                $vip_p = self::get_vip_price($price_arr,$vip);
                $cash_price = $data['cash_price'];
                $n_cash = $data['n_cash'];
                $price = !empty($n_cash) ? $n_cash : $cash_price;
                $price = !empty($price) ? $price : 0;
            } else if($pay_type == 'credit') {
                $credit_arr = array(
                    's_price' => $data['credit_price'],
                    'vip_discount' => $data['vip_discount'],
                );
                $vip_p = self::get_vip_price($credit_arr,$vip);
                $price = !empty($data['credit_price']) ? $data['credit_price'] : 0;
            }

            //return $vip_p;

            if($vip_p !== '999999' && $vip){
                $pp = $vip_p;
            } else {
                $pp = $price;
            }

            return array(
                'total_amount' => $pp,
                'subject' => '文章购买:'.$data['title'].'',
            );

        }

        // 下载资源列表
        public static function get_ppo_down_item($pid,$user_id){
            $meta = get_post_meta($pid,'_ppo_post_options',true);
  
            $list = '';
            if(!empty($meta)){
                $down_item = isset($meta['down_item']) ? $meta['down_item'] : array();
                $ob = $meta['dd_box_data'];   
                $ob['pid'] = $pid;     
                $down_num = self::vip_user_downnum_box($user_id,$ob);
                $info = $meta['down_item_html'] ? '<div class="down-item-html">'.$meta['down_item_html'].'</div>' : '';

                $title_adv = get_op('dp_title_adv','');
                $list_adv = get_op('dp_list_adv','');

                if (!empty($down_item) && is_array($down_item)) {
                foreach($down_item as $k => $v){
                    $title = $v['title'];
                    $link = $v['link'];
                    $tqm = $v['tqm'];
                    $jym = $v['jym'];
                    $time = date('Y-m-d');
                    $encode = encrypt_url('id='.$k.'&post_id='.$pid.'&time='.$time,'ppo_down_encode');  
                    $down_link = esc_url(home_url('/download?token='.$encode));


                    $tq = $tqm ? '<a class="code-copy tqm-copy hint--bottom hint--rounded" data-clipboard-target="#tq-'.$k.'" data-clipboard-action="copy" data-hint="点击复制">提取码:<span id="tq-'.$k.'" data-clipboard-text="'.$tqm.'">'.$tqm.'</span></a>' : '';
                    $jy = $jym ? '<a class="code-copy jym-copy hint--bottom hint--rounded" data-clipboard-target="#jy-'.$k.'" data-clipboard-action="copy" data-hint="点击复制">解压码:<span id="jy-'.$k.'" data-clipboard-text="'.$jym.'">'.$jym.'</span></a>' : '';
                    $list .= '<div class="ppo-down-item">
                                <div class="left">
                                    <div class="down-icon"><i class="ri-download-cloud-line"></i></div>
                                    <div class="down-info">
                                        <div class="title">'.$title.'</div>
                                        <div class="down-code">
                                            '.$tq.$jy.'          
                                        </div>
                                    </div>
                                    
                                </div>
                                <div class="right"> 
                                    <a class="ppo-down-link-btn" href="'.$down_link.'">下载</a>
                                </div>
                            </div>';

                       
                }
                } else {
                    $list = '<div class="down-empty"><i class="ri-inbox-line"></i> 未配置下载项</div>';
                }
                return $title_adv.$down_num.'<div class="list-item">'.$list.'</div>'.$list_adv.$info; 
            }
        }

        // 付费下载弹窗
        public static function ppo_down_modal(){
            $pid = $_POST['pid'];
            $title = $_POST['title'];
            $current_user = wp_get_current_user();
            $user_id = $current_user->ID;
            $today = date('Y-m-d');

            $meta = get_post_meta($pid,'_ppo_post_options',true);
            if(empty($meta)) {
                wp_send_json(array('html'=> '<div class="down-error">数据异常</div>'));
                return;
            }

            $data = $meta['dd_box_data'];
            $data['pid'] = $pid;

            $bought = self::check_user_bought($data);
            if(!$bought) {
                wp_send_json(array('html'=> '<div class="down-error"><i class="ri-error-warning-line"></i>您没有下载权限，请先购买</div>'));
                return;
            }

            $down_data = self::get_user_down_num($user_id);
            if($down_data['time'] !== $today){
                $update_arr = get_user_down_num_arr($user_id);
                update_user_meta($user_id,'user_down_num',$update_arr);
            }

            $down_item = self::get_ppo_down_item($pid,$user_id);

            $down_box = '<div class="ppo-down-content">
                            <div class="ppo-downc-title">'. $title.'</div>
                            '.$down_item.'
                        </div>';

            if($down_item && $pid > 0){
                wp_send_json(array('html'=> $down_box  ));
            } else {
                wp_send_json(array('html'=> '<div class="down-error">拉取异常</div>'));
            }

            
        }

        // 密码下载弹窗
        public static function ppo_pwd_modal(){
            $pid = $_POST['pid'];
            
            $meta = get_post_meta($pid,'_ppo_post_options',true);
            if(!empty($meta)){
                $data = $meta['dd_box_data'];
                $qr_code = !empty($data['pwd_qrcode']) ? '<div class="pwd-qrcode"><img src="'.$data['pwd_qrcode'].'"></div>' : '';
                $pwd = $data['down_pwd'];
                $pwd_html = $data['down_pwd_html'];
                $pwd_html = !empty($pwd_html) ? '<div class="pwd-tips">'.$pwd_html.'</div>' : '';

                $html = $qr_code.$pwd_html;

                wp_send_json(array('html' => $html));
            }
            
        }

        // 密码验证
        public static function ppo_pwd_check(){
            $pwd = $_POST['pwd'];
            $pid = $_POST['pid'];

            $meta = get_post_meta($pid,'_ppo_post_options',true);
            if(!empty($meta)){
                $data = $meta['dd_box_data'];
                $_pwd = $data['down_pwd'];
                
                if($pwd == $_pwd) {
                    $expire = time()+60*60*24*7;
                     $arr = array(
                        'post_id' => $pid,
                        'code' => $pwd,
                    );  

                    $arr = serialize($arr);
                    setcookie('pwd_down_'.$pid, $arr, time()+3600*24*30,"/");
                    wp_send_json(array('code' => 1,'msg' => '密码正确，2s后自动刷新'));
                } else {
                    wp_send_json(array('code' => 0,'msg' => '密码错误！'));
                } 
 
            }
            
        }

        //输出下载链接
	public static function go_down($file_dir){
		$file_dir = chop($file_dir);

		// 远程文件下载
		if (substr($file_dir, 0, 7) == 'http://' || substr($file_dir, 0, 8) == 'https://') {
			$remote_url = $file_dir;

			// SSRF 防护：检查是否为内网 IP
			$host = parse_url($remote_url, PHP_URL_HOST);
			if ($host) {
				$ip = gethostbyname($host);
				if (self::is_private_ip($ip)) {
					header('HTTP/1.1 403 Forbidden');
					exit();
				}
			}

			// 安全跳转（使用 meta 跳转避免 XSS）
			echo '<html><head><meta http-equiv="refresh" content="0;url='.esc_url($remote_url).'"></head><body></body></html>';
			exit();
		}

		// 本地缓冲下载文件
		$file_dir = ABSPATH . '/' . $file_dir;
		if (!file_exists($file_dir)) {
			header('HTTP/1.1 404 NOT FOUND');
			return false;
		}
		$pathinfoarr = pathinfo($file_dir);
		$file_name = time().mt_rand(1000,9999).'.'.$pathinfoarr['extension'];
		$file = fopen ( $file_dir,"rb" );
		header('Content-Description: File Transfer');
		Header ( "Content-type: application/octet-stream" );
		Header ( "Accept-Ranges: bytes" );
		Header ( "Content-Length: " . filesize ( $file_dir ) );
		Header ( "Content-Disposition: attachment; filename=" . $file_name );
		echo fread ( $file, filesize ( $file_dir) );
		fclose ( $file );
		exit();
	}

	// 检查是否为私有/内网 IP
	private static function is_private_ip($ip) {
		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
			return true;
		}
		$private_ranges = [
			'127.0.0.0/8',
			'10.0.0.0/8',
			'172.16.0.0/12',
			'192.168.0.0/16',
			'169.254.0.0/16',
			'0.0.0.0/8',
		];
		foreach ($private_ranges as $range) {
			if (self::ip_in_range($ip, $range)) {
				return true;
			}
		}
		return false;
	}

	// 检查 IP 是否在指定 CIDR 范围内
	private static function ip_in_range($ip, $range) {
		if (strpos($range, '/') === false) {
			return $ip === $range;
		}
		list($subnet, $bits) = explode('/', $range);
		$ip = ip2long($ip);
		$subnet = ip2long($subnet);
		$mask = -1 << (32 - $bits);
		$subnet &= $mask;
		return ($ip & $mask) == $subnet;
	}

       

    }
}

new PPO_Down;
