<?php

namespace App\Http\Controllers;

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

class LoginController extends Controller
{
    public function showLogin() {
        return view('Login');
    }

    public function login(Request $request)
{
    $credentials = $request->only('usernameOrEmail', 'password');

    $userByUsername = User::where('Username', $credentials['usernameOrEmail'])->first();
    $userByEmail = User::where('Email', $credentials['usernameOrEmail'])->first();

    if (!$userByUsername && !$userByEmail) {
        return back()->withErrors(['error' => 'No user found with these details.']);
    }

    if ($userByUsername) {
        if (Hash::check($credentials['password'], $userByUsername->Password)) {
            Auth::login($userByUsername);
            session(['logged_in' => true]);  // Store session data
            return redirect()->intended('profile');
        } else {
            return back()->withErrors(['error' => 'Password does not match for username.']);
        }
    } 

    if ($userByEmail) {
        if (Hash::check($credentials['password'], $userByEmail->Password)) {
            Auth::login($userByEmail);
            session(['logged_in' => true]);  // Store session data
            return redirect()->intended('profile');
        } else {
            return back()->withErrors(['error' => 'Password does not match for email.']);
        }
    }
}

public function logout() {
    Auth::logout();
    session()->forget('logged_in');  // Remove the session data
    return redirect()->route('home');
}

}
?>