<?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;
use App\dao\UserDao;
use app\dao\UserRewardDao;
use app\model\UserReward;

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

class UserController
{

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

    /**
     * @Apidoc\Title("1.0 登录")
     * @Apidoc\Url("api/user/login")
     * @Apidoc\Method("POST")
     */
    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, '登录成功');
    }
    /**
     * @Apidoc\Title("1.0 注册")
     * @Apidoc\Url("api/user/register")
     * @Apidoc\Method("POST")
     */
    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;
        $ff_id =0;
        if (!empty($invitation)) {
            if (User::where('invite_code', $invitation)->count() == 0) {
                return ApiResponseApp::error([], "代理不存在");
            } else {
                $f = User::where('invite_code', $invitation)->first();
                $f_id=$f->id;
                $ff_id = $f->f_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->ff_id = $ff_id;
        $user->invite_code = Random::str_random(5);
        $user->password = password_hash($password, PASSWORD_DEFAULT);
        $user->save();
        $user_new=User::where('username', $username)->first();
        var_dump($user_new);
        UserRewardDao::Register_for_free($user_new->id);
        return ApiResponseApp::success([], '注册成功');
    }
    /**
     * @Apidoc\Title("1.0 获取用户相关信息")
     * @Apidoc\Url("api/user/userInfo")
     * @Apidoc\Method("POST")
     */
    public function userInfo(Request $request)
    {
        $user_id = $request->data['id'];
        
        return ApiResponseApp::success(UserDao::get_index_userInfo($user_id));
    }
    /**
     * @Apidoc\Title("1.0 获取用户佣金信息")
     * @Apidoc\Url("api/user/team_info")
     * @Apidoc\Method("POST")
     */
    public function team_info(Request $request)
    {
        $user_id = $request->data['id'];
        $user = User::find($user_id);
        $res = [
            //活跃用户数
            'active_users' => UserDao::active_users($user_id),
            //所有收入总和
            'all_income' => UserDao::all_income($user_id),
            //邀请码
            'invite_code' => $user->invite_code,
            //直属活跃
            'level_1' => UserDao::level_1($user_id),
            //今天收入
            'today_income' => UserDao::today_team_income($user_id),
            //昨天收入
            'yesterday_income' => UserDao::today_team_income_old($user_id),
        ];
        return ApiResponseApp::success($res);
    }

    /**
     * @Apidoc\Title("1.0 修改密码")
     * @Apidoc\Url("api/user/uppassword")
     * @Apidoc\Method("POST")
     */
    public function uppassword(Request $request)
    {
        $old_password = $request->post('old_password');
        $new_password = $request->post('new_password');
        $user_id=$request->data['id'];
        $user=User::find($user_id);
        if (!password_verify($old_password, $user->password)) {
            return ApiResponseApp::error([], "原密码错误");
        }
        //修改密码
        $user->password = password_hash($new_password, PASSWORD_DEFAULT);
        //保存到数据库
        $user->save();
        return ApiResponseApp::success('修改成功');
    }
}
