<?php

namespace App\Models\Admin;

use App\Models\Image;
use App\Models\ImageSetting;
use App\Traits\HasFiles;
use App\Traits\HasSortsTrait;
use App\Traits\ImagenesGetterTrait;
use Doctrine\DBAL\Query\QueryBuilder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Type\Integer;

class Interna extends Model
{
    use HasFactory, HasSortsTrait, ImagenesGetterTrait, HasFiles;
    protected $table = 'internas';

    protected $fillable = [
        'titulo',
        'slug',
        'grupo_interna_id',
        'admin_id',
        'borrador',
        'descripcion',
        'estado',
        'orden',
        'operadores'
    ];


    protected $appends = [
        'image_small',
        'image_large',
    ];

    protected $casts = [
        'created_at' => 'datetime:d-m-Y H:i',
        'updated_at' => 'datetime:d-m-Y H:i',
    ];

    protected string $imageThumbSize = 'medium';

    public function enlace()
    {
        //grupo_interna_id
        $grupo = DB::table('grupos_internas')
            ->where('id', $this->grupo_interna_id)
            ->first();

        return asset("/interna/{$grupo->slug}/{$this->id}/{$this->slug}");
    }

    public function scopeNoBorrador($query)
    {
        $query->where('borrador', false);
    }

    public function setTituloAttribute($value)
    {
        $this->attributes['titulo'] = ucfirst(trim($value));
        $slug = str_slug(trim($value));
        $this->attributes['slug'] = $this->validateSlug($slug, $this->id);
    }

    private function validateSlug($slug, $id = null)
    {
        $val = Interna::where('slug', $slug)
            ->first();

        if ($val && $id && $val->id === $id)
            return $slug;

        if (!!$val)
            return $this->validateSlug(str_slug($slug . '1'));

        return $slug;
    }

    public function scopeModulo($query, int $id)
    {
        return $query->where('grupo_interna_id', $id);
    }

    public function scopeUserBorradores($query)
    {
        $user =  auth()->user();
        $user_id = $user->id;

        //Si es root mostrar todos

        //Si no es root mostrar solo sus borradores
        return $query->where(function ($q) use ($user_id) {
            $q->where('borrador', 1)
                ->where('admin_id', $user_id);
        })->orWhere(function ($q) use ($user_id) {
            $q->where('borrador', 0);
        });
    }

    public function scopeFirstBorradores($query)
    {
        //Mostrar primero los que son borradores
        return $query;
    }

    public function secciones()
    {
        return $this->HasMany(Secciones::class)->ordenar()
            ->selectFillableAnd(['id as image_large_getter']);
    }

    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }

    public function setImageThumbSize($size)
    {
        $this->imageThumbSize = $size;
    }
}
