<?php

namespace App\Domain\Website\Models;

use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Shared\Traits\ManglesUniqueOnDelete;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class WebsitePage extends Model
{
    use Auditable, BelongsToAcademy, HasUuid, ManglesUniqueOnDelete, SoftDeletes;

    /** Frees the slug for reuse when a page is soft-deleted. */
    protected array $uniqueFieldsToMangle = ['slug'];

    protected array $mangleMaxLengths = ['slug' => 160];

    protected $fillable = [
        'academy_id',
        'slug',
        'title',
        'title_en',
        'meta_title',
        'meta_title_en',
        'meta_description',
        'meta_description_en',
        'og_image_path',
        'noindex',
        'layout',
        'is_homepage',
        'is_published',
        'published_at',
        'sort_order',
        'settings',
        'created_by',
    ];

    protected $casts = [
        'noindex' => 'boolean',
        'is_homepage' => 'boolean',
        'is_published' => 'boolean',
        'published_at' => 'datetime',
        'sort_order' => 'integer',
        'settings' => 'array',
    ];

    /** Top-level blocks only; nested children are loaded through the tree. */
    public function blocks(): HasMany
    {
        return $this->hasMany(WebsiteBlock::class)
            ->whereNull('parent_id')
            ->orderBy('sort_order');
    }

    public function allBlocks(): HasMany
    {
        return $this->hasMany(WebsiteBlock::class);
    }

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function localizedTitle(?string $locale = null): string
    {
        $locale ??= app()->getLocale();

        return $locale === 'ar'
            ? ($this->title ?: $this->title_en ?: $this->slug)
            : ($this->title_en ?: $this->title ?: $this->slug);
    }

    /**
     * The page's public URL in a given locale (the active one by default).
     *
     * Always locale-prefixed: an internal link must not drop the reader back
     * into whatever language their session happens to hold.
     */
    public function url(?string $locale = null): string
    {
        return website_url($this->is_homepage ? '' : $this->slug, $locale);
    }
}
