<?php

namespace Wave\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;
use App\Models\SiteSetting;
use App\Models\UserAccessLog;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/cms/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function username(){
        if(setting('auth.email_or_username')){
            return setting('auth.email_or_username');
        }

        return 'email';
    }

    public function showLoginForm()
    {
        return view('theme::auth.user-login');
    }

    protected function authenticated(Request $request, $user)
    {
        if(!$user->verified){
            $this->guard()->logout();
            return redirect()->back()->with(['message' => 'Please verify your email before logging into your account.', 'message_type' => 'warning']);
        }
        if ($request->user_type == 'user') {
            if ($user->status == 'inactive'){
                $this->guard()->logout();
                return redirect()->back()->with(['message' => 'User is currently deactivated.', 'message_type' => 'warning']);
            }
            if (!in_array($user->role_id, [Role::OWNER_ROLE, Role::ADMINISTRATOR_ROLE, Role::BOOKKEEPER_ROLE, Role::COMPANY_SECRETARY_ROLE])) {
                $this->guard()->logout();
                return redirect()->back()->with(['message' => 'Wrong Email or Password', 'message_type' => 'warning']);
            }
        }
        if ($request->user_type == 'admin') {
            if ($user->status == 'inactive'){
                $this->guard()->logout();
                return redirect()->back()->withErrors(['email' => 'User is currently deactivated.']);
            }
            if(!in_array($user->role_id, [Role::IT_PERSONNEL_ROLE, Role::NUMSTATION_MANAGER_ROLE, Role::NUMSTATION_STAFF_ROLE])) {
                $this->guard()->logout();
                return redirect()->back()->withErrors(['email' => 'These credentials do not match our records.']);
            }
        }

        UserAccessLog::create([
            'user_id' => $user->id,
            'event' => 'Login',
            'description' => 'Login to [' . $user->email . ']',
            'status' => 'success',
        ]);
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended(Auth::user()->getRedirectRoute())->with(['message' => 'Successfully logged in.', 'message_type' => 'success']);
    }
    
    protected function sendFailedLoginResponse(Request $request)
    {
        if($request->user_type == 'user') {
            return redirect()->back()->with(['message' => 'Wrong Email or Password', 'message_type' => 'warning']);
        }
        else {
            return redirect()->back()->withErrors(['email' => 'These credentials do not match our records.']);
        }
    }

    public function logout()
    {
        $user = auth()->user();
        UserAccessLog::create([
            'user_id' => $user->id,
            'event' => 'Logout',
            'description' => 'Logout [' . $user->email . ']',
            'status' => 'success',
        ]);

        Auth::logout();
        return redirect($user->getRedirectRouteIfNotAuthenticated());
    }

    public function showAdminLoginForm()
    {
        return view('theme::auth.login');
    }

    public function termsAndConditions()
    {
        $siteSetting = SiteSetting::latest()->first();
        return view('theme::auth.terms-and-conditions', [
            'siteSetting' => $siteSetting,
        ]);
    }

    public function privacyPolicy()
    {
        $siteSetting = SiteSetting::latest()->first();
        return view('theme::auth.privacy-policy', [
            'siteSetting' => $siteSetting,
        ]);
    }

    public function apiLogin(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'email' => 'required',
            'password' => 'required',
        ]);
        if ($validate->fails()) {
            return response()->json([
                'status' => false,
                'message' => $validate->messages(),
            ]);
        }

        $user = User::where('email', $request->email)->first();

        if ($user) {
            if (\Hash::check($request->password, $user->password)) {
                $token = \Str::random(60);
 
                $user->forceFill([
                    'api_token' => hash('sha256', $token),
                ])->save();

                return response()->json([
                    'status' => true,
                    'user' => array(
                        'id' => $user->id,
                        'first_name' => $user->first_name,
                        'last_name' => $user->last_name,
                        'email' => $user->email,
                        'username' => $user->username,
                        'api_token' => $token,
                    ),
                ]);
            }
        }

        return response()->json([
            'status' => false,
            'message' => 'Invalid Email or Password',
        ]);
    }
}
