<?php

namespace App\Http\Middleware;

use App\Models\ProductOrganisation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Interfaces\OrganisationRepositoryInterface;


class CheckOrgActiveForPayroll
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    private OrganisationRepositoryInterface $orgRepository;

    public function __construct(OrganisationRepositoryInterface $orgRepository)
    {
        $this->orgRepository = $orgRepository;
    }

    public function handle($request, Closure $next)
    {
        $organisationId = $request->user()->organisation_id;
        $userRole = $request->user()->user_type;

        // Check if the organisation is active for the payroll product
        $orgProduct = ProductOrganisation::where('product_id', 1)->where('organisation_id', $organisationId)->first();

        if (!$orgProduct || !$orgProduct->is_active) {
            if ($userRole === 'employee') {
                return response()->json([
                    'status' => 'success',
                    'message' => 'No access',
                    'redirectUrl' => '/no-access'
                ], 433);
            } else {
                return response()->json([
                    'status' => 'success',
                    'message' => 'No access',
                    'redirectUrl' => '/all-products/no-access'
                ], 433);
            }
        }
        // If active, proceed with the request
        return $next($request);
    }
}
