<?php

namespace App\Models\Publications;

use App\Models\Asset;
use App\Models\Pages\Page;
use App\Models\User;
use App\Support\HasObjectsTrait;
use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;

class Publication extends Model {
    use UuidScopeTrait, SoftDeletes, HasObjectsTrait, RelationValuesTrait;

    protected $dates = [
        'published_at'
    ];

    protected $fillable = [
        'uuid',
        'page_id',
        'poster_id',
        'author_id',
        'slug',
        'type',
        'name',
        'excerpt',
        'params',
        'published_at',
        'is_published',
    ];

    protected $hidden = [
        'id'
    ];


    public function page(): BelongsTo {
        return $this->belongsTo(Page::class);
    }

    public function poster(): BelongsTo {
        return $this->belongsTo(Asset::class);
    }

    public function author(): BelongsTo {
        return $this->belongsTo(User::class);
    }

    public function sections(): MorphToMany {
        return $this->objects()->wherePivot('group', '=', 'sections');
    }

    public function sidebars(): MorphToMany {
        return $this->objects()->wherePivot('group', '=', 'sidebars');
    }


    public function scopeBySlug($query, $slug) {
        $query->where(['slug' => $slug]);
    }


    public function getLinkAttribute(): string {
        return ($this->page->link ?? '') . "/{$this->slug}";
    }

    public function getParentsAttribute(): Collection {
        $page = $this->page;
        $result = collect([$page]);
        while ($page = $page->parent) $result->push($page);
        return $result;
    }

    public function getParsedTypeAttribute(): array {
        return ['name' => $this->type, 'title' => PublicationType::TITLES[$this->type] ?? null];
    }

    public function getParsedParamsAttribute() {
        return json_decode($this->params);
    }



    public function addSection($typeName, $ord = null): ?Model {
        return $this->createObject($typeName, $ord, 'sections');
    }

    public function addSidebar($typeName = 'page-sidebar', $ord = null): ?Model {
        return $this->createObject($typeName, $ord, 'sidebars');
    }


    public static function byUrl($url) {
        if ($url = trim($url, '/ ')) {
            $slugs = explode('/', $url);
            $publicationSlug = array_pop($slugs);
            $pageUrl = implode('/', $slugs);
            if ($pageUrl) {
                return ($page = Page::byUrl($pageUrl)) ? $page->publications()->bySlug($publicationSlug)->first() : null;
            } else return self::bySlug($publicationSlug)->first();
        }
        return null;
    }

}
