<?php 
//文件下载

header("Content-type:text/html;character=utf-8");
date_default_timezone_set('PRC');
global $current_user;

$token = !empty($_GET['token']) ? $_GET['token'] : 0;
$user_id = $current_user->ID;
$today = date('Y-m-d');
$get = geturl($token,'ppo_down_encode'); 

$id = $get['id']; //下载序号
$post_id = $get['post_id']; 
$time = $get['time'];

$meta = get_post_meta($post_id,'_ppo_post_options',true);
$dd_data = $meta['dd_box_data'];
$dd_data['pid'] = $post_id;
$pay_type = $dd_data['pay_type'];

if(isset($post_id)){
	$down_data = PPO_Down::get_user_down_num($user_id);
	$bought = PPO_Down::check_user_bought($dd_data);

	$down_item = $meta['down_item'];
	$down_link = $down_item[$id]['link'];
	$home_url = esc_url(home_url());

	if(strpos($down_link,$home_url) !== false){
		$parse_url = parse_url($down_link);
		$down_link  = $parse_url['path'];
	}

	// 判断用户是否购买或有剩余下载次数
	if($bought){
		// 如果日期变更，先更新数据并重新获取
		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_data = PPO_Down::get_user_down_num($user_id);
		}

		$times = $down_data['down_num'];

		if($times >= 9999) { // 无限次则直接下载，不更新数据
			PPO_Down::go_down($down_link);
			exit();
		}

		if($times <= 0){
			wp_die('抱歉，今日下载额度已用完');
		} else {
			$_times = $times - 1;
			$down_data['down_num'] = $_times;
			update_user_meta($user_id,'user_down_num',$down_data);
			PPO_Down::go_down($down_link);
			exit();
		}
	} else {
		wp_die('抱歉，您没有下载权限');
	} 

	
}

