<?php

namespace App;

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

/**
 * Class Product
 * @property mixed id
 * @property mixed is_special
 * @package App
 * @mixin Builder
 */
class Product extends Model
{
    use SoftDeletes;
    protected $fillable = ['is_special', 'show_advantages', 'show_table', 'images', 'points'];

    protected $casts = [
        'images' => 'array',
        'points' => 'array',
    ];

    public function currentDescription() : HasOne
    {
        return $this->hasOne(ProductDescription::class)->where('language_id', currentLanguage()->id);
    }

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

    public static function withDescription($ids = [], $limit = null, $isSpecial = [1])
    {
        $query = self::orderByDesc('products.id')
            ->whereIn('products.is_special', $isSpecial)
            ->join('product_descriptions as pDesc', 'pDesc.product_id', 'products.id')
            ->where('pDesc.language_id', currentLanguage()->id)
            ->select([
                'products.id',
                'products.show_advantages',
                'products.show_table',
                'products.images',
                'products.points',
                'pDesc.name',
                'pDesc.description',
                'pDesc.advantages',
                'pDesc.advantage_desc',
                'pDesc.minimum_title',
                'pDesc.maximum_title',
                ]);

        if (count($ids) > 1){
            $query->whereIn('products.id', $ids);
        }

        if (count($ids) == 1){
            $query->where('products.id', $ids);
        }

        if ($limit){
            $query->limit($limit);
        }

        return count($ids) == 1 ? $query->first() : $query->get() ?? [];
    }

}
