<?php
namespace SabaiApps\Directories\Component\Form\Field;

use SabaiApps\Directories\Component\Form\Form;

/**
 * CheckboxField provides a single checkbox input.
 * Supports switch-style rendering and validation for required fields.
 */
class CheckboxField extends RadioField {

	protected $_type = 'checkbox';

	/**
	 * Initializes the Checkbox field and enables switch style if specified.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		parent::formFieldInit( $name, $data, $form );

		if ( isset( $data['#switch'] ) && ! $data['#switch'] ) {
			return;
		}

		$data['#switch'] = true;
	}

	/**
	 * Handles value processing and validation for the Checkbox field on submit.
	 *
	 * @param mixed $value
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldSubmit( &$value, array &$data, Form $form ) {
		$_value = is_array( $value ) ? $value : array( $value );

		// Is it a required field?
		if ( count( $_value ) === 0 || empty( $_value[0] ) ) {
			if ( $form->isFieldRequired( $data ) ) {
				$form->setError( isset( $data['#required_error_message'] ) ? $data['#required_error_message'] : __( 'Selection required.', 'directories-pro' ), $data );
			}
			$value = isset( $data['#off_value'] ) ? $data['#off_value'] : false;

			return;
		}

		if ( isset( $data['#on_value'] ) ) {
			if ( $_value[0] != $data['#on_value'] ) {
				$form->setError( __( 'Invalid option selected.', 'directories-pro' ), $data );

				return;
			}
			$value = $data['#on_value'];
		} else {
			$value = true;
		}
	}

	/**
	 * Renders the Checkbox field, supporting switch-style rendering.
	 *
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldRender( array &$data, Form $form ) {
		if ( empty( $data['#switch'] ) ) {
			$data['#horizontal_label_padding'] = false;
			parent::formFieldRender( $data, $form );

			return;
		}

		$checked                           = $this->_isChecked( $data );
		$data['#horizontal_label_padding'] = false;
		$html                              = sprintf(
			'<label class="%6$smy-custom-switch%4$s" for="%7$s-on">
    <input class="%6$smy-custom-switch-input" type="checkbox" id="%7$s-on" name="%1$s" value="%3$s"%2$s%5$s>
    <span class="%6$smy-custom-switch-indicator"></span>
    <span class="%6$smy-custom-switch-description"></span>
</label>',
			$data['#name'],
			$checked ? ' checked="checked"' : '',
			isset( $data['#on_value'] ) ? $this->_application->H( $data['#on_value'] ) : 1,
			empty( $data['#disabled'] ) ? '' : ' ' . DRTS_BS_PREFIX . 'my-custom-switch-disabled',
			$this->_application->Attr( $data['#attributes'], 'class' ),
			DRTS_BS_PREFIX,
			$form->getFieldId( $data['#name'] )
		);

		$this->_render( $html, $data, $form );
	}
}
