<?php

namespace App\Models;

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

/**
 * @property mixed id
 */
class Cobon extends Model
{
    //use soft delete
    use SoftDeletes;

    protected $fillable = 
    [
        'code','status','discount_type','discount_amount','start_date','end_date','count','seller_id','cobon_status','status_user'
    ];
    public function currentDescription()
    {
        return $this->hasOne(CobonDescription::class)->where('language_id',currentLanguage()['id']);
    }
    public function seller()
    {
        return $this->belongsTo(User::class,'seller_id')->withTrashed();
    }
    public function users()
    {
        return $this->belongsToMany(User::class,'cobon_users','cobon_id','user_id');
    }
    public function products()
    {
        return $this->belongsToMany(Product::class,'cobon_products','cobon_id','product_id');
    }
    /**
     * Return descriptions for cobon
     * @return HasMany
     */
    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(CobonDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(CobonDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(CobonDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }
    public static function withDescription($cobon_id = null)
    {
        $query = self::orderByDesc('cobons.id')->join('cobon_descriptions as ad', 'ad.cobon_id', 'cobons.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['cobons.created_at', 'ad.*']);

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

}
