<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Form\Fields\Component;

use DropshippingExportFreeVendor\WPDesk\Forms\Field\HiddenField;
use DropshippingExportFreeVendor\WPDesk\Forms\Field\InputTextField;
use DropshippingExportFreeVendor\WPDesk\Forms\Field\CheckboxField;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\OptionalProductField;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldDefaultValue;
class ProductFieldsComponent extends \DropshippingExportFreeVendor\WPDesk\Forms\Field\BasicField
{
    public const PRODUCT_FIELDS = 'product_fields';
    public const FIELD_ACTIVE = 'is_active';
    public const FIELD_VALUE = 'value';
    public const FIELD_KEY = 'key';
    private array $product_fields = [];
    private array $items = [];
    public function __construct()
    {
        parent::__construct();
        $this->attributes['multiple'] = \true;
        $this->set_name(self::PRODUCT_FIELDS);
    }
    public function set_product_fields(array $product_fields)
    {
        $this->product_fields = $product_fields;
        return $this;
    }
    private function generate_items(): array
    {
        $items = [];
        if (empty($this->product_fields)) {
            return $items;
        }
        foreach ($this->product_fields as $field) {
            $key = $field::get_default_field_name();
            $val = $field::get_default_field_nice_name();
            $checkbox = (new CheckboxField())->add_class('product_field_checkbox')->set_name(self::FIELD_ACTIVE)->set_default_value(CheckboxField::VALUE_TRUE);
            if (is_subclass_of($field, OptionalProductField::class)) {
                if (\false === $field::is_optional()) {
                    $checkbox->set_readonly();
                }
            }
            $text = (new InputTextField())->set_name(self::FIELD_VALUE)->set_label($val)->add_class('width-100')->set_default_value($val);
            $items[] = [$checkbox, $text, (new HiddenField())->set_name(self::FIELD_KEY)->set_default_value($key)];
        }
        return $items;
    }
    public function get_items(): array
    {
        if (empty($this->items)) {
            $this->items = $this->generate_items();
        }
        return $this->items;
    }
    public function get_template_name(): string
    {
        return 'product-fields-component';
    }
}
