<?php

namespace Seka\Vzdelavanie\Models\Kniznica;

use Kalnoy\Nestedset\NodeTrait;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Seka\Vzdelavanie\Models\Pouzivatel\Kniznica\Oblubene;
use Seka\Vzdelavanie\Models\Pouzivatel\Kniznica\OblubeneModelTypeEnum;

/**
 * Class Sekcia
 * @package Seka\Vzdelavanie\Models\Kniznica
 */
class Sekcia extends Model
{
    use NodeTrait;

    /**
     * @var string
     */
    protected $table = 'vzdelavanie_kniznica_sekcie';

    /**
     * @var array
     */
    protected $fillable = [
        'nazov',
        'obsah',
        'parent_id',
        'ucebnica_id',
    ];

    /**
     * @var string[]
     */
    protected $appends = [
        'url',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function ucebnica()
    {
        return $this->belongsTo(Ucebnica::class, 'ucebnica_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function oblubene(): MorphMany
    {
        return $this->morphMany(Oblubene::class, 'oblubene')
            ->where('pouzivatel_id', Auth::id())
            ->limit(1);
    }

    /**
     * @return string
     */
    public static function type(): string
    {
        return OblubeneModelTypeEnum::MODEL_TYPE_SEKCIA();
    }

    /**
     * @return array
     */
    protected function getScopeAttributes(): array
    {
        return [
            'ucebnica_id',
        ];
    }

    /**
     * @param       $query
     * @param mixed ...$columns
     *
     * @return mixed
     */
    public function scopeExclude($query, ...$columns)
    {
        return $query->select(
            array_diff(
                $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable()),
                $columns
            )
        );
    }

    /**
     * @return string|null
     */
    public function getUrlAttribute()
    {
        if (! $this->getKey()) return null;

        return URL::route(
            'vzdelavanie.kniznica.ucebnica.sekcia.show',
            [
                'id' => $this->getAttribute('ucebnica_id'),
                'sekciaId' => $this->getKey(),
            ]
        );
    }

    /**
     * @param string      $childType
     * @param mixed       $value
     * @param string|null $field
     *
     * @return \Illuminate\Database\Eloquent\Model|void|null
     */
    public function resolveChildRouteBinding($childType, $value, $field)
    {
        // TODO: Implement resolveChildRouteBinding() method.
    }
}
