<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait BranchScoped
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('branch', function (Builder $builder) {
            $user = auth()->user();

            if ($user instanceof \App\Models\User && !$user->isAdmin() && $user->branch_id) {
                $builder->where('branch_id', $user->branch_id);
            }
        });
    }

    public static function forBranch($branchId)
    {
        return static::where('branch_id', $branchId);
    }

    public static function allBranches()
    {
        return static::withoutGlobalScope('branch');
    }
}
