<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\DaUser; // Adjust the namespace as per your User model

class LoginController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        // Validate the request data
        $credentials = $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);

        // Retrieve the user by email
        $user = DaUser::where('email', $credentials['email'])->first();

        // Check if user exists and if password matches
        if ($user && Hash::check($credentials['password'], $user->password)) {
            // Password matches, log in the user
            Auth::login($user);
            return redirect()->route('lietotaja_interfeiss');
        } else {
            // Authentication failed
            return redirect()->route('login')->with('error', 'These credentials do not match our records.');
        }
    }

    public function logout(Request $request)
    {
        Auth::logout();
        return redirect()->route('welcome');
    }
}
