<?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;

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

    protected $fillable = [
        'id'
    ];

    /**
     * Return descriptions for choice
     * @return HasMany
     */
    public function details()
    {
        return $this->hasOne(ChoiceDescription::class)->where('language_id',currentLanguage()->id);
    }
    public function descriptions($language_id= null)
    {
        if ($language_id) {
            $data = $this->hasMany(ChoiceDescription::class)->where('language_id', $language_id)->first();
            if(!$data){
                $data = $this->hasMany(ChoiceDescription::class)->first();
            }
            return $data;
        }
        $data = $this->hasMany(ChoiceDescription::class)->where('language_id', currentLanguage()['id'])->first();
        return $data;
    }
    public function currentLangauge()
    {
        return $this->hasOne(ChoiceDescription::class)->where('language_id',currentLanguage()->id);
    }
    public static function withDescription($choice_id = null)
    {
        $query = self::orderByDesc('choices.id')->join('choice_descriptions as ad', 'ad.choice_id', 'choices.id')
            ->where('ad.language_id', currentLanguage()->id)
            ->select(['choices.created_at', 'ad.*']);

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

}
