<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Pagina extends Model
{
    protected $table = 'paginas';

    protected $fillable = ['titulo', 'slug', 'contenido', 'meta_descripcion', 'activo', 'orden'];

    protected $casts = [
        'activo' => 'boolean',
    ];

    public function scopeActivas($query)
    {
        return $query->where('activo', true)->orderBy('orden');
    }

    /**
     * Genera un slug único a partir del título.
     */
    public static function generarSlug(string $titulo, ?int $excludeId = null): string
    {
        $slug = Str::slug($titulo);
        $original = $slug;
        $i = 1;

        while (true) {
            $query = static::where('slug', $slug);
            if ($excludeId) {
                $query->where('id', '!=', $excludeId);
            }
            if (!$query->exists()) break;
            $slug = $original . '-' . $i++;
        }

        return $slug;
    }
}
