<?php

namespace Seka\Vzdelavanie\Models\Kniznica;

use Core\Http\Traits\Hashidable;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Seka\Vzdelavanie\Enums\ModelsTypeEnum;
use Seka\Vzdelavanie\Enums\ModelStatusEnum;
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 = [
        'autor',
        'nazov',
        'popis',
        'stav',
        'kategoria_id',
        'obrazok',
    ];

    /**
     * @var string[]
     */
    protected $appends = [
        'url',
        'hash_id',
    ];

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

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

    /**
     * @return string
     */
    public function getUrlAttribute(): string
    {
        return URL::route(
            'vzdelavanie.kniznica.ucebnica.show',
            $this,
        );
    }
}
