<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Middleware\SetLocale;
use App\Support\AuthenticatedRedirect;
use App\Support\PortalSession;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Kimlik bilgilerini ve customer rolünü doğrulayıp müşteri oturumunu güvenle başlatır.
     *
     * @param  Request  $request  Müşteri giriş formu ve oturum bilgileri.
     * @param  AuthenticatedRedirect  $redirect  Güvenli müşteri yönlendirmesini belirleyen yardımcı.
     * @return RedirectResponse Güvenli intended adresine veya müşteri paneline yönlendirme.
     *
     * @author Gökhan Engin - İletişim : https://bit.ly/YazılımUzmanı
     */
    public function store(Request $request, AuthenticatedRedirect $redirect): RedirectResponse
    {
        $credentials = $request->validate(['email' => ['required', 'email'], 'password' => ['required', 'string']]);
        $key = Str::transliterate(Str::lower($credentials['email']).'|'.$request->ip());
        if (RateLimiter::tooManyAttempts($key, 5)) {
            throw ValidationException::withMessages(['email' => __('ui.errors.throttle')]);
        }
        if (! Auth::attempt([...$credentials, 'status' => 'active'], $request->boolean('remember'))) {
            RateLimiter::hit($key, 60);
            throw ValidationException::withMessages(['email' => __('ui.errors.credentials')]);
        }
        if (! Auth::user()->canAccessCustomerPortal()) {
            RateLimiter::hit($key, 60);
            app(PortalSession::class)->terminate($request);
            throw ValidationException::withMessages(['email' => __('auth.portal_denied')]);
        }
        RateLimiter::clear($key);
        $request->session()->regenerate();
        if (! in_array(Auth::user()->locale, SetLocale::SUPPORTED, true)) {
            Auth::user()->forceFill(['locale' => $request->session()->get('locale', 'tr')])->save();
        }

        return redirect()->to($redirect->intended($request) ?? $redirect->landing());
    }

    public function destroy(Request $request, PortalSession $sessions): RedirectResponse
    {
        $sessions->terminate($request);

        return redirect()->route('home');
    }
}
