<?php

/**
* 
*/
class Phosphor_Backend_Form
{
	function __construct() {
	}

	/**
	 * Checks if a field is nested i.e. contains other fields in it.
	 *
	 * @var array $field Array containing Field information.
	 * @return bool Inidicating whether or not the field is nested.
	 **/
	function is_nested( $field ){
		return (isset($field['type']) && $field['type'] == 'nested') || (isset($field['widget']) && $field['widget'] == 'nested');
	}

	/**
	 * Checks if a field is hidden.
	 *
	 * @var array $field Array containing Field information.
	 * @return bool Inidicating whether or not the field is nested.
	 **/
	function is_hidden( $field ){
		return (isset($field['widget']) && $field['widget'] == 'hidden');
	}

	/**
	 * Uses the wp_parse_args() function to add the missing arguments to a field array.
	 *
	 * @var array An array containing infomation about a single field.
	 * @return array The passed array with all the missing items filled in.
	 **/
	function parse_args($args) {
		$defaults = array(
			'title' 	=> '',
			'def' 		=> '',
			'widget'	=> 'text',
			'type' 		=> 'text',
			'desc' 		=> '',
			'items' 	=> array(),
		);
		return wp_parse_args($args, $defaults);
	}

	function enqueue_resources() {
		wp_enqueue_script( "phosphor-form-script" );
		wp_enqueue_style( "phosphor-form-styles" );
	}

	function render_with_label($args) {
		$this->enqueue_resources();
		$args = $this->parse_args($args);
		?>
			<label class="fe-label"><?php echo $args['title'] ?></label>
		<?php
		$this->print_field($args);
	}

	/**
	 * Takes an array of attributes and outputs a settings field by using the appropriate callback.
	 *
	 * @var array $args Field arguments such as field type, current value etc.
	 **/
	public function render($args){
		$this->enqueue_resources();
		$args = $this->parse_args($args);
		$this->print_field($args);
	}

	public function print_field($args) {
		call_user_func( array($this, $args['widget'] . '_widget_callback'), $args['field_name'], $args['current'], $args );

		if( $args['desc'] ):
			?>
		 		<p class="description"><?php echo $args['desc']; ?></p>
		 	<?php
		endif;
	}

	/**
	 * Removes potentially harmful tags from user input and makes sure the entered value is what it is supposed to be.
	 *
	 * @var mixed $input The item to be validated.
	 * @var string $type The type that should be considered when sanitizing this item. For instance int.
	 * @return mixed A sanitized value ready to be inserted in the DB.
	 **/
	public function sanitize( $input, $type ) {

		if( $input === '' )
			return $input;

		switch ($type) {
			case 'int':
				$input = intval($input);
				break;

			case 'bool':
				$input = (bool)$input;
				break;

			case 'multicheckbox':
				foreach ($input as $subitem_key => $subitem) {
					$input[$subitem_key] = (bool)$subitem;
				}
				break;

			case 'html':
				$input = balanceTags($input);
				break;

			default:
				$input = wp_strip_all_tags($input);
				break;
		}

		return $input;
	}

	public function make_field_name($base, $indices) {
		$field_name = $base;
		foreach ($indices as $index) {
			$field_name .= '['. $index . ']';
		}

		return $field_name;
	}

	public function get_current_val($values, $indices) {
		$val = $values;
		foreach ($indices as $index) {
			if( isset($val[ $index ]) ){
				$val = $val[ $index ];
			}
			else {
				$val = '';
			}
		}

		return $val;
	}

	function nested_widget_callback($field_name, $current, $args) {
		foreach($args['items'] as $item_id => $item):
			$item_args 	= array_merge(
				array(
					'current' 		=> isset( $args['current'][$item_id] ) ? $args['current'][$item_id] : '',
					'field_name' 	=> $args['field_name'] . '['. $item_id .']'
				),
				$item
			);
			$this->render($item_args);
		endforeach;
	}

	function text_widget_callback($field_name, $current, $args) {
		?>
			<input type="text" name="<?php echo $field_name; ?>" value="<?php echo esc_attr($current); ?>" />
		<?php
	}

	function color_widget_callback($field_name, $current, $args) {
		?>
			<div class="fe-color-container">
				<input type="text" class="fe-color" name="<?php echo $field_name; ?>" value="<?php echo esc_attr($current); ?>" />
				<button class="fe-colorpicker-btn button"><?php _e('Pick Color', 'phosphor') ?></button><span style="background:<?php echo esc_attr($current); ?>;" class="fe-color-preview"></span>
				<div class="fe-colorpicker"></div>
			</div>
			<?php wp_enqueue_style( 'farbtastic' ); ?>
    		<?php wp_enqueue_script( 'farbtastic' ); ?>
		<?php
	}

	function checkbox_widget_callback($field_name, $current, $args)	{
		?>
			<input type="hidden" name="<?php echo $field_name; ?>" value="0" />
			<input type="checkbox" id="<?php echo $field_name; ?>" name="<?php echo $field_name; ?>" value="1" <?php checked($current); ?> />
		<?php
	}

	function select_widget_callback($field_name, $current, $args) {
		?>
			<select name="<?php echo $field_name ?>">
				<?php foreach ($args['items'] as $key => $item): ?>
					<option value="<?php echo $key; ?>" <?php selected($current, $key); ?> ><?php echo $item; ?></option>
				<?php endforeach; ?>
			</select>
		<?php
	}

	function image_picker_widget_callback($field_name, $current, $args){
		wp_enqueue_script( "image-picker-script" );
		wp_enqueue_style( "image-picker-style" );
		?>
			<div class="fe-image-picker-container">
				<select class="fe-image-picker" name="<?php echo $field_name ?>">
					<?php foreach ($args['items'] as $key => $item): ?>
						<?php
							$item = wp_parse_args (
								$item,
								array(
									'image' => '',
									'label' => ''
								)
							);
						?>
						<option value="<?php echo $key; ?>" data-img-src="<?php echo $item['image']; ?>" data-img-label="<?php echo $item['label']; ?>"  <?php selected($current, $key); ?> ></option>
					<?php endforeach; ?>
				</select>
			</div>
		<?php
	}

	function textarea_widget_callback($field_name, $current, $args) {
		?>
			<textarea name="<?php echo $field_name ?>"><?php echo esc_textarea($current); ?></textarea>
		<?php
	}

	function media_items_widget_callback($field_name, $current, $args) {
		wp_enqueue_media();

		?>
		<div class="fe-media-items">
			<input type="hidden" name="<?php echo $field_name ?>" value="<?php echo esc_attr($current); ?>" autocomplete='off' />
			<button type="button" class="button fe-media-select"><?php _e('Choose Media Items', 'phosphor'); ?></button>
			<button type="button" class="button fe-media-clear"><?php _e('Clear', 'phosphor'); ?></button>
			<div class="fe-selected-media">
				<?php
					$image_ids = !empty($current) ? explode(',', $current) : array();
					foreach($image_ids as $id){
						echo wp_get_attachment_image( $id, 'thumbnail' );
					}
				?>
			</div>
		</div>
		<?php
	}

	function multicheckbox_widget_callback($field_name, $current, $args) {
		?>
			<?php
				foreach ($args['items'] as $key => $checkboxitem ):
					$item_field_name = $field_name."[$key]";
					$item_current = isset($current[$key]) ? $current[$key] : '';
			?>
				<input type="hidden" name="<?php echo $item_field_name ?>" value="0" />
				<input type="checkbox" name="<?php echo $item_field_name ?>" id="<?php echo esc_attr($item_field_name) ?>" value="1" <?php checked( $item_current ); ?> />
				<label for="<?php echo $item_field_name ?>"><?php echo $checkboxitem; ?></label><br/>
			<?php endforeach; ?>
		<?php
	}

	function media_url_widget_callback($field_name, $current, $args) {
		wp_enqueue_media();

		?>
			<div class="fe-media-url">
				<input type="text" name="<?php echo $field_name; ?>" value="<?php echo esc_attr($current); ?>" />
				<button class="button fe-media-url-select"><?php _e('Choose Media Item', 'phosphor'); ?></button>
			</div>
		<?php
	}

	function hidden_widget_callback($field_name, $current, $args) {
		?>
			<input type="hidden" name="<?php echo $field_name; ?>" value="<?php echo esc_attr($current); ?>" />
		<?php
	}

	function slider_widget_callback($field_name, $current, $args) {
		wp_enqueue_script('jquery-ui-slider');
		$args = wp_parse_args(
			$args,
			array(
				'unit' 	=> '',
				'min' 	=> '',
				'max' 	=> ''
			)
		);

		?>
			<div class="fe-slider-container">
				<input type="hidden" name="<?php echo $field_name; ?>" value="<?php echo esc_attr($current); ?>" />
				<div class="fe-slider-default <?php echo ($current) ? 'fe-hidden' : ''; ?>">
					<?php _e('Default', 'phosphor'); ?>
				</div>
				<div class="fe-slider-state <?php echo ($current) ? '' : 'fe-hidden'; ?>">
					<span class="fe-slider-value">
						<?php echo ($current) ? esc_html($current) : __('Default', 'phosphor'); ?>
					</span>
					<span class="fe-slider-unit">
						<?php echo $args['unit']; ?>
					</span>
				</div>
				<div class="fe-slider" data-value="<?php echo esc_attr($current); ?>" data-min="<?php echo $args['min']; ?>" data-max="<?php echo $args['max']; ?>"></div>
				<button class="fe-slider-clear button"><?php _e('Clear', 'phosphor') ?></button>
			</div>
		<?php
	}
}

?>