<?php
@header('Content-Type: application/json; charset=UTF-8');
include(dirname(__DIR__) . '/includes/common.php');
if($islogin!=1)exit("<script language='javascript'>window.location.href='./login.php';</script>");
$act=isset($_GET['act'])?daddslashes($_GET['act']):null;
switch($act){
case 'list':
	$biz = isset($_GET['biz']) ? daddslashes($_GET['biz']) : 'all';
	if(!in_array($biz, ['all','cloud','dg','qzone'], true)) $biz = 'all';
	$has_goods_version_col = $DB->getColumn("SHOW COLUMNS FROM pre_goods LIKE 'version'");
	$where = '1=1';
	if(!$has_goods_version_col){
		if($biz !== 'all' && $biz !== 'cloud'){
			$where = '0=1';
		}
	}else{
		if($biz === 'cloud'){
			$where = "(version='cloud' OR version='' OR version IS NULL OR version='cloud_all' OR version='all')";
		}elseif($biz === 'dg'){
			$where = "(version='dg' OR version='dg_all')";
		}elseif($biz === 'qzone'){
			$where = "version='qzone'";
		}
	}
	$numrows=$DB->getColumn("SELECT count(*) FROM pre_goods WHERE {$where}");
	$pagesize=isset($_GET['limit'])?intval($_GET['limit']):30;//每页显示数量
	if($pagesize>200)$pagesize=200;
	$pages=ceil($numrows/$pagesize);//总页数
	$page=isset($_GET['page'])?intval($_GET['page']):1;//当前页数
	$offset=isset($_GET['offset'])?intval($_GET['offset']):$pagesize*($page - 1);//SQL语句起始索引

	$_price = [];
	$rs=$DB->query("SELECT id,name FROM `pre_price`");
	if($rs !== false){
		while($res = $rs->fetch(PDO::FETCH_ASSOC)){
			$_price[$res['id']] = $res;
		}
	}

	$cid = get_login_class(1);
	$rows = [];
	$rs=$DB->query("SELECT * FROM `pre_goods` WHERE {$where} ORDER BY id DESC LIMIT $offset,$pagesize");
	if($rs !== false){
		while($res = $rs->fetch(PDO::FETCH_ASSOC)){
			$version = isset($res['version']) && $res['version'] !== '' ? $res['version'] : 'cloud';
			if($version === 'all') $version = 'cloud_all';
			$res['version'] = $version;
			if($version === 'qzone'){
				$res['names'] = '秒赞版无分类';
			}elseif($version === 'tri_all'){
				$cn = isset($cid[intval($res['type_cloud'] ?? 0)]['name']) ? $cid[intval($res['type_cloud'] ?? 0)]['name'] : '未分类';
				$dn = isset($cid[intval($res['type_dg'] ?? 0)]['name']) ? $cid[intval($res['type_dg'] ?? 0)]['name'] : '未分类';
				$res['names'] = '云端:' . $cn . ' / 代挂:' . $dn;
			}elseif($res['type'] == 9999){
				// 后台列表仅展示“全部接口”标签
				$res['names'] = '全部接口';
			}else{
				$res['names'] = isset($cid[$res['type']]['name']) ? $cid[$res['type']]['name'] : '未分类';
			}
			
			$res['pricename'] = '';
			$rows[] = $res;
		}
	}
	exit(json_encode(array('total'=>$numrows,'rows'=>$rows,'cid'=>$cid)));
break;
case 'edit':
	$id = intval($_POST['id']);
	$zt = intval($_POST['zt']);
	$type = daddslashes($_POST['type']);
	if($type == 'zt'){
		$sql = "UPDATE pre_goods SET status='".$zt."' WHERE id='{$id}'";
	}elseif($type == 'del'){
		$sql = "DELETE FROM pre_goods WHERE id='{$id}'";
	}elseif($type == 'activity_toggle'){
		// 切换活动状态
		$activity_enabled = intval($_POST['activity_enabled']);
		$sql = "UPDATE pre_goods SET activity_enabled='".$activity_enabled."' WHERE id='{$id}'";
	}elseif($type == 'activity_discount'){
		// 更新活动折扣
		$activity_discount = intval($_POST['activity_discount']);
		if($activity_discount < 1 || $activity_discount > 100){
			exit('{"code":-1,"msg":"折扣必须在1-100之间"}');
		}
		$sql = "UPDATE pre_goods SET activity_discount='".$activity_discount."' WHERE id='{$id}'";
	}else{
		exit('{"code":-1,"msg":"类型错误"}');
	}
	if($DB->exec($sql)){
		exit('{"code":1,"msg":"操作成功"}');
	}else{
		exit('{"code":-1,"msg":"操作失败"}');
	}
break;
case 'sync_activity':
	// 同步活动到同分类商品
	$cid = daddslashes($_POST['cid']);
	$activity_enabled = intval($_POST['activity_enabled']);
	$activity_start = !empty($_POST['activity_start']) ? date('Y-m-d H:i:s', strtotime($_POST['activity_start'])) : null;
	$activity_end = !empty($_POST['activity_end']) ? date('Y-m-d H:i:s', strtotime($_POST['activity_end'])) : null;
	$activity_discount = intval($_POST['activity_discount']);

	if($activity_discount < 1 || $activity_discount > 100){
		$activity_discount = 100;
	}

	// 构建更新条件
	$where = '';
	if($cid == 'all'){
		// 所有商品
		$where = '1=1';
	}elseif($cid == 'dg'){
		// 代挂版商品
		$where = "version IN ('dg','dg_all')";
	}elseif($cid == 'qzone'){
		// 秒赞版商品
		$where = "version='qzone'";
	}elseif($cid == 'cloud'){
		// 云端版商品
		$where = "(version='cloud' OR version='' OR version IS NULL OR version IN ('cloud_all','all'))";
	}elseif($cid == '9999'){
		// 全部接口分类
		$where = "type='9999'";
	}else{
		// 指定分类
		$where = "type='".$cid."'";
	}

	// 执行更新
	$sql = "UPDATE pre_goods SET
			activity_enabled='".$activity_enabled."',
			activity_start=".($activity_start ? "'".$activity_start."'" : "NULL").",
			activity_end=".($activity_end ? "'".$activity_end."'" : "NULL").",
			activity_discount='".$activity_discount."'
			WHERE ".$where;

	$affected = $DB->exec($sql);
	if($affected !== false){
		exit('{"code":1,"msg":"同步成功，共更新 '.$affected.' 条商品记录"}');
	}else{
		exit('{"code":-1,"msg":"同步失败：'.$DB->error().'"}');
	}
break;
case 'add':
	$id = intval($_POST['id']);
	$type = daddslashes($_POST['act']);
	unset($_POST['id']);
	unset($_POST['act']);
	
	$version = isset($_POST['version']) ? daddslashes($_POST['version']) : 'cloud';
	if(!in_array($version, ['cloud','dg','qzone','cloud_all','dg_all','tri_all','all'], true)){
		exit('{"code":-1,"msg":"商品版本参数错误"}');
	}
	if($version === 'all') $version = 'cloud_all';
	$has_goods_version_col = $DB->getColumn("SHOW COLUMNS FROM pre_goods LIKE 'version'");
	if(!$has_goods_version_col){
		if($version !== 'cloud'){
			exit('{"code":-1,"msg":"数据库缺少 pre_goods.version 字段，请先执行升级SQL后再添加该版本商品"}');
		}
		unset($_POST['version']);
	}else{
		$_POST['version'] = $version;
	}
	$has_type_cloud_col = $DB->getColumn("SHOW COLUMNS FROM pre_goods LIKE 'type_cloud'");
	$has_type_dg_col = $DB->getColumn("SHOW COLUMNS FROM pre_goods LIKE 'type_dg'");
	if(!$has_type_cloud_col) unset($_POST['type_cloud']);
	if(!$has_type_dg_col) unset($_POST['type_dg']);

	if($version == 'qzone'){
		$_POST['type'] = '0';
	}else{
		if($version === 'tri_all'){
			$type_cloud = isset($_POST['type_cloud']) ? intval($_POST['type_cloud']) : 0;
			$type_dg = isset($_POST['type_dg']) ? intval($_POST['type_dg']) : 0;
			if($type_cloud <= 0 || $type_dg <= 0){
				exit('{"code":-1,"msg":"请选择云端/代挂接口分类"}');
			}
			$_POST['type'] = (string)$type_cloud;
		}else{
			if(!isset($_POST['type']) || $_POST['type']===''){
				exit('{"code":-1,"msg":"请选择接口分类"}');
			}
			if(isset($_POST['type_cloud'])) $_POST['type_cloud'] = 0;
			if(isset($_POST['type_dg'])) $_POST['type_dg'] = 0;
		}
	}

	// 处理固定等级价格
	$is_fixed_price = isset($_POST['is_fixed_price']) ? intval($_POST['is_fixed_price']) : 0;
	$_POST['is_fixed_price'] = $is_fixed_price;
	
	// 如果是固定价格，清空基础价格
	if($is_fixed_price == 1) {
		$_POST['price'] = '0';
	}
	
	// 处理 fixed_prices JSON
	if(isset($_POST['fixed_prices'])) {
		$_POST['fixed_prices'] = $_POST['fixed_prices'];
	}
	
	// 过滤掉 vip_price_* 字段，这些字段只在表单中使用
	foreach ($_POST as $k => $v) {
		if (strpos($k, 'vip_price_') === 0) {
			unset($_POST[$k]);
		}
	}

	// 处理活动字段
	$activity_enabled = isset($_POST['activity_enabled']) ? 1 : 0;
	$_POST['activity_enabled'] = $activity_enabled;
	
	$has_goods_limit_once_col = $DB->getColumn("SHOW COLUMNS FROM pre_goods LIKE 'limit_once'");
	$limit_once = (isset($_POST['limit_once']) && intval($_POST['limit_once']) == 1) ? 1 : 0;
	if($has_goods_limit_once_col){
		$_POST['limit_once'] = $limit_once;
	} else {
		unset($_POST['limit_once']);
	}

	// 处理活动时间
	if(isset($_POST['activity_start']) && !empty($_POST['activity_start'])) {
		$_POST['activity_start'] = date('Y-m-d H:i:s', strtotime($_POST['activity_start']));
	} else {
		$_POST['activity_start'] = null;
	}
	if(isset($_POST['activity_end']) && !empty($_POST['activity_end'])) {
		$_POST['activity_end'] = date('Y-m-d H:i:s', strtotime($_POST['activity_end']));
	} else {
		$_POST['activity_end'] = null;
	}

	// 处理活动折扣
	if(isset($_POST['activity_discount'])) {
		$_POST['activity_discount'] = intval($_POST['activity_discount']);
		if($_POST['activity_discount'] < 1 || $_POST['activity_discount'] > 100) {
			$_POST['activity_discount'] = 100;
		}
	}
	
	if($type == 'add'){ 
		if($sort = $DB->getRow("SELECT sort FROM pre_goods ORDER BY sort DESC LIMIT 1")){
			$_POST['sort'] = $sort['sort']+1;
		}else{
			$_POST['sort'] = '10';
		}
		$price = floatval($_POST['price']);
		$skey = array();
		$value = array();
		foreach ($_POST as $k => $v) {
			$skey[] = '`'.$k.'`';
			$value[] = "'".$v."'";
		}
		$sql = "INSERT INTO `pre_goods` (".implode(',',$skey).") VALUES (".implode(',',$value).")";
		if($DB->exec($sql)){
			exit('{"code":1,"msg":"添加成功"}');
		}else{
			exit('{"code":-1,"msg":"添加失败'.$DB->error().'"}');
		}
	}

	if($type == 'edit'){
		$_POST['num'] = intval($_POST['num']);
		
		// 如果是固定价格，清空基础价格
		if($is_fixed_price == 1) {
			$_POST['price'] = '0';
		}
		$has_goods_limit_once_col = $DB->getColumn("SHOW COLUMNS FROM pre_goods LIKE 'limit_once'");
		$limit_once = (isset($_POST['limit_once']) && intval($_POST['limit_once']) == 1) ? 1 : 0;
		if($has_goods_limit_once_col){
			$_POST['limit_once'] = $limit_once;
		} else {
			unset($_POST['limit_once']);
		}
		
		$key = array();
		$data = array();
		foreach ($_POST as $k => $v) {
			$key[] = '`'.$k.'`=:'.$k;
			$data[':'.$k] = $v;
		}
		$sql = "UPDATE `pre_goods` SET ".implode(',',$key)." WHERE id='{$id}'";
		if($DB->exec($sql,$data)){
			exit('{"code":1,"msg":"修改成功"}');
		}else{
			exit('{"code":-1,"msg":"修改失败'.$DB->error().'"}');
		}
	}
	exit('{"code":-1,"msg":"未知类型"}');
break;
default:
	exit('{"code":-4,"msg":"No Act"}');
break;
}
