<?php

namespace Seka\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\Vzdelavanie\Enums\ModelsTypeEnum;
use Seka\Vzdelavanie\Models\Popularita\Popularita;
use Seka\Vzdelavanie\Models\Pouzivatel\Kniznica\Oblubene;

/**
 * Class Sekcia
 *
 * @package Seka\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',
    ];

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

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

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

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function ucebnica(): BelongsTo
    {
        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');
    }

    /**
     * @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',
        ];
    }
}
