<?php
/**
 * Scope Class
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Scopes
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025, 2026 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */

namespace BplanBase\Globals\Scopes;


use BplanBase\Globals\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;


/**
 * Scope Class
 *
 * @version     1.2.0 / 2026-02-17
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
class TenantScope implements Scope
{


/* +++ TRAITS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS CONSTANTS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT MEMBERS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ CLASS MEMBERS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


/* +++ OBJECT METHODS +++ +++++++++++++++++++++++++++++++++++++++++++++++++++ */


    /**
     * Apply the scope to a given Eloquent query builder
     *
     * @param       Builder $Builder
     *
     * @param       Model $Model
     *
     * @version     1.2.0 / 2026-02-17
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function apply(Builder $Builder, Model $Model): void
    {
        $Tenant = Tenant::current();

        if ($Tenant !== null) {
            $Builder->where($Model->getTable().'.tenant_id', $Tenant->id);
        }
    } // apply()


    /**
     * Extend the query builder with functions to ignore the tenant scope.
     *
     * @param       Builder $Builder
     *
     * @version     1.0.0 / 2026-02-17
     * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
     * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
     */
    public function extend(Builder $Builder): void
    {
        $Builder->macro('withoutTenancy', function (Builder $Builder) {
            return $Builder->withoutGlobalScope($this);
        });
    } // extend()


/* +++ CLASS METHODS +++ ++++++++++++++++++++++++++++++++++++++++++++++++++++ */


} // class TenantScope implements Scope {}
