<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Livewire\Livewire;
use Symfony\Component\HttpFoundation\Response;

class LivewireUserCan {
	/**
	 * Handle an incoming request.
	 *
	 * @param Request $request
	 * @param Closure(Request): (Response) $next
	 *
	 * @return Response
	 */
	public function handle( Request $request, Closure $next ): Response {
		if ( $request->route()->getName() == 'livewire.upload-file' && \Config::get( 'app.is_demo', false ) ) {
			abort( 403, __( 'This action is disabled in the demo!' ) );
		}

		if ( ! isset( $request->fingerprint['name'] ) && $request->route()->getName() != 'livewire.upload-file' ) {
			abort( 403, __( 'Access denied' ) );
		}

		$excluded = [ 'auth.login', 'auth.forgot-password' ];
		if ( isset( $request->fingerprint['name'] ) && ! in_array( $request->fingerprint['name'], $excluded ) && ! can( $request->fingerprint['name'] ) ) {
			abort( 403, __( 'Access denied' ) );
		}

		return $next( $request );
	}
}
