<?php

namespace App\Models\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class SiteScope implements Scope
{
	/**
	 * Apply the scope to a given Eloquent query builder.
	 *
	 * @param  \Illuminate\Database\Eloquent\Builder  $builder
	 * @param  \Illuminate\Database\Eloquent\Model  $model
	 * @return void
	 */
	public function apply(Builder $builder, Model $model)
	{
		$builder->when(
			! collect($builder->getQuery()->wheres)->pluck('column')->contains(function($item) { return preg_match('/^(.*[^.]\.)?site_id/',$item); }),
			function($q) use ($model)
			{
				// @todo Remove this override "?? 1" it was put in place to retry failed AccountingPaymentSync
				return $q->where($model->getTable().'.site_id',config('site')->site_id ?? 1);
			}
		);
	}
}