<?php

namespace App\Http\Controllers\UyelerAuth;

use App\Http\Controllers\Controller;
use App\Http\Requests\UyelerAuth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('tema.uye.login');
    }

    /**
     * Handle an incoming authentication request.
     *
     * @param  \App\Http\Requests\Auth\LoginRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(LoginRequest $request)
    {

        $field = filter_var($request->input('username_or_email'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        $credentials = [
            $field => $request->input('username_or_email'),
            'password' => $request->input('password'),
        ];

        if (Auth::guard('uye')->attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended(RouteServiceProvider::USER_HOME);
        }


        throw ValidationException::withMessages([
            'username_or_email' => ['Kullanıcı adı, e-posta veya şifre hatalı.'],
        ]);


    }

    /**
     * Destroy an authenticated session.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request)
    {
        Auth::guard('uye')->logout();

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

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

        return redirect('uye/login');
    }
}
