<?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\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Auth;
use Seka\Portal\Modul\Vzdelavanie\Enums\ModelStatusEnum;
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 Ucebnica
 *
 * @package Seka\Portal\Modul\Vzdelavanie\Models\Kniznica
 */
class Ucebnica extends Model
{
    use Hashidable;
    use HasFactory;

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

    /**
     * @var array
     */
    protected $fillable = [
        'id',
        'autor',
        'nazov',
        'popis',
        'stav',
        'kategoria_id',
        'obrazok',
    ];

    /**
     * @var string[]
     */
    protected $casts = [
        'stav' => ModelStatusEnum::class,
    ];

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

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

        static::deleting(function (Ucebnica $ucebnica) {
            $ucebnica->sekcie->each->delete();
            $ucebnica->oblubene->each->delete();
            $ucebnica->popularita->each->delete();
        });
    }

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

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function sekcie(): HasMany
    {
        return $this->hasMany(Sekcia::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 int
     */
    public function getPopularitaCountAttribute(): int
    {
        return $this->popularita()->count();
    }

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