<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    // Show Login Form
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Process Login
    public function login(Request $request)
    {
        // 1. Validate Input
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        // 2. Attempt to Log In
        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            // 3. Redirect Logic
            // If they are an Admin, send to Admin Panel
            if (Auth::user()->hasRole('super_admin')) {
                return redirect()->intended('/admin');
            }

            // If they are a Client, send to Dashboard
            return redirect()->intended('/dashboard');
        }

        // 4. Login Failed
        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }
}
