<?php

namespace App\Traits;

use App\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

trait Multitenantable
{
    public static function bootMultitenantable()
    {
        // Otomatis isi tenant_id saat pembuatan data baru
        static::creating(function ($model) {
            if (Auth::check()) {
                if(!$model instanceof Tenant) {
                    $model->tenant_id =Auth::user()->tenant_id;
                }
            }
        });

        // Global Scope: Otomatis filter setiap query (select, update, delete)
        static::addGlobalScope('tenant_id', function (Builder $builder) {
            $tenantId = Auth::check() ?Auth::user()->tenant_id : config('app.current_tenant_id');

            if($tenantId && !(static::class === Tenant::class)) {
                $builder->where($builder->getModel()->getTable() .'.tenant_id', $tenantId);
            }
        });
    }
}
