<?php

namespace App\Models;

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

class Escola extends Model
{
    protected $casts = [
        'endereco' => 'array',
    ];

    protected $fillable = [
        'cnpj',
        'endereco',
        'nome',
    ];

    /*
    |--------------------------------------------------------------------------
    | GLOBAL SCOPE MULTI-TENANT
    |--------------------------------------------------------------------------
    */

    protected static function booted()
    {
        static::addGlobalScope('user_escolas', function (Builder $builder) {

            if (Auth::check() && !Auth::user()->is_super_admin) {

                $builder->whereIn('id', function ($query) {

                    $query->select('escola_id')
                        ->from('user_escolas')
                        ->where('user_id', Auth::id());

                });

            }

        });
    }

    /*
    |--------------------------------------------------------------------------
    | RELACIONAMENTOS
    |--------------------------------------------------------------------------
    */

    public function turmas()
    {
        return $this->hasMany(Turma::class, 'id_escola');
    }

    public function users()
    {
        return $this->belongsToMany(
            User::class,
            'user_escolas',
            'escola_id',
            'user_id'
        );
    }
}
