<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DynamicPage extends Model
{
    protected $fillable = [
        'title',
        'slug',
        'content',
        'meta_title',
        'meta_description',
        'show_in_header',
        'show_in_footer',
        'is_active',
        'sort_order',
        'created_by',
    ];

    protected $casts = [
        'show_in_header' => 'boolean',
        'show_in_footer' => 'boolean',
        'is_active' => 'boolean',
        'sort_order' => 'integer',
    ];

    /**
     * Get the creator of the page.
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get active pages for header.
     */
    public static function getHeaderPages()
    {
        return self::where('is_active', true)
            ->where('show_in_header', true)
            ->orderBy('sort_order')
            ->get(['id', 'title', 'slug']);
    }

    /**
     * Get active pages for footer.
     */
    public static function getFooterPages()
    {
        return self::where('is_active', true)
            ->where('show_in_footer', true)
            ->orderBy('sort_order')
            ->get(['id', 'title', 'slug']);
    }

    /**
     * Get all active pages.
     */
    public static function getActive()
    {
        return self::where('is_active', true)
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * Generate unique slug.
     */
    public static function generateSlug(string $title, ?int $excludeId = null): string
    {
        $slug = \Illuminate\Support\Str::slug($title);
        $originalSlug = $slug;
        $count = 1;

        $query = self::where('slug', $slug);
        if ($excludeId) {
            $query->where('id', '!=', $excludeId);
        }

        while ($query->exists()) {
            $slug = "{$originalSlug}-{$count}";
            $count++;
            $query = self::where('slug', $slug);
            if ($excludeId) {
                $query->where('id', '!=', $excludeId);
            }
        }

        return $slug;
    }
}
