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

class Radio extends Field {
    /** @var array */ protected $options = array();
    /** @var bool  */ protected $inline  = true;

    /** @return static */ public function set_options( $o ) { $this->options = $o; return $this; }
    /** @return static */ public function options( $o )     { return $this->set_options($o); }
    /** @return static */ public function inline( $v = true ) { $this->inline = (bool)$v; return $this; }

    public function sanitize( $raw ) {
        $v = sanitize_text_field( (string)$raw );
        if ( array_key_exists( $v, $this->options ) ) return $v;
        reset($this->options);
        return (string)key($this->options);
    }

    public function render( $value ) {
    $id  = $this->field_id();
    $cls = 'sz-radio-group' . ( $this->inline ? ' sz-radio-group--inline' : '' );
    $is_pro_active = defined('STORZEN_IS_PRO') && STORZEN_IS_PRO === 'yes';
    $show_pro = $this->pro && ! $is_pro_active;
    echo '<div class="' . esc_attr($cls) . '">';
    foreach ( $this->options as $v => $l ) {
        $rid = $id . '_' . $v;
        echo '<label class="sz-radio-btn" for="' . esc_attr($rid) . '">';
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- disabled attribute may be added
        echo '<input type="radio" id="' . esc_attr($rid) . '" name="' . esc_attr($this->field_name()) . '" value="' . esc_attr($v) . '" ' . checked($value,$v,false) . ( $show_pro ? ' disabled' : '' ) . '>';
        echo '<span>' . esc_html($l) . '</span></label>';
    }
    echo '</div>';
    if ( $show_pro ) echo '<span class="sz-pro-badge">PRO</span>';
    }
}
