<?php
declare (strict_types = 1);

namespace app\admin\controller\api;

use app\manager\model\Member as MemberModel;
use think\admin\Controller;


/**
 * 会员接口管理
 */
class Member extends Controller
{
    /**
     * 验证会员状态
     */
    public function check()
    {
        // 接收参数
        $keyword = trim(input('keyword', ''));
        if (empty($keyword)) {
            return json([
                'code' => 1,
                'msg' => '请输入查询关键字'
            ]);
        }

        // 查询会员信息 (email = xxx OR order_id = xxx)
        $member = MemberModel::whereOr('email', '=', $keyword)
            ->whereOr('order_id', '=', $keyword)
            ->find();

        if (empty($member)) {
            return json([
                'code' => 1,
                'msg' => '会员不存在'
            ]);
        }

        // 检查会员状态
        if ($member['status'] != 1) {
            return json([
                'code' => 1,
                'msg' => '会员已被禁用'
            ]);
        }

        // 检查有效期
        if (strtotime($member['expire_time']) < time()) {
            return json([
                'code' => 1,
                'msg' => '会员已过期'
            ]);
        }

        // 检查使用次数
        if ($member['usage_limit'] > 0 && $member['used_count'] >= $member['usage_limit']) {
            return json([
                'code' => 1,
                'msg' => '使用次数已达上限'
            ]);
        }

        // 更新使用次数和最后登录信息
        $member->used_count = $member->used_count + 1;
        $member->last_login_time = date('Y-m-d H:i:s');
        $member->last_login_ip = $this->request->ip();
        $member->save();

        // 返回成功
        return json([
            'code' => 0,
            'msg' => '验证通过',
            'data' => [
                'email' => $member['email'],
                'order_id' => $member['order_id'],
                'expire_time' => $member['expire_time'],
                'usage_limit' => $member['usage_limit'],
                'used_count' => $member['used_count'],
                'last_login_time' => $member['last_login_time']
            ]
        ]);
    }
} 