<?php

namespace Hilco\Models;

use DB;
use Illuminate\Database\Eloquent\Builder;

trait KeyWordsFunctional
{
	public function keywords(){
		return $this->morphMany(KeyWord::class, 'object');
	}

	public function setKeywordsAttribute($words) {
		$this->saveKeyWords($words);
	}
	
	public function saveKeyWords($words){
		if(gettype($words) == 'string'){
			$words = str_replace(',', ' ', $words);
			$words = explode(' ',$words);	
		}
		$existsKeyWords = $this->keywords;
		if(!isset($existsKeyWords)){
			$existsKeyWords = $this->keywords()->get();
		}
		$toDelete = $existsKeyWords->filter(function($val)use(&$words){
			$ind = array_search($val->keyword,$words);
			if($ind !== false){
				array_splice($words, $ind, 1);
				return false;
			}
			return true;
		});
		KeyWord::whereIn('id',$toDelete->pluck('id'))->forceDelete();
		foreach ($words as $word){
			$this->keywords()->create(['keyword'=>$word]);
		}
	}

	public function scopeGetByKeywords(Builder $query, $words){
		return $query->whereHas('keywords',function($query)use($words){
			return $query->search($words);
		});
	}
}