<?php

namespace App\Models\Ecommerce\Product\Product\Concerns;

trait HasPropertiesJson
{
    /**
     * Initialize the trait
     */
    public function initializeHasPropertiesJson()
    {
        $this->casts['properties_json'] = 'array';
    }

    /**
     * Sync properties to JSON column
     */
    public function syncPropertiesJson(): void
    {
        $this->load(['properties.attribute', 'properties.values.value']);

        $propertiesJson = [];

        foreach ($this->properties as $property) {
            $attributeSlug = $property->attribute->slug;

            if (! isset($propertiesJson[$attributeSlug])) {
                $propertiesJson[$attributeSlug] = [];
            }

            foreach ($property->values as $value) {
                // We want to store both the key (for standard values) and the custom value
                // so we can filter by either.
                if ($value->value) {
                    $propertiesJson[$attributeSlug][] = $value->value->key;
                }

                if ($value->product_custom_value) {
                    $propertiesJson[$attributeSlug][] = $value->product_custom_value;
                }
            }

            // Unique values just in case
            $propertiesJson[$attributeSlug] = array_values(array_unique($propertiesJson[$attributeSlug]));
        }

        $this->properties_json = $propertiesJson;
        $this->saveQuietly();
    }
}
