<?php

namespace Storeplugin\PDFInvoice\Framework\Fields\Types;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractField;

class CheckboxField extends AbstractField
{
    /**
     * Get the field type.
     *
     * @return string
     */
    public static function getType(): string
    {
        return 'checkbox';
    }

    /**
     * Render the field.
     *
     * @param array  $field
     * @param mixed  $value
     * @param string $prefix
     *
     * @return string
     */
    public function render(array $field, $value, string $prefix): string
    {
        $options = $field['options'];
        $isDisabled = $this->hasTruthyFlag($field, 'disabled');
        $isRequired = $this->hasTruthyFlag($field, 'required');
        $input_class = $this->resolveClass(
            $field,
            'nxtf-field-checkbox'
        );

        if (empty($options) || !is_array($options)) {
            $attrs = $this->buildAttributes([
                'type'    => 'checkbox',
                'id'      => $this->getFieldId($field),
                'name'    => $this->getFieldName($field['id'], $prefix),
                'value'   => '1',
                'class'   => $input_class,
                'checked' => $this->isTruthy($value),
                'disabled' => $isDisabled ? true : null,
                'required' => $isRequired ? true : null,
            ]);

            $singleId = $this->getFieldId($field);

            return sprintf(
                '<div class="nxtf-checkbox-wrapper"><input %s><label for="%s" class="nxtf-checkbox-label">%s</label></div>',
                $attrs,
                \esc_attr($singleId),
                \esc_html($field['checkbox_label'] ?? 'Enable')
            );
        }

        $value = is_array($value) ? array_map('strval', $value) : [];
        $items = [];

        foreach ($options as $option_value => $option_label) {
            $optionId = $this->getFieldId($field) . '_' . \sanitize_key((string) $option_value);
            $attrs = $this->buildAttributes([
                'type'    => 'checkbox',
                'id'      => $optionId,
                'name'    => $this->getFieldName($field['id'], $prefix, true),
                'value'   => (string) $option_value,
                'class'   => $input_class,
                'checked' => in_array((string) $option_value, $value, true),
                'disabled' => $isDisabled ? true : null,
            ]);

            $items[] = sprintf(
                '<div class="nxtf-checkbox-wrapper"><input %s><label for="%s" class="nxtf-checkbox-label">%s</label></div>',
                $attrs,
                \esc_attr($optionId),
                \esc_html($option_label)
            );
        }

        return sprintf('%s', implode('', $items));
    }
}
