<?php

namespace app\adminapi\controller;

use app\adminapi\BaseController;
use support\Request;
use think\facade\Db;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        
        $req = $request->post();

        $username = $req['username'];
        $password = $req['password'];

        $admin_user=Db::name('admin')
        ->where('username',$username)
        ->find();

        if(!$admin_user){
            return $this->Error('帳號或密碼錯誤',302);                
        }

        if(!password_verify($password , $admin_user['password'])){
            return $this->Error('帳號或密碼錯誤',303);
        }
        
        // 登入成功,產生token
        $key = 'jwtkey123456';

        $payload = [
            'iss' => 'prodio',
            'exp' => time()+30*60*1000,
            'iat' => time(),
            'nbf' => time(),
            'jti' => md5(uniqid('JWT').time()),
            'uid' => $admin_user['id'],
        ];

        try{
            $jwt = JWT::encode($payload, $key, 'HS256');

            $result=[
                'token'=>$jwt,
            ];
            
            $data = [
                'login_time' => time(),
                'login_num' => $admin_user['login_num']+1,
            ];

            Db::name('admin')
            ->where('id',$admin_user['id'])
            ->update($data);
            
            return $this->Success($result);
    
        }catch(\Exception $e){
            return $this->Error('登入失敗');                
        }
    }
}
