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

class CheckboxGroup extends Field {
    /** @var array */ 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); }

    public function sanitize( $raw ) {
        if ( ! is_array($raw) ) return array();
        $clean = array_map( 'sanitize_text_field', $raw );
        return array_values( array_intersect( $clean, array_keys($this->options) ) );
    }

    public function render( $value ) {
        $value = (array)$value;
        $id    = $this->field_id();
        echo '<div class="sz-checkbox-group">';
        foreach ( $this->options as $v => $l ) {
        $cid = $id . '_' . $v;
        echo '<label class="sz-checkbox-item" for="' . esc_attr($cid) . '">';
        $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 '<input type="checkbox" id="' . esc_attr($cid) . '" name="' . esc_attr($this->field_name()) . '[]" value="' . esc_attr($v) . '" ' . checked( in_array($v,$value), true, false ) . ( $show_pro ? ' disabled' : '' ) . '>';
        echo '<span>' . esc_html($l) . '</span></label>';
    }
    echo '</div>';
    $is_pro_active = defined('STORZEN_IS_PRO') && STORZEN_IS_PRO === 'yes';
    $show_pro = $this->pro && ! $is_pro_active;
    if ( $show_pro ) echo '<span class="sz-pro-badge">PRO</span>';
    }
}
