<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\AdminRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('check.token')->except('login');
    }

    public function login(Request $request)
    {
        $name=$request->input('name');
        $admin = Admin::where('name',$name)->first();
        if(empty($admin)){
            return $this->error('450001','账号不存在');
        }
        if($admin->status == 0){
            return $this->error('450001','账号已禁用');
        }
        if(Hash::check($request->input('password'),$admin->password)){
            if ($token = Auth::guard('api')->fromUser($admin)) {
                return $this->success($token);
            }
        }else{
            return $this->error('450001','密码错误');
        }
    }

    public function editPassword(Request $request){
        $rules=[
            'password' => 'required|min:6|max:18',
        ];
        $messages = [
            'password.required' => '密码为必填项.',
            'password.min' => '密码不能少于6个字符.',
            'password.max' => '密码不能超过18个字符.',
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if($validator->fails()){
            return $this->error('450001',$validator->errors()->first());
        }
        $id= Auth::user()->id;
        $admin = Admin::where('id',$id)->first();
        if(Hash::check($request->input('oldPwd'),$admin->password)){
            $admin->password = Hash::make($request->input('password'));
            $admin->save();
            return $this->success([]);
        }else{
            return $this->error('450001','原密码错误');
        }

    }

    public function me()
    {
        $admin = Auth::user();
        $data = Admin::query()->with('role')->where('id',$admin->id)->first();
        return $this->success($data);
    }

    public function logout()
    {
        auth('api')->logout();
        return $this->success([]);;
    }
}
