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

class Select extends Field {
    /** @var array|callable */ protected $options = array();

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

    protected function get_options() {
        return is_callable( $this->options ) ? call_user_func( $this->options ) : (array)$this->options;
    }

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

    public function render( $value ) {
    $id   = $this->field_id();
    $opts = $this->get_options();
    $is_pro_active = defined('STORZEN_IS_PRO') && STORZEN_IS_PRO === 'yes';
    $show_pro = $this->pro && ! $is_pro_active;
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- disabled attribute may be added
    echo '<select class="sz-select" id="' . esc_attr($id) . '" name="' . esc_attr($this->field_name()) . '"' . ( $show_pro ? ' disabled' : '' ) . '>';
    foreach ( $opts as $v => $l ) {
        echo '<option value="' . esc_attr($v) . '" ' . selected($value, $v, false) . '>' . esc_html($l) . '</option>';
    }
    echo '</select>';
    if ( $show_pro ) echo '<span class="sz-pro-badge">PRO</span>';
    }
}
