<?php
namespace Storzen\Fields;
use Storzen\Contracts\Field;
defined('ABSPATH') || exit;

class Color extends Field {
    public function sanitize( $raw ) {
        $clean = sanitize_hex_color( (string)$raw );
        return $clean ? $clean : (string)$this->default;
    }

    public function render( $value ) {
    $id  = $this->field_id();
    $sw  = $id . '_sw';
    $val = esc_attr( (string)$value );
    $is_pro_active = defined('STORZEN_IS_PRO') && STORZEN_IS_PRO === 'yes';
    $show_pro = $this->pro && ! $is_pro_active;
    echo '<div class="sz-color-wrap">';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $val is already escaped with esc_attr() above
    echo '<input type="color" class="sz-color-swatch" id="' . esc_attr($sw) . '" value="' . $val . '"';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- disabled attribute may be added
    echo ' oninput="document.getElementById(\'' . esc_js($id) . '\').value=this.value"' . ( $show_pro ? ' disabled' : '' ) . '>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $val is already escaped with esc_attr() above
    echo '<input type="text" class="sz-input sz-color-text" id="' . esc_attr($id) . '" name="' . esc_attr($this->field_name()) . '" value="' . $val . '" placeholder="#000000"';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- disabled attribute may be added
    echo ' oninput="document.getElementById(\'' . esc_js($sw) . '\').value=this.value"' . ( $show_pro ? ' disabled' : '' ) . '>';
    echo '</div>';
    if ( $show_pro ) echo '<span class="sz-pro-badge">PRO</span>';
    }
}
