<?php

namespace Seka\Portal\Modul\Vzdelavanie\Models\Kniznica;

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

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

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

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

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

    protected static function boot(): void
    {
        parent::boot();

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

    public function ucebnica(): BelongsTo
    {
        return $this->belongsTo(Ucebnica::class, 'ucebnica_id', 'id');
    }

    public function oblubene(): MorphMany
    {
        return $this
            ->morphMany(Oblubene::class, 'oblubene')
            ->where('pouzivatel_id', Auth::id())
            ->limit(1);
    }

    public function popularita(): MorphMany
    {
        return $this->morphMany(Popularita::class, 'popularita');
    }

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

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

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