<?php

namespace Daylight\Core\Models;

use Daylight\Core\Models\Enums\PublishStatus;
use Daylight\Core\Modules\Multilingualism\Contracts\HasTranslations;
use Daylight\Core\Modules\Multilingualism\Models\Concerns\InteractsWithTranslations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;

class Page extends Model implements HasTranslations
{
    use HasRecursiveRelationships;
    use InteractsWithTranslations;

    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'status' => PublishStatus::class,
        ];
    }

    protected static function booted(): void
    {
        static::saved(function (Page $page) {
            if ($page->wasChanged('parent_id')) {
                $page->load('translations');
                foreach ($page->translations as $translation) {
                    $translation->updateNestedSlug();
                    $translation->saveQuietly();
                    $translation->updateDescendantNestedSlugs();
                }
            }
        });
    }

    public function translatedFields(): array
    {
        return ['name', 'slug', 'meta_title', 'meta_description', 'robots'];
    }

    public function parent(): BelongsTo
    {
        return $this->belongsTo(daylightModel('page'), 'parent_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(daylightModel('page'), 'parent_id');
    }

    public function translations(): HasMany
    {
        return $this->hasMany(daylightModel('page_translation'));
    }

    public function defaultTranslation(): HasOne
    {
        return $this
            ->hasOne(daylightModel('page_translation'))
            ->where('locale', config('multilingualism.default_locale'));
    }
}
