<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class CustomLoginController extends Controller // Change the class name
{
    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        // Validate the incoming request
        $this->validate($request, [

            'name' => 'required',

            'password' => 'required',

        ]);

        // Get the user by email
        $user = User::where('uname', $request->name)->first();

        // Check if user exists and if the provided password matches
        if ($user && $user->password === $request->password) {
            // Log the user in
            Auth::login($user);
            // Redirect to the intended page
            return redirect()->intended('/home');
        }

        // If authentication fails, redirect back with errors
        return redirect()->back()->withErrors(['email' => 'Invalid credentials']);
    }
    public function logout(Request $request)
    {
        Auth::logout();

        // Redirect to the login page after logout
        return redirect('/login');
    }
}
