<?php

namespace App\Models;

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

class Product extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = [
        'image','children','adult','category_id'
    ];

    public function category()
    {
        return $this->belongsTo(Category::class)->withTrashed();
    }

    public function feature() :hasMany
    {
        return $this->hasMany(ProductFeature::class);
    }
    public function featureSample()
    {
        $features = ProductFeature::where('product_id',$this->id)->take(5)->get();
        return $features;
        return $this->hasMany(ProductFeature::class,'product_id')->take(5);
    }

    public function descriptions($language_id= null)
    {

        if ($language_id) {
            $data = $this->hasMany(ProductDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(ProductDescription::class)->first();
            }

            return $data;
        }
        $data = $this->hasMany(ProductDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }

    public function photos() :hasMany
    {
        return $this->hasMany(ProductPhoto::class);
    }

    public static function withDescription($product_id = null)
    {
        $query = self::query()
            ->orderByDesc('products.id')
            ->join('product_descriptions as ad', 'ad.product_id', 'products.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['products.created_at', 'ad.*']);

        if ($product_id)
        {
            if (is_array($product_id))
            {
                $query->whereIn('products.id', $product_id);
            }
            else
            {
                $query->where('products.id', $product_id);
            }
        }
        $query->select([
            'products.*',
            'ad.name',
            'ad.description',
        ]);
        return $query;
    }
}
