<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\DaUser;

class RegisterController extends Controller
{
    public function showRegistrationForm()
    {
        return view('registret_kontu');
    }

    public function showLoginForm()
    {
        return view('autentificet');
    }

    public function processRegistration(Request $request)
    {
        $request->validate([
            'lietotajvards' => 'required|string|max:20',
            'epasts' => 'required|email|unique:da_users,email',
            'parole' => 'required|string|min:8|max:20',
        ]);

        $user = DaUser::create([
            'username' => $request->lietotajvards,
            'email' => $request->epasts,
            'password' => substr(Hash::make($request->parole), 0, 20),
        ]);

        if ($user) {
            return redirect('/')->with('success', 'Konts izveidots veiksmīgi! Lūdzu, pieteikties.');
        } else {
            return back()->withInput()->with('error', 'Kļūda, mēģiniet vēlreiz!');
        }
    }

    public function authenticate(Request $request)
    {
        $request->validate([
            'email'=>'required|email',
            'password'=>'required|min:8|max:20'
        ]);

        $user = DaUser::where('email', '=', $request->email)->first();

        if ($user) {
            if (Hash::check($request->password, $user->password)) {
                $request->session()->put('loginId', $user->id);
                return redirect()->route('lietotaja_interfeiss'); 
            } else {
                return back()->with('fail', 'Parole nav pareiza');
            }
        } else {
            return back()->with('fail', 'Lietotājs nav atrasts');
        }
    }

    public function showUserInterface()
    {
        return view('lietotaja_interfeiss');
    }

    public function logout()
    {
        Auth::logout();
        return redirect('/');
    }
}
