<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\UserManagement\Admin;
use App\Services\ImageService;
use App\Traits\ImageUploadTrait;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AdminAuthController extends Controller{
    use ImageUploadTrait;
    use AuthenticatesUsers {
        logout as protected originalLogout;
        login as protected originalLogin;
    }


    const GUARD = "admin";

    public function login() : View{
        return view('backend.login');
    }

    public function loginForm(){
        return view('backend.login');
    }

    public function forgotPassword(): View{
        return view('backend.forgot-password');
    }

    public function accountSetting(): View{
        return view('backend.account_setting');
    }


    public function connexion(Request $request){

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        $credentials = $request->only(['loginId',"password",'remember']);
        $remember = $request->remember ?? true;

        $loginId = $credentials['loginId'];

        $user = Admin::where('email',$loginId)
                    ->orWhere('username',$loginId)
                    ->orWhere('phone',$loginId)
                    ->first();

//        dd($guard,$user);

        //si l'user n'exite pas
        if (!$user) {
            throw ValidationException::withMessages([
                'loginId' => [__("Incorrect email, username or phone")],
            ]);
        }
        if (!Hash::check($credentials['password'], $user->password)){
            throw ValidationException::withMessages([
                'password' => [__("Incorrect password")],
            ]);
        }

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        Auth::guard(self::GUARD)->login($user,$remember);

        if ($request->hasSession()) {
            $request->session()->put('auth.password_confirmed_at', time());
        }
        return $this->sendLoginResponse($request);
    }

    public function redirectTo(){
        return $this->redirectTo =  route("admin.index");
    }

    public function logout(Request $request){

        $user = auth()->user();

        $redirect =  route("admin.auth.login");

        /* Call Original Logout Method */
        $response = $this->originalLogout($request);

        if ($request->ajax()){
            return response()->json([
                "success" => true,
                "redirect" => $redirect,
                "message" => __("You are now logged-out"),
            ]);
        }
        return redirect($redirect)->with([
            "message" => __("You are now logged-out"),
            "alert-type" => "success",
        ]);

        /* Repopulate Original Response  */
        // return $response;
    }

    public function updateAccount(Request $request): RedirectResponse{
        $user = auth(activeGuard())->user();

        if ($request->password){
            $password = bcrypt($request->password);
        }

        $user->update([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'username' => $request->username,
            'email' => $request->email,
            'phone' => $request->phone,
            'active' => $request->active,
         //   'user_image' => $adminImage ?? auth(activeGuard())->user()->user_image,
            'password' => $password ?? auth()->user()->password
        ]);

        if ($request->hasFile('user_image')) {
            $user->uploadFiles([$request->user_image],['width' => 150, "height" => 100]);
        }


        return redirect()->route('admin.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }
}
