<?php

namespace app\controller;

use support\Request;
use yzh52521\EasyHttp\Response;
use yzh52521\EasyHttp\RequestException;
use yzh52521\EasyHttp\Http;
use support\Db;
use Webman\Captcha\CaptchaBuilder;

class Account
{
    public function login(Request $request)
    {
        $session = $request->session();
        $user=$session->get('user',null);
        if($user!=null){
            return redirect('/my');
        }
        return view('login');
    }
    public function logout(Request $request)
    {
        $session = $request->session();
        $session->delete('user');
        $session->delete('realname');
        return redirect('/');
    }
    public function my(Request $request)
    {
        $session = $request->session();
        $user=$session->get('user',null);
        $realname=$session->get('realname',null);
        if($user==null||$realname==null){
            return redirect('/');
        }
        $record=Db::table('links')->where('user', "$user")->get();
        print_r($record);
        return view('my', ['user' => $user,'realname' => $realname,'record' => $record]);
    }
    public function captcha(Request $request)
    {
         // 初始化验证码类
         $builder = new CaptchaBuilder;
         // 生成验证码
         $builder->build();
         // 将验证码的值存储到session中
         $request->session()->set('captcha', strtolower($builder->getPhrase()));
         // 获得验证码图片二进制数据
         $img_content = $builder->get();
         // 输出验证码二进制数据
         return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }
    public function loginapi(Request $request)
    {
        $session = $request->session();
        $username = $request->input('username');
        $password = $request->input('password');
        $captcha = $request->input('captcha');
        $captcha_session = $request->session()->get('captcha');
        if(strtolower($captcha) != $captcha_session){
            return json(['code' => 400, 'msg' => '验证码错误']);
        }
        if($username == null || $password == null){
            return json(['code' => 400, 'msg' => '用户名或密码不能为空']);
        }
        if(strlen($username)>=36){
            return json(['code' => 400, 'msg' => '用户名格式错误']);
        }
        $username=Db::table('users')->where('username', "$username")->where('password',"$password")->value('username');
        if($username==null){
            return json(['code' => 400, 'msg' => '用户名或密码错误']);
        }else{
            $session->set('user', $username);
            $session->set('realname', Db::table('users')->where('username', "$username")->value('realname'));
            return json(['code' => 200, 'msg' => '登陆成功']);
        }
    }
}