<?php

namespace App\Http\Controllers\Web\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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 = '/platform/dashboard';

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

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'username';
    }

    protected function redirectTo()
    {
        $user = request()->user();

        if (! $user) {
            return '/platform/login';
        }

        return '/platform/system-assistant/notes-reminders';
    }

    protected function authenticated(Request $request, $user)
    {
        if ($user && ! $user->is_admin) {
            $user->loadMissing('employee', 'roles');
            $roleId = (int) ($user->employee?->role_id ?? 0);

            if ($roleId > 0 && ! $user->roles->contains('id', $roleId)) {
                $user->roles()->sync([$roleId]);
            }

            if ($user->employee && ! (bool) ($user->employee->is_active ?? true)) {
                Auth::logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();

                $message = app()->getLocale() === 'ar'
                    ? 'حساب الموظف موقوف.'
                    : 'Employee account is disabled.';

                return redirect()->route('login')->withErrors(['username' => $message]);
            }
        }

        $request->session()->flash('show_important_news_popup', true);
        $request->session()->forget('url.intended');

        if ($user && (string) ($user->two_factor_pending_secret ?? '') !== '') {
            $request->session()->put('two_factor_user_id', $user->id);
            Auth::logout();

            return redirect()->route('two-factor.setup');
        }

        if ($user && (bool) ($user->two_factor_enabled ?? false) && (string) ($user->two_factor_secret ?? '') !== '') {
            $request->session()->put('two_factor_user_id', $user->id);
            Auth::logout();

            return redirect()->route('two-factor.challenge');
        }

        return redirect()->to($this->redirectTo());
    }

    protected function loggedOut(Request $request)
    {
        return redirect()->route('login');
    }
}
