<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Branch;

class EnsureBranchAccess
{
    public function handle(Request $request, Closure $next, ...$roles): Response
    {
        $user = auth()->user();

        if (!$user) {
            return redirect('login');
        }

        if ($user->isAdmin()) {
            return $next($request);
        }

        if (!$user->branch_id) {
            return abort(403, app()->getLocale() == 'ar' ? 'لم يتم تعيين فرع لحسابك' : 'No branch assigned to your account');
        }

        if ($request->route('branch')) {
            $requestedBranch = $request->route('branch');
            if (is_numeric($requestedBranch)) {
                $requestedBranch = Branch::find($requestedBranch);
            }

            if ($requestedBranch && $requestedBranch->id != $user->branch_id) {
                return abort(403, app()->getLocale() == 'ar' ? 'ليس لديك صلاحية الوصول إلى هذا الفرع' : 'You do not have access to this branch');
            }
        }

        return $next($request);
    }
}
