<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\Value;

use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldArrayValue;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldValue;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldValueModificator;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\AttributesModificator;
use WC_Product;
class CustomAttributesProductFieldValue implements ProductFieldValue, ProductFieldArrayValue, AttributesModificator
{
    public const KEY = 'custom_attributes';
    private ?array $value = null;
    private WC_Product $product;
    private ProductFieldValueModificator $modificator;
    public function __construct(WC_Product $product)
    {
        $this->product = $product;
    }
    public function set_attributes_modificator(ProductFieldValueModificator $modificator): void
    {
        $this->modificator = $modificator;
    }
    public static function get_key(): string
    {
        return self::KEY;
    }
    public static function get_name(): string
    {
        return esc_attr__('Custom Attributes', 'dropshipping-export-free');
    }
    public function has_array_value(): bool
    {
        return \is_array($this->get_field_value());
    }
    public function get_array_value(): ?array
    {
        return $this->get_field_value();
    }
    private function get_field_value(): ?array
    {
        $result = [];
        if ($this->value !== null) {
            return $this->value;
        }
        if (isset($this->modificator)) {
            $attributes_string = $this->modificator->get_value($this->product);
            $attributest_separator = $this->modificator->get_attributes_separator();
            $key_separator = $this->modificator->get_key_separator();
            $attributes = explode($attributest_separator, $attributes_string);
            foreach ($attributes as $attribute) {
                $attribute = explode($key_separator, $attribute);
                $key = $attribute[0];
                $value = $attribute[1];
                $options = trim($value);
                $result[$key] = $options;
            }
            $this->value = $result;
        }
        return $this->value;
    }
}
