<?php

namespace App;

use App\Facades\General;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Config;

class TenantScope implements Scope
{

    protected $tenantCol = 'account_id';

    /**
     * @param Builder $builder
     * @param Model $model
     */
    public function apply(Builder $builder, Model $model)
    {
        if (!General::isSuperAdmin()){
            $builder->whereRaw($model->getTenantWhereClause($this->tenantCol, Config::get("account.id")));
        }
    }

    /**
     * @param Builder $builder
     * @param Model $model
     */
    public function remove(Builder $builder, Model $model)
    {
        $query = $builder->getQuery();
        foreach ((array)$query->wheres as $key => $where) {
            if ($this->isTenantConstraint($model, $where, $this->tenantCol, Config::get("account.id"))) {
                unset($query->wheres[$key]);
                $query->wheres = array_values($query->wheres);
                break;
            }
        }
    }

    /**
     * @param $model
     * @param array $where
     * @param $tenantColumn
     * @param $tenantId
     * @return bool
     */
    public function isTenantConstraint($model, array $where, $tenantColumn, $tenantId)
    {
        return $where['type'] == 'raw' && $where['sql'] == $model->getTenantWhereClause($tenantColumn, $tenantId);
    }

}
