<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use App\Helper;
use App\Models\Users;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use App\Models\UserLogs;

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 = RouteServiceProvider::HOME;

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

    public function username()
    {
        return "email";
    }

    // public function login(Request $req)
    // {
    //     $this->validateLogin($req);

    //     if (method_exists($this, "hasTooManyLoginAttempts") && $this->hasTooManyLoginAttempts($req)) {
    //         $this->fireLockoutEvent($req);

    //         return $this->sendLockoutResponse($req);
    //     }

    //     if ($this->guard()->validate($this->credentials($req))) {
    //         $user = $this->guard()->getLastAttempted();

    //         if ($user->dlt != null) {
    //             $this->incrementLoginAttempts($req);
    //             throw ValidationException::withMessages([
    //                 $this->username() => [trans("auth.failed")],
    //             ]);
    //         }
    //         if ($user->status != Users::STATUS_ACTIVE) {
    //             $this->incrementLoginAttempts($req);

    //             throw ValidationException::withMessages([
    //                 $this->username() => __("Your account not active, please contact admin."),
    //             ]);
    //         }

    //         if ($this->attemptLogin($req)) {
    //             return $this->sendLoginResponse($req);
    //         }
    //     }

    //     $this->incrementLoginAttempts($req);

    //     return $this->sendFailedLoginResponse($req);
    // }
    public function login(Request $req)
    {
        $this->validateLogin($req);

        if (method_exists($this, "hasTooManyLoginAttempts") && $this->hasTooManyLoginAttempts($req)) {
            $this->fireLockoutEvent($req);
            return $this->sendLockoutResponse($req);
        }

        // Cari user yang belum dihapus (dlt == null)
        $user = Users::where("email", $req->email)
            ->whereNull("dlt")
            ->first();

        if (!$user || !\Hash::check($req->password, $user->password)) {
            $this->incrementLoginAttempts($req);
            return $this->sendFailedLoginResponse($req);
        }

        if ($user->status != Users::STATUS_ACTIVE) {
            $this->incrementLoginAttempts($req);
            throw ValidationException::withMessages([
                $this->username() => __("Your account not active, please contact admin."),
            ]);
        }

        // Login manual
        $this->guard()->login($user);

        return $this->sendLoginResponse($req);
    }

    protected function validateLogin(Request $req)
    {
        $this->validate($req, [
            $this->username() => "required|string|email",
            "password" => "required|string",
        ]);
    }

    protected function sendLoginResponse(Request $req)
    {
        $req->session()->regenerate();

        $this->clearLoginAttempts($req);

        if ($response = $this->authenticated($req, $this->guard()->user())) {
            return $response;
        }

        // return $req->wantsJson()
        //     ? new JsonResponse([], 204)
        //     : redirect()->intended($this->redirectPath());
        // return $req->wantsJson()
        //     ? new JsonResponse([], 204)
        //     : redirect(route('view_dashboard'));
		$log = [
			"module" => "Auth",
			"action" => "Login",
			"desc" => "User login",
		];
		UserLogs::insert(Auth::user()->id, $log);

        if ($req->wantsJson()) {
            return new JsonResponse([], 204);
        } else {
            $user = Auth::user();
            if ($user->role == Users::ROLE_ADMIN) {
                return redirect(route("view_dashboard"));
            } elseif ($user->role == Users::ROLE_VENDOR) {
                return redirect(route("view_dashboard"));
            } elseif ($user->role == Users::ROLE_CHECKER) {
                return redirect(route("view_user_checker"));
            } elseif ($user->role == Users::ROLE_CLIENT_ADMIN) {
                return redirect(route("view_user_client_transaction_add") . "?rdl=1");
            } elseif ($user->role == Users::ROLE_SPECIAL_TRACKING) {
                return redirect(route("view_dashboard"));
            } elseif ($user->role == Users::ROLE_FINANCE) {
                return redirect(route("view_keuangan_payment"));
            } else {
                $this->guard()->logout();
                $req->session()->invalidate();
                $req->session()->regenerateToken();
                // return redirect(route('login'));
                return redirect(route("login"));
            }
        }
    }

    public function logout(Request $req)
    {
        $user = Auth::user();
		$log = [
			"module" => "Auth",
			"action" => "Logout",
			"desc" => "User logout",
		];
		UserLogs::insert(Auth::user()->id, $log);

		if ($user->role == Users::ROLE_ADMIN) {
            $this->guard()->logout();
            $req->session()->invalidate();
            $req->session()->regenerateToken();
            if ($response = $this->loggedOut($req)) {
                return $response;
            }
            return $req->wantsJson() ? new JsonResponse([], 204) : redirect(route("login_admin"));
        } elseif ($user->role == Users::ROLE_FINANCE) {
            $this->guard()->logout();
            $req->session()->invalidate();
            $req->session()->regenerateToken();
            if ($response = $this->loggedOut($req)) {
                return $response;
            }
            return $req->wantsJson() ? new JsonResponse([], 204) : redirect(route("login_admin"));
        } elseif ($user->role == Users::ROLE_VENDOR) {
            $this->guard()->logout();
            $req->session()->invalidate();
            $req->session()->regenerateToken();
            if ($response = $this->loggedOut($req)) {
                return $response;
            }
            return $req->wantsJson() ? new JsonResponse([], 204) : redirect(route("login_vendor"));
        } elseif ($user->role == Users::ROLE_CHECKER) {
            $this->guard()->logout();
            $req->session()->invalidate();
            $req->session()->regenerateToken();
            if ($response = $this->loggedOut($req)) {
                return $response;
            }
            return $req->wantsJson() ? new JsonResponse([], 204) : redirect(route("login_checker"));
        } elseif ($user->role == Users::ROLE_CLIENT_ADMIN) {
            $this->guard()->logout();
            $req->session()->invalidate();
            $req->session()->regenerateToken();
            if ($response = $this->loggedOut($req)) {
                return $response;
            }
            return $req->wantsJson() ? new JsonResponse([], 204) : redirect(route("login_client"));
        } elseif ($user->role == Users::ROLE_SPECIAL_TRACKING) {
            $this->guard()->logout();
            $req->session()->invalidate();
            $req->session()->regenerateToken();
            if ($response = $this->loggedOut($req)) {
                return $response;
            }
            return $req->wantsJson() ? new JsonResponse([], 204) : redirect(route("login_admin"));
        }
    }
}
