<?php

namespace Seka\Vzdelavanie\Models\Kniznica;

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

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

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

    /**
     *
     */
    protected static function boot()
    {
        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 \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_UCEBNY_MATERIAL()->value;
    }

    /**
     * @return int
     */
    public function getPopularitaCountAttribute(): int
    {
        return (int) $this->popularita()->count();
    }
}
