<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;

class CompanyScope 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)
    {
        // Only apply the scope if user is authenticated
        if (Auth::check() && !is_null(Auth::user()->CompanyID)) {
            $table = $model->getTable();
            $column = in_array('CompanyID', $model->getFillable()) ? 'CompanyID' : 'company_id';
            $builder->where("$table.$column", Auth::user()->CompanyID);
        }
    }
}
