<?php

namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

class HelloPlus_Radio_Checkbox_Field {

	public function __construct() {
		add_action( 'init', [ $this, 'init_hooks' ] );
	}

	public function init_hooks() {
		add_action( 'hello_plus/forms/render_field/radio', [ $this, 'render_custom_radio_checkbox_field' ], 10, 3 );
		add_action( 'hello_plus/forms/render_field/checkbox', [ $this, 'render_custom_radio_checkbox_field' ], 10, 3 );
	}

	/**
	 * Render custom radio/checkbox field for Hello Plus Form.
	 *
	 * @param array $item Field settings.
	 * @param int $item_index Field index.
	 * @param object $form_instance Hello Plus Form widget instance.
	 */
	public function render_custom_radio_checkbox_field( $item, $item_index, $form_instance ) {
		$options = preg_split( "/\\r\\n|\\r|\\n/", $item['field_options'] );
		if ( empty( $options ) ) {
			return;
		}

		$field_type = $item['field_type']; // 'radio' or 'checkbox'

		echo '<div class="elementor-field-subgroup ' . esc_attr( $item['css_classes'] ?? '' ) . ' ' . esc_attr( $item['inline_list'] ?? '' ) . '">';

		foreach ( $options as $key => $option ) {
			$element_id = esc_attr( $item['custom_id'] ) . $key;
			$html_id = esc_attr( $item['custom_id'] . '-' . $key );
			$option_label = $option;
			$option_value = $option;

			if ( strpos( $option, '|' ) !== false ) {
				list( $option_label, $option_value ) = explode( '|', $option );
			}

			// Determine if checked
			$checked = '';
			if ( ! empty( $item['field_value'] ) ) {
				if ( $field_type === 'checkbox' && is_array( $item['field_value'] ) && in_array( $option_value, $item['field_value'], true ) ) {
					$checked = 'checked';
				} elseif ( $field_type === 'radio' && $option_value === $item['field_value'] ) {
					$checked = 'checked';
				}
			}

			// Input name
			$name = method_exists( $form_instance, 'get_attribute_name' ) ? $form_instance->get_attribute_name( $item ) : sanitize_title( $item['custom_id'] );
			if ( $field_type === 'checkbox' && count( $options ) > 1 ) {
				$name .= '[]';
			}

			echo '<span class="elementor-field-option">';
			echo '<input type="' . esc_attr( $field_type ) . '" id="' . esc_attr( $html_id ) . '" name="' . esc_attr( $name ) . '" value="' . esc_attr( $option_value ) . '" ' . $checked;

			if ( ! empty( $item['required'] ) && $field_type === 'radio' ) {
				echo ' required';
			}

			echo '> <label for="' . esc_attr( $html_id ) . '">' . esc_html( $option_label ) . '</label>';
			echo '</span>';
		}

		echo '</div>';
	}
}

new HelloPlus_Radio_Checkbox_Field();
