<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Auth;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->renderable(function (TokenMismatchException $e, $request) {
            // Handle CSRF token mismatch specifically for logout route
            // Check the request path directly since route might not be resolved when exception occurs
            if ($request->path() === 'logout' || $request->is('logout')) {
                // Log out the user and invalidate session
                Auth::guard('web')->logout();
                $request->session()->invalidate();
                $request->session()->regenerateToken();

                // Redirect to login with success message
                return redirect()->route('login')
                    ->with('status', 'You have been successfully logged out.');
            }

            // For other routes, let the parent handle the exception
            return parent::render($e, $request);
        });
    }
}