<?php
/**
 * 余额充值API
 * 处理充值相关的接口请求
 */

class BalanceAPI {
    private $DB;
    private $user;
    
    public function __construct() {
        global $DB;
        $this->DB = $DB;
        $this->user = is_user_login();
    }
    
    /**
     * 处理API请求
     */
    public function handleRequest() {
        $action = isset($_POST['action']) ? $_POST['action'] : '';
        
        switch($action) {
            case 'recharge':
                $this->createRechargeOrder();
                break;
            case 'get_history':
                $this->getRechargeHistory();
                break;
            case 'get_balance':
                $this->getBalance();
                break;
            default:
                $this->error('未知操作');
        }
    }
    
    /**
     * 充值（供外部调用）
     */
    public function recharge() {
        $this->createRechargeOrder();
    }
    
    /**
     * 创建充值订单
     */
    private function createRechargeOrder() {
        if (!$this->user) {
            $this->error('请先登录');
        }
        
        $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
        $payment_method = isset($_POST['payment_method']) ? $_POST['payment_method'] : 'alipay';
        
        if ($amount <= 0) {
            $this->error('充值金额必须大于0');
        }
        
        if ($amount > 10000) {
            $this->error('单次充值金额不能超过10000元');
        }
        
        // 确保表存在
        $this->createBalanceTable();
        
        // 生成订单号
        $order_no = 'CZ' . date('YmdHis') . rand(1000, 9999);
        $uid = $this->user['id'];
        
        // 创建订单
        $sql = "INSERT INTO `balance_orders` (`order_no`, `uid`, `amount`, `payment_method`, `status`, `create_time`) 
                VALUES ('{$order_no}', '{$uid}', '{$amount}', '{$payment_method}', 'pending', NOW())";
        
        if ($this->DB->query($sql)) {
            // 获取全局支付配置
            global $alipay_config;
            
            // 检查支付配置是否完整
            if (empty($alipay_config['partner']) || empty($alipay_config['key']) || empty($alipay_config['apiurl'])) {
                $this->error('支付配置不完整，请联系管理员');
            }
            
            // 构建支付参数（易支付标准参数）
            $pay_url = $this->buildPayUrl(array(
                'pid' => $alipay_config['partner'],
                'type' => $payment_method == 'wechat' ? 'wxpay' : 'alipay',
                'out_trade_no' => $order_no,
                'notify_url' => $alipay_config['notify_url'],
                'return_url' => $alipay_config['return_url'],
                'name' => '余额充值',
                'money' => $amount,
                'clientip' => $_SERVER['REMOTE_ADDR']
            ), $alipay_config);
            
            $this->success(array(
                'order_no' => $order_no,
                'amount' => $amount,
                'pay_url' => $pay_url
            ));
        } else {
            $this->error('创建订单失败');
        }
    }
    
    /**
     * 构建支付URL
     */
    private function buildPayUrl($parameter, $alipay_config = null) {
        include(__DIR__ . '/../../MPHX/lib/submit.class.php');
        
        // 确保apiurl以斜杠结尾（在创建对象之前）
        $apiurl = $alipay_config['apiurl'];
        if (substr($apiurl, -1) !== '/') {
            $apiurl .= '/';
            $alipay_config['apiurl'] = $apiurl;
        }
        
        // 自动检测并使用当前页面协议（HTTP/HTTPS）
        $current_protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        if (strpos($apiurl, 'http://') === 0 && $current_protocol === 'https') {
            // 如果当前是HTTPS，但apiurl是HTTP，则升级为HTTPS
            $apiurl = 'https://' . substr($apiurl, 7);
            $alipay_config['apiurl'] = $apiurl;
        }
        
        $alipaySubmit = new AlipaySubmit($alipay_config);
        
        return $alipaySubmit->buildRequestForm($parameter, 'get', '确认');
    }
    
    /**
     * 获取充值记录
     */
    public function getRechargeHistory() {
        global $DB;
        
        $user = is_user_login();
        if (!$user) {
            $this->error('请先登录');
        }
        
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $page_size = isset($_POST['page_size']) ? intval($_POST['page_size']) : 10;
        $offset = ($page - 1) * $page_size;
        
        // 确保表存在
        $this->createBalanceTable();
        
        $uid = $user['id'];
        
        // 获取用户当前余额
        $user_info = intval($uid);
        $user_info = $DB->get_row("SELECT * FROM `zj` WHERE `id`='{$uid_escaped}'");
        $balance = ($user_info && isset($user_info['balance'])) ? floatval($user_info['balance']) : 0;
        
        $uid_escaped = intval($uid);
        $total = $DB->count("SELECT COUNT(*) FROM `balance_orders` WHERE `uid`='{$uid_escaped}'");
        
        $uid_escaped = intval($uid);
        $offset_escaped = intval($offset);
        $page_size_escaped = intval($page_size);
        $sql = "SELECT * FROM `balance_orders` WHERE `uid`='{$uid_escaped}' ORDER BY `id` DESC LIMIT {$offset_escaped}, {$page_size_escaped}";
        $result = $DB->query($sql);
        
        $list = array();
        while ($row = $DB->fetch($result)) {
            $list[] = array(
                'order_no' => $row['order_no'],
                'amount' => floatval($row['amount']),
                'payment_method' => $row['payment_method'],
                'status' => $row['status'],
                'pay_time' => $row['pay_time'],
                'create_time' => $row['create_time']
            );
        }
        
        $this->success(array(
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'page_size' => $page_size,
            'balance' => $balance
        ));
    }
    
    /**
     * 获取余额
     */
    private function getBalance() {
        if (!$this->user) {
            $this->error('请先登录');
        }
        
        $user_id_escaped = intval($this->user['id']);
        $user_info = $this->DB->get_row("SELECT * FROM `zj` WHERE `id`='{$user_id_escaped}'");
        $balance = ($user_info && isset($user_info['balance'])) ? floatval($user_info['balance']) : 0;
        
        $this->success(array('balance' => $balance));
    }
    
    /**
     * 创建余额订单表
     */
    private function createBalanceTable() {
        $sql = "CREATE TABLE IF NOT EXISTS `balance_orders` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `order_no` varchar(50) NOT NULL,
            `uid` int(11) NOT NULL,
            `amount` decimal(10,2) NOT NULL,
            `payment_method` varchar(20) NOT NULL DEFAULT 'alipay',
            `status` varchar(20) NOT NULL DEFAULT 'pending',
            `pay_time` datetime DEFAULT NULL,
            `create_time` datetime NOT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `order_no` (`order_no`),
            KEY `uid` (`uid`),
            KEY `status` (`status`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
        
        $this->DB->query($sql);
        
        // 检查 zj 表是否有 balance 字段
        $result = $this->DB->query("SHOW COLUMNS FROM `zj` LIKE 'balance'");
        if ($this->DB->num_rows($result) == 0) {
            $this->DB->query("ALTER TABLE `zj` ADD `balance` decimal(10,2) NOT NULL DEFAULT '0.00' AFTER `zt`");
        }
    }
    
    /**
     * 成功响应
     */
    private function success($data) {
        header('Content-Type: application/json; charset=UTF-8');
        echo json_encode(array(
            'status' => true,
            'code' => 'success',
            'data' => $data
        ));
        exit;
    }
    
    /**
     * 错误响应
     */
    private function error($message) {
        header('Content-Type: application/json; charset=UTF-8');
        echo json_encode(array(
            'status' => false,
            'code' => 'error',
            'msg' => $message
        ));
        exit;
    }
}

// 处理请求
$api = new BalanceAPI();
$api->handleRequest();
