<?php

namespace App\Models;

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

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

    protected $fillable = [
        'image','second_image','status'
    ];

    /**
     * Return descriptions for offer
     * @return HasMany
     */

    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(OfferDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(OfferDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(OfferDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }

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

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