<?php
/**
 * VR票务插件 - C端票夹API控制器
 *
 * 路由机制（PluginsService::PluginsApiCall）:
 *   URL: /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=ticket&pluginsaction=list
 *   → pluginsname=vr_ticket, pluginscontrol=ticket, pluginsaction=list
 *   → class = \app\plugins\vr_ticket\api\Ticket (ucfirst('ticket') = 'Ticket')
 *   → method = ucfirst('list') = 'list'
 *   → app/plugins/vr_ticket/api/Ticket.php::list()  ✓
 *
 * @package vr_ticket\api
 */

namespace app\plugins\vr_ticket\api;

use app\plugins\vr_ticket\service\WalletService;

/**
 * C端票夹 API
 */
class Ticket
{
    private static function getUserId()
    {
        // 方式1：X-Token / Authorization header（JS 发送方式）
        $token = request()->header('X-Token') ?: request()->header('Authorization', '');
        if (!empty($token)) {
            $token = trim(str_replace('Bearer ', '', $token));
        }

        if (!empty($token)) {
            // 优先用 vrt_user_platform.token 查 DB（App 登录场景）
            $user = \app\service\UserService::UserTokenData($token);
            if (!empty($user) && !empty($user['id'])) {
                return intval($user['id']);
            }

            // 如果没查到，说明是 web 登录 token（存在 user_info cookie 里，不在 vrt_user_platform）
            // 尝试从 user_info cookie 直接解码（cookie 内容 = 用户 JSON）
            $userInfoCookie = request()->cookie('user_info');
            if (!empty($userInfoCookie)) {
                $decoded = urldecode($userInfoCookie);
                $userData = json_decode($decoded, true);
                if (!empty($userData) && !empty($userData['id'])) {
                    return intval($userData['id']);
                }
            }
        }

        // 方式2：ShopXO 标准方式（session / cookie，适用于页面直接访问场景）
        $user = \app\service\UserService::LoginUserInfo();
        if (!empty($user) && !empty($user['id'])) {
            return intval($user['id']);
        }

        return null;
    }

    /**
     * 返回未登录错误
     *
     * @return Json
     */
    private static function unauthorized(string $msg = '请先登录')
    {
        return [
            'code' => 401,
            'msg'  => $msg,
            'data' => [],
        ];
    }

    /**
     * 返回成功响应
     *
     * @param mixed $data
     * @param string $msg
     * @return Json
     */
    private static function success($data = [], string $msg = 'success')
    {
        return [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
        ];
    }

    /**
     * 返回错误响应
     *
     * @param string $msg
     * @param int $code
     * @return Json
     */
    private static function error(string $msg = '请求失败', int $code = -1)
    {
        return [
            'code' => $code,
            'msg'  => $msg,
            'data' => [],
        ];
    }

    /**
     * 获取用户票列表
     *
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=ticket&pluginsaction=list
     *
     * @return Json
     */
    public function list()
    {
        $userId = self::getUserId();
        if (empty($userId)) {
            return self::unauthorized();
        }

        try {
            $tickets = WalletService::getUserTickets($userId);

            return self::success([
                'tickets' => $tickets,
                'count'   => count($tickets),
            ]);
        } catch (\Exception $e) {
            return self::error('获取票列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取用户票列表（tickets 别名，兼容文档格式）
     *
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=ticket&pluginsaction=tickets
     *
     * @return Json
     */
    public function tickets()
    {
        $userId = self::getUserId();
        if (empty($userId)) {
            return self::unauthorized();
        }

        try {
            $tickets = WalletService::getUserTickets($userId);

            return self::success([
                'tickets' => $tickets,
                'count'   => count($tickets),
            ]);
        } catch (\Exception $e) {
            return self::error('获取票列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取票详情（含 QR payload）
     *
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=ticket&pluginsaction=detail&id=X
     *
     * @return Json
     */
    public function detail()
    {
        $userId = self::getUserId();
        if (empty($userId)) {
            return self::unauthorized();
        }

        $ticketId = input('id', 0, 'intval');
        if ($ticketId <= 0) {
            return self::error('参数错误：票ID无效');
        }

        try {
            $ticket = WalletService::getTicketDetail($ticketId, $userId);

            if (empty($ticket)) {
                return self::error('票不存在或无权访问', -404);
            }

            return self::success([
                'ticket' => $ticket,
            ]);
        } catch (\Exception $e) {
            return self::error('获取票详情失败: ' . $e->getMessage());
        }
    }

    /**
     * 强制刷新 QR payload
     *
     * GET /api.php?s=plugins/index&pluginsname=vr_ticket&pluginscontrol=ticket&pluginsaction=refreshQr&id=X
     *
     * @return Json
     */
    public function refreshQr()
    {
        $userId = self::getUserId();
        if (empty($userId)) {
            return self::unauthorized();
        }

        $ticketId = input('id', 0, 'intval');
        if ($ticketId <= 0) {
            return self::error('参数错误：票ID无效');
        }

        try {
            $ticket = WalletService::refreshQrPayload($ticketId, $userId);

            if (empty($ticket)) {
                return self::error('票不存在或无权访问', -404);
            }

            return self::success([
                'ticket' => $ticket,
            ]);
        } catch (\Exception $e) {
            return self::error('刷新QR失败: ' . $e->getMessage());
        }
    }
}
