<?php

namespace app\controller\api;

use support\Request;

use App\Utils\ApiResponse;
use App\Utils\Random;

use Tinywan\Jwt\JwtToken;
use App\model\User;
use App\Utils\ApiResponseApp;

/**
 * @Apidoc\Title("用户控制器")
 */

class UserController
{

    /**
     * 不需要登录的方法
     */
    protected $noNeedLogin = ['login', 'register'];

    /**
     * 登录
     * @param Request $request
     * @return void
     */
    public function login(Request $request)
    {
        // 获取请求数据
        $username = $request->post('username');
        $password = $request->post('password');
        // 根据手机号查询用户
        $user = User::where('username', '=', $username)->first();

        // // 如果未找到用户，返回错误
        if (!$user) {
            return ApiResponseApp::error('账号或密码错误');
        }

        // 验证密码是否正确
        if (!password_verify($password, $user->password)) {
            return ApiResponseApp::error('账号或密码错误');
        }
        $user->login_ip = $request->getRealIp($safe_mode = true);
        $user->login_time = time();
        $user->save();
        $tmp = [
            'id'  => $user->id,
            'username'  => $user->username,
            'access_exp'  => 2592000, 
        ];
        // 如果密码正确，生成 JWT 令牌
        $token = JwtToken::generateToken($tmp);
        $createtime=time();
        // 返回成功响应和用户信息（可以将 token 添加到响应中）
        $res = array('userinfo' => array('createtime' => $createtime, 'expires_in' => $tmp['access_exp'], 'expiretime' => $createtime+$tmp['access_exp'], 'id' => $user->id, 'money' => $user->money, 'token' => $token['access_token'], 'user_id' => $user->id, 'username' => $user->username));
        return ApiResponseApp::success($res,'登录成功');
    }

    /**
     * 注册
     */
    public function register(Request $request)
    {
        $username = $request->post('username');
        $password = $request->post('password');
        $invitation = $request->post('invitation');

        if (User::where('username', $username)->count() > 0) {
            return ApiResponseApp::error([], "账号已存在");
        }
        $f_id = 0;
        if (!empty($invitation)) {
            if (User::where('invite_code', $invitation)->count() == 0) {
                return ApiResponseApp::error([], "代理不存在");
            } else {
                $f_id = User::where('invite_code', $invitation)->first('id');
            }
        }
        $user = new User();
        $col = ['username'];
        foreach ($col as $v) {
            $user->$v = $request->post($v);
        }
        $user->join_ip = $request->getRealIp($safe_mode = true);
        $user->f_id = $f_id;
        $user->invite_code = Random::str_random(5);
        $user->password = password_hash($password, PASSWORD_DEFAULT);
        $user->save();
        return ApiResponseApp::success([], '注册成功');
    }
    public function userInfo(Request $request) {
        $user_id= $request->data['id'];
        $user=User::find($user_id);
        return ApiResponseApp::success($user);
    }
}
