<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'price',
        'discount',
        'amount',
        'colors',
        'images',
        'amazon_url',
        'category_id',
        'status',
    ];

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

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

    public static function withDescription($categoriesId = null, $productName = null, $productId = null, $limit = null, $status = null)
    {
        $products = self::orderBy('products.id', 'ASC')
            ->join('product_descriptions as pd', 'pd.product_id', 'products.id')
            ->where('pd.language_id', currentLanguage()->id)
            ->join('categories', 'products.category_id', 'categories.id')
            ->join('category_descriptions as cat_d', 'cat_d.category_id', 'categories.id')
            ->where('cat_d.language_id', currentLanguage()->id);

        if (is_array($productId) && count($productId)){
            $products->whereIn('products.id', $productId);
        } elseif ($productId){
            $products->where('products.id', $productId);
        }

        if (is_array($categoriesId) && count($categoriesId)){
            $products->whereIn('products.category_id', $categoriesId);
        }

        if ($productName){
            $products->where('pd.name', 'LIKE', '%'.$productName.'%');
        }

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

        if ($status){
            $products->where('products.status', $status);
        }

        $products->select([
            'products.*',
            'pd.name',
            'pd.description',
            'cat_d.name as category_name',
        ])
            ->selectSub("SELECT COUNT(product_id) FROM evaluates WHERE product_id = products.id", 'evaluate_count')
            ->selectSub("SELECT AVG(evaluate) FROM evaluates WHERE product_id = products.id", 'evaluate_average');

        return $productId ? $products->first() : $products->get() ?? [];
    }


    public function comments()
    {
        return $this->hasMany(Evaluate::class);
    }

    public function coupon()
    {
        return $this->hasOne(Coupon::class)
            ->where('coupons.status', '=', 1)
            ->where('coupons.type', '=', 'products');
    }

}
