<?php

namespace App\Admin\Controllers;

use App\Models\AdminUsers;
use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    protected $view = 'admin.login';

    public function getLogin(Content $content)
    {
        // 获取角色参数
        $role = request()->get('role');

        // 根据角色参数决定登录页面
        if ($role === 'store') {
            $this->view = 'admin.loginstore'; // 店铺管理员登录页面
        } else {
            $this->view = 'admin.login'; // 默认管理员登录页面
        }

        if ($this->guard()->check()) {
            return redirect($this->getRedirectPath());
        }

        return $content->full()->body(view($this->view));
    }

    /**
     * Handle a login request.
     *
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        $role = $request->input('role'); // 获取角色参数
        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username() => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        $user = AdminUsers::where(['username' => $credentials['username']])->first();
        if (isset($user->is_block) && $user->is_block) {
            return $this->validationErrorsResponse([
                $this->username() => '账号异常，请联系管理员！',
            ]);
        }

        // 检查用户角色是否为 pharmacy
        if ($role === 'store' && $user && $user->role === 'pharmacy') {
            // 验证短信验证码
            $verificationCode = $request->input('verification_code');
            // 假设您有一个方法来验证短信验证码
            if (! $this->verifySmsCode($user->username, $verificationCode)) {
                return $this->validationErrorsResponse([
                    'verification_code' => '验证码错误或已过期！',
                ]);
            }

            // 短信验证码验证通过，执行登录
            return $this->guard()->login($user, $remember) ? $this->sendLoginResponse($request) : $this->sendFailedLoginResponse($request);
        }

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }
}
