<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property mixed id
 * @property mixed currentDescription
 * @property mixed slug_text
 */
class Supplier extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'image',
    ];


    /**
     * Return current descriptions of supplier
     * @return HasOne
     */
    public function currentDescription() : HasOne
    {
        return $this->hasOne(SupplierDescription::class)->where('language_id', currentLanguage()->id);
    }

    /**
     * Return descriptions for supplier
     * @return HasMany
     */
    public function descriptions() : HasMany
    {
        return $this->hasMany(SupplierDescription::class);
    }

    public static function withDescription($supplierId = null)
    {
        $query = self::join('supplier_descriptions as ad', 'ad.supplier_id', 'suppliers.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['suppliers.created_at', 'ad.*']);
        if ($supplierId){
           $query->where('suppliers.id', $supplierId);
        }

        $query->select([
            'suppliers.id',
            'suppliers.image',
            'ad.name',
            'ad.description',
        ]);

        return $supplierId ? $query->first() : ($query->cursor() ?? []);
    }

    /**
     * Return Slug of supplier
     * @return string|null
     */
    public function getSlugTextAttribute() : ?string
    {
        return str_slug(strtolower($this->currentDescription->slug));
    }

}
