<?php

namespace App\Traits;

use App\Models\Language;
use App\Models\LanguageProficiency;
use Illuminate\Support\Facades\DB;

trait Languagable
{

    public function addMastery(int $languageId, int $proId)
    {
        $this->languageMasteries()->save(Language::find($languageId), [
            'language_proficiency_id' => $proId,
        ]);
    }

    public function languageMasteries()
    {
        return $this->morphToMany(Language::class, 'languagable')->withPivot('id', 'language_proficiency_id');
    }

    public function removeMastery(int $id)
    {
        DB::table('languagables')->where('id', $id)->delete();
    }

    public function updateMastery(int $id, int $languageId, int $proId)
    {
        DB::table('languagables')->where('id', $id)->update([
            'language_proficiency_id' => $proId,
            'language_id' => $languageId,
        ]);
    }

    public function getLanguageMasteriesAttribute()
    {
        $languageMasteries = [];
        $masteries = $this->languageMasteries()->get();
        foreach ($masteries as $mastery) {
            $mastery = $mastery->pivot;
            // dd($mastery);
            $proficiency = LanguageProficiency::find($mastery->language_proficiency_id);
            $language = Language::find($mastery->language_id);
            $languageMasteries[] = [
                'id' => $mastery->id,
                'language' => $language,
                'proficiency' => $proficiency
            ];
        }
        return $languageMasteries;

    }

}
