<?php

namespace App\Models;

use App\Exceptions\ValidationException;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use OwenIt\Auditing\Auditable;
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;

class Feriado extends Model implements AuditableContract
{
    use SoftDeletes;
    use Auditable;

    protected $guarded = [];
    protected $appends = ['url'];

    public function scopeSearch($query, $inicio, $fim)
    {
        $inicio = Carbon::create($inicio);
        $fim = Carbon::create($fim);

        return $query->where('data_inicio', '>=', $inicio)
                     ->where('data_fim', '<=', $fim);
    }

    public function existeNoAno()
    {
        $ano = $this->attributes['data_inicio']->year;
        $feriado = self
                ::where('titulo', 'ILIKE', $this->titulo)
                ->whereYear('data_inicio', $ano)
                ->first();
        
        if ($this->id && $feriado) {
            return $this->id != $feriado->id;
        }

        return (bool) $feriado;
    }

    public function scopeFormatted($query)
    {
        return $query->select(
            'titulo as title',
            'data_inicio as start',
            'data_fim as end',
            'id'
        );
    }

    public function setDataInicioAttribute($data)
    {
        $this->attributes['data_inicio'] = Carbon::createFromFormat('d/m/Y', $data);
    }

    public function setDataFimAttribute($data)
    {
        $this->attributes['data_fim'] = Carbon::createFromFormat('d/m/Y', $data);
    }

    public function getUrlAttribute()
    {
        return route('admin.feriados.edit', ['feriado' => $this]);
    }

    public function getDataInicioAttribute()
    {
        return Carbon::create($this->attributes['data_inicio'])->format('d/m/Y');
    }

    public function getDataFimAttribute()
    {
        return Carbon::create($this->attributes['data_fim'])->format('d/m/Y');
    }

    public function getDataInicioFimAttribute()
    {
        return $this->data_inicio . ' - ' . $this->data_fim;
    }

    public static function eFeriado(Carbon $inicio, Carbon $fim = null)
    {
        $fim = $fim ?? $inicio;
        
        return self::where('data_inicio', '<=', $inicio)
                   ->where('data_fim', '>=', $fim)
                   ->get()
                   ->isNotEmpty();
    }
}
