<?php

namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Builder;

trait BelongsToCompany
{
    protected static function bootBelongsToCompany(): void
    {
        static::addGlobalScope('company', function (Builder $builder): void {
            if (! auth()->check()) {
                return;
            }

            $companyId = auth()->user()->company_id;
            if ($companyId) {
                $builder->where(
                    $builder->getModel()->getTable().'.company_id',
                    $companyId
                );
            }
        });

        static::creating(function ($model): void {
            if (auth()->check() && empty($model->company_id)) {
                $model->company_id = auth()->user()->company_id;
            }
        });
    }
}
