<?php

namespace Seka\Vzdelavanie\Models\Kniznica;

use Kalnoy\Nestedset\NodeTrait;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Seka\Vzdelavanie\Enums\ModelsTypeEnum;
use Elceka\Laravel\HashId\Http\Traits\Hashidable;
use Seka\Vzdelavanie\Models\Popularita\Popularita;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Seka\Vzdelavanie\Models\Pouzivatel\Kniznica\Oblubene;

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

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

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

    /**
     *
     */
    protected static function boot()
    {
        parent::boot();

        static::deleting(function (Sekcia $sekcia) {
            $sekcia->oblubene->each->delete();
            $sekcia->popularita->each->delete();
        });
    }

    /**
     * @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 \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function popularita(): MorphMany
    {
        return $this->morphMany(Popularita::class, 'popularita');
    }

    /**
     * @return string
     */
    public static function type(): string
    {
        return ModelsTypeEnum::MODEL_TYPE_KNIZNICA_SEKCIA()->value;
    }

    /**
     * @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
            )
        );
    }

    /**
     * @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.
    }
}
