<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;

class Page extends Model
{
    use HasFactory, HasTranslations;

    protected $fillable = [
        'parent_id',
        'title',
        'slug',
        'description',
        'content',
        'alternative_content',
        'meta_title',
        'meta_keywords',
        'meta_description',
        'status',
        'display_in_navigation',
        'ordernum',
    ];

    public $translatable = [
        'title',
        'slug',
        'description',
        'content',
        'alternative_content',
        'meta_title',
        'meta_keywords',
        'meta_description',
    ];

    public function parent()
    {
        return $this->belongsTo(Page::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Page::class, 'parent_id');
    }

    public function scopeSearch($query, $keyword)
    {
        return $query->where('title', 'like', '%' . $keyword . '%');
    }

    public function ancestors()
    {
        $ancestors = collect();

        $parent = $this->parent;
        while ($parent) {
            $ancestors->push($parent);
            $parent = $parent->parent;
        }

        return $ancestors->reverse();
    }

    public function images()
    {
        return $this->hasMany(PageImage::class);
    }

    public function getImageByTitle($title = null, $isSingle = true)
    {
        if ($title === null) {
            return $isSingle ? $this->images()->first() : $this->images()->get();
        }

        if ($isSingle) {
            return $this->images()->where('title', $title)->first();
        } else {
            return $this->images()->where('title', $title)->get();
        }
    }

}