<?php

namespace App\Traits;

use App\Models\SocialLink;

trait Sociable
{

    private $providers = ['facebook', 'linkedin', 'twitter', 'instagram'];

    public function addSocials(array $links)
    {
        foreach ($links as $provider => $value) {
            if (!$this->isAllowedSocial($provider)) {
                return back('303')->with(['error' => 'unsupported provider']);
            }
            if($provider!=null && $value!=null){
                $this->social($provider) != null ? $this->social($provider)->update([
                    'link' => $value,
                ]) : $this->socialLinks()->create([
                    'provider' => $provider,
                    'link' => $value,
                ]);
            }

        }
        return $this->socialLinks();
    }

    /**
     * @param $provider
     */
    public function isAllowedSocial($provider)
    {
        return in_array($provider, $this->providers);
    }

    public function social($provider)
    {
        if (count($this->socialLinks()->where('provider', $provider)->get())) {
            return $this->socialLinks()->where('provider', $provider)->first();
        }
        return null;
    }

    public function socialLinks()
    {
        return $this->morphMany(SocialLink::class, 'sociable');
    }

    public function facebook()
    {
        return $this->social('facebook')->get();
    }

    public function twitter()
    {
        return $this->social('twitter')->get();
    }

    public function linkedin()
    {
        return $this->social('linkedin')->get();
    }

    public function instagram()
    {
        return $this->social('instagram')->get();
    }

    public function getSocialsAttribute()
    {
        $socialLinks = [];
        foreach ($this->providers as $provider) {
            $socialLinks[$provider] = $this->social($provider);
        }
//        dd($socialLinks);
        return $socialLinks;
    }
}
