<?php

namespace Storeplugin\PDFInvoice\Framework\Fields\Types;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractField;

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

    /**
     * Render the field.
     *
     * @param array  $field
     * @param mixed  $value
     * @param string $prefix
     *
     * @return string
     */
    public function render(array $field, $value, string $prefix): string
    {
        $checked = $this->isTruthy($value);
        $isDisabled = $this->hasTruthyFlag($field, 'disabled');
        $input_class = 'nxtf-field-checkbox';
        $track_class = $this->resolveClass(
            $field,
            "nxtf-checkbox-checkmark",
            '',
            'switch_track_class',
            'switch_track_extra_class'
        );

        $attrs = $this->buildAttributes([
            'type'    => 'checkbox',
            'id'      => $this->getFieldId($field),
            'name'    => $this->getFieldName($field['id'], $prefix),
            'value'   => '1',
            'class'   => $input_class,
            'checked' => $checked,
            'disabled' => $isDisabled ? true : null,
        ]);

        return sprintf(
            '<label for="%s" class="nxtf-checkbox-switch">
                    <input %s>
                    <div class="%s">
                    <span class="nxtf-checkmark-icon--x dashicons dashicons-no-alt"></span>
                    <span class="nxtf-checkmark-icon--check dashicons dashicons-yes"></span>
                    </div>
                </label>',
            \esc_attr($this->getFieldId($field)),
            $attrs,
            \esc_attr($track_class)
        );
    }
}
