<?php

namespace App;

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

/**
 * Class PurposeTraining
 * @mixin Builder
 * @package App
 */
class PurposeTraining extends Model
{
    use SoftDeletes;

    public function descriptions() :HasMany
    {
        return $this->hasMany(PurposeTrainingDescription::class);
    }

    /**
     * Get description of current language for pages
     * @return HasOne
     */
    public function currentDescription() :HasOne
    {
        return $this->hasOne(PurposeTrainingDescription::class)->where('language_id', currentLanguage()->id);
    }


    public static function withDescription($purpose_training_id = null, $hasRelation = null)
    {
        $purpose = self::join('purpose_training_descriptions as cd', 'cd.purpose_training_id', 'purpose_trainings.id')
            ->where('cd.language_id', currentLanguage()->id);

        if ($hasRelation){
            $purpose->whereHas($hasRelation);
        }

        if ($purpose_training_id){
            $purpose->where('purpose_trainings.id', $purpose_training_id);
        }

        $purpose->select([
            'purpose_trainings.id',
            'cd.name',
        ]);
        return $purpose_training_id ? $purpose->first() : $purpose->get() ?? [];
    }
}
