<?php

namespace App\Merchant\Controllers;

use Auth;
use Illuminate\Http\Request;
use Validator;

class AuthController extends Controller
{

    public function login(Request $request)
    {
        if ($request->isMethod('post')) {

            $validator = Validator::make($request->all(), [
                'username' => 'required|min:4',
                'password' => 'required|min:6',
            ], [
                'username.requird' => '用户名不能为空',
                'username.min'     => '用户名不能小于:min字符',
                'password.requird' => '密码不能为空',
                'password.min'     => '密码不能小于:min字符',
            ]);

            if ($validator->fails()) {
                return [
                    'code' => 0,
                    'msg'  => $validator->errors()->first(),
                ];
            }

            $remember = $request->remember ?: false;
            if (Auth::guard('merchant')->attempt(['username' => $request->username, 'password' => $request->password], $remember)) {
                $user = Auth::guard('merchant')->user();
                if (in_array($user->identity->identity_id, ['1'])) {
                    return [
                        'code' => 1,
                        'msg'  => '登录成功',
                        'url'  => route('merchant.index'),
                    ];
                } else {
                    Auth::guard('merchant')->logout();
                    session()->flush();
                    return [
                        'code' => 0,
                        'msg'  => '没有登录权限',
                    ];
                }
            } else {
                return [
                    'code' => 0,
                    'msg'  => '用户名或密码错误',
                ];
            }
        } else {
            return view('Merchant::auth.login');
        }
    }

    public function logout(Request $request)
    {
        Auth::guard('merchant')->logout();
        session()->flush();
        return $this->success('注销成功', 'merchant.login');
    }
}
