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

use SabaiApps\Directories\Component\Form\Form;

/**
 * SortableCheckboxesField provides a group of checkboxes with drag-and-drop sorting.
 * Remembers previous sort order and supports custom option formatting.
 */
class SortableCheckboxesField extends CheckboxesField {

	protected static $_elements = array();

	/**
	 * Initializes the SortableCheckboxes field, sets up sortable options and pre-render callback.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		parent::formFieldInit( $name, $data, $form );
		$data['#inline'] = $data['#columns'] = false;
		if ( ! isset( $data['#id'] ) ) {
			$data['#id'] = $form->getFieldId( $name );
		}

		if ( ! isset( self::$_elements[ $form->settings['#id'] ] ) ) {
			self::$_elements[ $form->settings['#id'] ] = array();
		}
		self::$_elements[ $form->settings['#id'] ][ $data['#id'] ] = $data['#id'];

		$form->settings['#pre_render'][ __CLASS__ ] = array( $this, 'preRenderCallback' );

		// Sort options as was sorted previously
		if ( ! empty( $data['#default_value'] ) ) {
			$sorted_options = array();
			foreach ( $data['#default_value'] as $value ) {
				if ( isset( $data['#options'][ $value ] ) ) {
					$sorted_options[ $value ] = $data['#options'][ $value ];
					unset( $data['#options'][ $value ] );
				}
			}
			$data['#options'] = $sorted_options + $data['#options'];
		}

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

	/**
	 * Returns the prefix for option labels based on depth, with padding for RTL/LTR.
	 *
	 * @param string $prefix
	 * @param int    $depth
	 * @return string
	 */
	protected function _getOptionPrefix( $prefix, $depth ) {
		return ' style="padding-' . ( $this->_application->getPlatform()->isRtl() ? 'right' : 'left' ) . ':' . $depth . '0px"';
	}

	/**
	 * Returns the HTML format for a single checkbox option.
	 *
	 * @param array $data
	 * @param bool  $checked
	 * @return string
	 */
	protected function _getOptionFormat( array $data, $checked = false ) {
		return '<div%10$s><div class="%8$s" data-depth="%7$d">'
			. '<div class="%9$sform-check"><input class="%9$sform-check-input" type="%1$s" name="%2$s" value="%3$s"%4$s />'
			. '<label class="%9$sform-check-label">%5$s</label></div>'
			. '</div></div>';
	}

	/**
	 * Pre-render callback to enable sortable functionality for checkboxes.
	 *
	 * @param Form $form
	 */
	public function preRenderCallback( Form $form ) {
		parent::preRenderCallback( $form );
		$this->_application->getPlatform()->loadJqueryUiJs( array( 'sortable' ) );
		if ( ! empty( self::$_elements[ $form->settings['#id'] ] ) ) {
			$form->settings['#js_ready'][] = '$("#' . implode( ', #', self::$_elements[ $form->settings['#id'] ] ) . '")
    .find(".drts-form-field-radio-options")
    .sortable({handle:"label", containment:"parent", axis:"y", cursor:"move"});';
		}
	}
}
