<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Supplier extends BaseAuditable
{
    use SoftDeletes;

    protected $guarded = ['id', 'created_at', '	updated_at'];

    protected $appends = ['productGroupNames'];

    public function getProductGroupNamesAttribute(): string
    {
        return $this->productGroup()->pluck('name');
    }

    public function contact(): \Illuminate\Database\Eloquent\Relations\MorphMany
    {
        return $this->morphMany(Contact::class, 'contactable');
    }

    public function contactOrderMail(): \Illuminate\Database\Eloquent\Relations\MorphMany
    {
        return $this->morphMany(Contact::class, 'contactable')->where('type', 'like', 'orderMail');
    }

    public function productGroup(): BelongsToMany
    {
        return $this->belongsToMany(ProductGroup::class, 'supplier_product_group')->withTimestamps();
    }

    public function service(): BelongsToMany
    {
        return $this->belongsToMany(Service::class, 'supplier_services')->withTimestamps();
    }

    public function profitCenter(): BelongsToMany
    {
        return $this->belongsToMany(ProfitCenter::class)->withTimestamps();
    }

    public function attachment(): \Illuminate\Database\Eloquent\Relations\MorphMany
    {
        return $this->morphMany(Attachment::class, 'attachable');
    }

    public function syncContactRelations(array $contactIds): bool
    {
        return $this->syncMorph(Contact::class, 'contactable', $contactIds);
    }

    public function syncMorph($class, $classFunctionName, $ids = []): bool
    {
        $f = new \ReflectionClass($class);
        $relationFunctionName = lcfirst($f->getShortName());
        if (method_exists($this, $relationFunctionName)) {
            $associated = $this->$relationFunctionName()->pluck('id')->toArray();
            $needToRemove = array_diff($associated, $ids);
            $needToAdd = array_diff($ids, $associated);
            if (count($needToRemove) > 0) {
                foreach ($needToRemove as $id) {
                    $item = $class::find($id);
                    $item->$classFunctionName()->dissociate($this);
                    $item->save();
                }
            }
            if (count($needToAdd) > 0) {
                foreach ($needToAdd as $id) {
                    $item = $class::find($id);
                    $item->$classFunctionName()->associate($this);
                    $item->save();
                }
            }

            return true;
        }

        return false;
    }
}
