<?php

namespace App\Traits;

use App\Models\AccessManagement\GroupManagement\System;


/**
 * Trait RemoveRoleSystemText
 * This trait removes all your fields with system text (defined in $this->RemoveRoleSystemText) after retrieving it to the database.
 */
trait RemoveRoleSystemText
{
    /**
     * Checks if the attribute is valid.
     * @param $key
     * @return bool
     */
    private function isRemoveSystemText($key)
    {
        return in_array($key, $this->removeRoleSystemText);
    }

    /**
     * returns the value without system text.
     * @param $value
     * @return string|void decrypted value
     */
    private function removeRoleSystemText($value)
    {
        $systems = System::get()->pluck('name');
        $systems = json_decode(json_encode($systems), true);
        return trim(str_replace($systems, '', $value));
    }

    /**
     * returns the current value
     * @param $value
     * @return string
     */
    private function roleSystemText($value)
    {
        return $value;
    }

    /**
     * Get an attribute from the model.
     *
     * @param  string  $key
     * @return mixed
     */
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);
        if ($this->isRemoveSystemText($key)) {
            $systems = System::get()->pluck('name');
            $systems = json_decode(json_encode($systems), true);
            return trim(str_replace($systems, '', $value));
        }

        return $value;
    }

    /**
     * Set a given attribute on the model.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return $this
     */
    public function setAttribute($key, $value)
    {
        return parent::setAttribute($key, $value);
    }

    /**
     * Get an attribute array of all arrayable attributes.
     *
     * @return array
     */
    protected function getArrayableAttributes()
    {
        $attributes = parent::getArrayableAttributes();

        foreach ($attributes as $key => $attribute) {
            if ($this->isRemoveSystemText($key)) {
                $systems = System::get()->pluck('name');
                $systems = json_decode(json_encode($systems), true);
                $attribute = trim(str_replace($systems, '', $attribute));
                $attributes[$key] = $attribute;
            }
        }

        return $attributes;
    }
}