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

use SabaiApps\Directories\Component\Form\Form;

/**
 * ButtonsField provides a group of radio or checkbox buttons styled as Bootstrap buttons.
 * Handles rendering of button groups and options.
 */
class ButtonsField extends RadiosField {

	/**
	 * Returns the HTML for the button group.
	 *
	 * @param array $data
	 * @param Form  $form
	 * @param array $values
	 * @return string
	 */
	protected function _getHtml( array &$data, Form $form, array $values ) {
		$data['#id'] = $form->getFieldId( $data['#name'] );
		$name        = $data['#name'];
		if ( $this->_type == 'checkbox' ) {
			$name .= '[]';
		}
		$group_buttons = ! empty( $data['#group_buttons'] );
		$html          = array();
		if ( $group_buttons ) {
			$html[] = '<div class="' . DRTS_BS_PREFIX . 'btn-group" role="group" aria-label="' . $this->_application->H( $data['#title'] ) . '">';
		}
		foreach ( $data['#options'] as $option_value => $option_label ) {
			$html[] = $this->_doRenderOption( $data, $form, $name, $values, $option_value, $option_label );
		}
		if ( $group_buttons ) {
			$html[] = '</div>';
		}

		return implode( PHP_EOL, $html );
	}

	/**
	 * Returns the HTML format for a single button option.
	 *
	 * @param array $data
	 * @param bool  $checked
	 * @return string
	 */
	protected function _getOptionFormat( array $data, $checked = false ) {
		$active         = $checked ? ' %9$sactive' : '';
		$btn_color      = isset( $data['#btn_color'] ) ? $data['#btn_color'] : 'outline-secondary';
		$btn_size_class = isset( $data['#btn_size'] ) && in_array( $data['#btn_size'], array( 'sm', 'lg' ) ) ? ' %9$sbtn-' . $data['#btn_size'] : '';

		return '<label class="%9$sbtn %9$sbtn-' . $btn_color . $active . ' %9$smb-1%8$s' . $btn_size_class . '">'
			. '<input type="%1$s" name="%2$s" value="%3$s" class="%9$sbtn-check"%4$s> %5$s'
			. '</label>';
	}
}
