<?php
/**
 * Class contains render functions for all admin setting fields
 *
 * @package Nevo
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) exit;

function nevo_array_value( $array, $index, $fallback = null ) {
	if ( ! is_array( $array ) ) {
		return null;
	}

	return isset( $array[ $index ] ) ? $array[ $index ] : $fallback;
}

/**
 * Return list of post types that support Page Settings.
 *
 * @param string $context
 * @return array
 */
function nevo_get_support_post_types( $context = 'all' ) {
	// Native post types
	$native_post_types = array( 'post', 'page' );

	// Custom post types
	$custom_post_types = get_post_types( array(
		'public'             => true,
		'publicly_queryable' => true,
		'rewrite'            => true,
		'_builtin'           => false,
	), 'names' );
	$custom_post_types = array_values( $custom_post_types );

	switch ( $context ) {
		case 'custom':
			$return = $custom_post_types;
			break;

		case 'native':
			$return = $native_post_types;
			break;

		default:
			$return = array_merge( $native_post_types, $custom_post_types );
			break;
	}

	return $return;
}

class Nevo_Admin_Fields {
	
	/**
	 * Render function wrapper
	 *
	 * @param array $args
	 * @param boolean $group
	 * @return string
	 */
	public static function render_field( $args, $group = false ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'type'       => 'text',
			'class'      => 'text',
			'label'      => '',
			'description'=> '',
			'notice'     => '',
			'required'   => false,
		) );

		if ( ! isset( $args['id'] ) ) {
			$args['id'] = sanitize_html_class( preg_replace( '/\[(.*?)\]/', '__$1', $args['name'] ) );
		}
		if ( $args['description'] ) {
			$args['description'] = "<p class=\"description\">{$args['description']}</p>";
		}
		if ( $args['label'] ) {
			$args['label'] = "<div class=\"nevo-admin-form-label\"><label>{$args['label']}</label>{$args['description']}</div>";
		}
		$function = 'render_' . $args['type'];
		if ( method_exists( 'Nevo_Admin_Fields', $function ) ) {
			ob_start();
			self::$function( $args );
			$html = ob_get_clean();
		}

		if ( !$group ) {
			echo "<div class=\"nevo-admin-form-row custom-{$args['class']}\">";
			echo $args['label'] ."<div class=\"nevo-admin-form-field\">";
			echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $args['notice'] .'</div></div>';
		} else {
			echo $html;
		}
	}
	
	/**
	 * Render tabs and inputs inside
	 */
	public static function render_tabs( $obj, $section, $tabs = array() ) {
		if ( ! isset( $section ) ) return;
		
		$first_tab = key( $tabs );
		?>
		<div id="nevo-page-settings" class="nevo-admin-page-settings nevo-admin-<?php echo esc_attr( $section ); ?> nevo-admin-form">
			<ul class="nevo-admin-nav tabs">
				<?php foreach ( $tabs as $key => $label ) : ?>
					<li class="nevo-admin-nav-item <?php echo esc_attr( $key == $first_tab ? 'active' : '' ); ?>">
						<a href="<?php echo esc_attr( '#nevo-page-settings--' . $key ); ?>"><?php echo $label; ?></a>
					</li>
				<?php endforeach; ?>
			</ul>

			<div class="nevo-admin-panels">
				<?php foreach ( $tabs as $key => $label ) : ?>
					<div id="<?php echo esc_attr( 'nevo-page-settings--' . $key ); ?>" class="nevo-admin-panel <?php echo esc_attr( $key == $first_tab ? 'active' : '' ); ?>">
						<?php
						/**
						 * Hook: nevo/admin/{$section}/page_settings/fields/{tab}
						 */
						do_action( "nevo/admin/{$section}/page_settings/fields/" . str_replace( '-', '_', $key ), $obj );

						/**
						 * Hook: nevo/admin/{$section}/page_settings/fields/
						 */
						do_action( "nevo/admin/{$section}/page_settings/fields", $obj, $key );
						?>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}
	
	/**
	 * Render Accordion and inputs inside
	 */
	public static function render_accordion( $obj, $section, $accordion = array() ) { // Đặt $obj lên đầu danh sách tham số
		if ( ! isset( $section ) ) return;
		
		$first_accor = key( $accordion );
		?>
		<div id="nevo-page-settings" class="nevo-admin-page-settings nevo-admin-<?php echo esc_attr( $section ); ?> nevo-admin-form">
			<ul class="nevo-admin-nav accordion">
				<?php foreach ( $accordion as $key => $label ) : ?>
					<li class="nevo-admin-nav-item <?php echo esc_attr( $key == $first_accor ? 'active' : '' ); ?>">
						<a href="<?php echo esc_attr( '#nevo-page-settings--' . $key ); ?>"><span class="admin-icon"><?php echo nevo_get_svg_icon( 'ui', 'bi-chevron-right', '', 12 ); ?></span><?php echo $label; ?></a>
					</li>
					<div class="nevo-admin-panels">
						<div id="<?php echo esc_attr( 'nevo-page-settings--' . $key ); ?>" class="nevo-admin-panel <?php echo esc_attr( $key == $first_accor ? 'active' : '' ); ?>">
							<?php
							/**
							 * Hook: nevo/admin/{$section}/page_settings/fields/{tab}
							 */
							do_action( "nevo/admin/{$section}/page_settings/fields/" . str_replace( '-', '_', $key ), $obj );

							/**
							 * Hook: nevo/admin/{$section}/page_settings/fields/
							 */
							do_action( "nevo/admin/{$section}/page_settings/fields", $obj, $key );
							?>
						</div>
					</div>
				<?php endforeach; ?>
			</ul>
		</div>
		<?php
	}

	/**
	 * Text control
	 *
	 * @param array $args
	 */
	private static function render_text( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'       => '',
			'placeholder' => '',
			'field_class' => 'regular-text',
			'before'      => '',
			'after'       => '',
		) );
		?>
		<?php echo $args['before']; ?>
		<input type="text" id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" class="nevo-admin-text-control <?php echo esc_attr( $args['field_class'] ); ?>" value="<?php echo esc_attr( $args['value'] ); ?>" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
		<?php echo $args['after']; ?>
		<?php
	}

	/**
	 * Textarea control
	 *
	 * @param array $args
	 */
	private static function render_textarea( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'       => '',
			'placeholder' => '',
			'field_class' => 'regular-text',
			'rows'        => 3,
		) );
		?>
		<textarea id="<?php echo esc_attr( $args['id'] ); ?>" rows="<?php echo esc_attr( $args['rows'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" class="nevo-admin-text-control <?php echo esc_attr( $args['field_class'] ); ?>" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>><?php echo esc_html( $args['value'] ); ?></textarea>
		<?php
	}

	/**
	 * URL control
	 *
	 * @param array $args
	 */
	private static function render_url( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'       => '',
			'placeholder' => '',
			'field_class' => 'regular-text',
		) );
		?>
		<input type="url" id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" class="nevo-admin-url-control <?php echo esc_attr( $args['field_class'] ); ?>" value="<?php echo esc_attr( $args['value'] ); ?>" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
		<?php
	}

	/**
	 * Number control
	 *
	 * @param array $args
	 */
	private static function render_number( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'       => '',
			'placeholder' => '',
			'min'         => '',
			'max'         => '',
			'step'        => '',
			'field_class' => 'small-text',
			'before'      => '',
			'after'       => '',
		) );
		?>
		<?php echo $args['before']; ?>
		<input type="number" id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" class="nevo-admin-number-control <?php echo esc_attr( $args['field_class'] ); ?>" value="<?php echo esc_attr( $args['value'] ); ?>" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" min="<?php echo esc_attr( $args['min'] ); ?>" max="<?php echo esc_attr( $args['max'] ); ?>" step="<?php echo esc_attr( $args['step'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
		<?php echo $args['after']; ?>
		<?php
	}

	/**
	 * Checkbox control
	 *
	 * @param array $args
	 */
	private static function render_checkbox( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'        => '',
			'return_value' => 1,
			'field_label'  => '',
			'field_class'  => '',
		) );
		?>
		<label class="nevo-admin-checkbox-control <?php echo esc_attr( $args['field_class'] ); ?>">
			<input type="checkbox" id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" value="<?php echo esc_attr( $args['return_value'] ); ?>" <?php checked( $args['return_value'], $args['value'] ); ?> <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
			<?php if ( ! empty( $args['field_label'] ) ) : ?>
				<span><?php echo $args['field_label']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
			<?php endif; ?>
		</label>
		<?php
	}

	/**
	 * Radio Image control
	 *
	 * @param array $args
	 */
	private static function render_radioimage( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'        => '',
			'field_label'  => '',
			'choices'      => array(),
			'field_class'  => '',
		));

		if ( is_null( $args['value'] ) ) {
			$args['value'] = '';
		}
		?>
		<ul class="nevo-admin-radioimage-control <?php echo esc_attr( $args['field_class'] ); ?>">
			<?php
			foreach ( $args['choices'] as $choice_value => $choice_data ) {
				if ( ! is_array( $choice_data ) ) {
					continue;
				}

				$choice_data = wp_parse_args( $choice_data, array(
					'field_label' => '',
					'disable'     => '',
					'bubble'      => '',
					'img' => '',
				) );

				$id = $args['name'] . '--' . $choice_value;
				$disabled = '';

				if ( $choice_data['disable'] && !apply_filters('nevo_open_field', false ) ) {
					$disabled = 'disabled';
				}

				?>
				<li class="nevo-admin-radioimage-control-item">
					<input type="radio" id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" value="<?php echo esc_attr( $choice_value ); ?>" <?php echo esc_attr( $choice_value === $args['value'] ? 'checked' : '' ); ?> <?php echo $disabled; ?>>
					<label for="<?php echo esc_attr( $id ); ?>" class="field-<?php echo esc_attr( $disabled ); ?>">
						<?php if ( ! empty( $choice_data['img'] ) ) : ?>
							<img src="<?php echo esc_url( $choice_data['img'] ); ?>">
						<?php endif; ?>
						<?php if ( ! empty( $choice_data['field_label'] ) ) : ?>
							<span><?php echo esc_html( $choice_data['field_label'] ); ?></span>
						<?php endif; ?>
						<?php if ( ! empty( $choice_data['bubble'] ) && !apply_filters('nevo_open_field', false ) ) : ?>
							<span class="bubble"><?php echo esc_html( $choice_data['bubble'] ); ?></span>
						<?php endif; ?>
					</label>
				</li>
				<?php
			}
			?>
		</ul>
		<?php
	}


	/**
	 * Color control
	 *
	 * @param array $args
	 */
	private static function render_color( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		wp_enqueue_script( 'alpha-color-picker' );
		wp_enqueue_style( 'alpha-color-picker' );

		$args = wp_parse_args( $args, array(
			'value'       => '',
			'default'     => '',
			'field_label' => '',
			'field_class' => '',
			'alpha'       => true,
		) );
		?>
		<div class="nevo-admin-color-control">
			<input type="text" id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" value="<?php echo esc_attr( $args['value'] ); ?>" maxlength="30" placeholder="<?php esc_attr_e( 'Hex / RGBA', 'nevo' ); ?>" data-default-color="<?php echo esc_attr( $args['default'] ); ?>" data-show-opacity="<?php echo esc_attr( $args['alpha'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
		</div>
		<?php
	}
	
	/**
	 * Select control
	 *
	 * @param array $args
	 */
	private static function render_select( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		$args = wp_parse_args( $args, array(
			'value'       => '',
			'placeholder' => '',
			'choices'     => array(),
			'field_class' => '',
			'before'      => '',
			'after'       => '',
		) );
		?>
		<?php echo $args['before']; ?>
		<select id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?>" class="nevo-admin-select-control <?php echo esc_attr( $args['field_class'] ); ?>" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
			<?php self::select_options_markup( $args['choices'], $args['value'] ); ?>
		</select>
		<?php echo $args['after']; ?>
		<?php
	}
	
	/**
	 * Selects control
	 *
	 * @param array $args
	 */
	private static function render_selects( $args ) {
		if ( ! isset( $args['name'] ) ) return;
		$args = wp_parse_args( $args, array(
			'value'       => array(),
			'placeholder' => '',
			'choices'     => array(),
			'field_class' => '',
			'before'      => '',
			'after'       => '',
			'multiple'    => false,
			'required'    => false,
		) );
		?>
		<?php echo $args['before']; ?>
		<select id="<?php echo esc_attr( $args['id'] ); ?>" name="<?php echo esc_attr( $args['name'] ); ?><?php echo $args['multiple'] ? '[]' : ''; ?>" class="nevo-admin-select-control <?php echo esc_attr( $args['field_class'] ); ?>" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" <?php echo $args['multiple'] ? 'multiple' : ''; ?> <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
			<?php self::selects_options_markup( $args['choices'], $args['value'] ); ?>
		</select>
		<?php echo $args['after']; ?>
		<?php
	}
	
	/**
	 * Upload control
	 *
	 * @param array $args
	 */
	private static function render_upload( $args ) {
		if ( ! isset( $args['name'] ) ) return;

		wp_enqueue_media();

		$args = wp_parse_args( $args, array(
			'value'        => '',
			'placeholder'  => '',
			'field_class'  => 'regular-text',
			'library'      => '',
			'frame_title'  => esc_html__( 'Upload & choose file', 'nevo' ),
			'frame_button' => esc_html__( 'Choose', 'nevo' ),
		) );
		?>
		<span id="<?php echo esc_attr( $args['id'] ); ?>" class="nevo-admin-upload-control <?php echo esc_attr( $args['field_class'] ); ?>" data-title="<?php echo esc_attr( $args['frame_title'] ); ?>" data-button="<?php echo esc_attr( $args['frame_button'] ); ?>" data-library="<?php echo esc_attr( implode( ',', (array) $args['library'] ) ); ?>">
			<div class="custom_media_preview">
			<?php if ( $args['value'] ) : ?>
				<img class="custom_media_preview_default"
					 src="<?php echo esc_url( $args['value'] ); ?>"
					 style="max-width:100%;"
				/>
			<?php endif; ?>
			</div>
			<input type="url" name="<?php echo esc_attr( $args['name'] ); ?>" value="<?php echo esc_attr( $args['value'] ); ?>" class="nevo-admin-upload-control-text custom_media_input" placeholder="<?php echo esc_attr( $args['placeholder'] ); ?>" <?php echo ( $args['required'] ? 'required' : '' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
			<a href="#" class="custom_media_upload button"><span class="dashicons dashicons-upload"></span></a>
		</span>
		<?php
	}

	/**
	 * Render <option> tags for <select> input using the given choices array.
	 */
	private static function select_options_markup( $array, $value = '', $echo = true ) {
		$output = '';

		if ( array_keys( $array ) === range( 0, count( $array ) - 1 ) ) {
			$array = self::convert_array_to_associative( $array );
		}

		foreach ( $array as $a1 => $a2 ) {

			if ( is_array( $a2 ) ) {
				// Add <optgroup> and do recursive
				$output .= '<optgroup label="' . esc_attr( $a1 ) . '">';
				$output .= self::select_options_markup( $a2, $value, false );
				$output .= '</optgroup>';
			} else {
				// Check selected state
				if ( is_array( $value ) ) {
					$selected = in_array( $a1, $value ) ? selected( true, true, false ) : '';
				} else {
					$selected = selected( $a1, $value, false );
				}

				$output .= '<option value="' . esc_attr( $a1 ) . '" ' . $selected . '>' . $a2 . '</option>';
			}
		}

		if ( $echo ) {
			echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		} else {
			return $output;
		}
	}
	private static function selects_options_markup( $choices, $value ) {
		foreach ( $choices as $key => $label ) {
			$selected = is_array( $value ) ? in_array( $key, $value ) : $key == $value;
			echo '<option value="' . esc_attr( $key ) . '" ' . ( $selected ? 'selected' : '' ) . '>' . esc_html( $label ) . '</option>';
		}
	}

	/**
	 * Convert any array type to be associative array.
	 */
	private static function convert_array_to_associative( $array ) {
		$assoc = array();

		foreach ( $array as $key => $value ) {
			$assoc[ $value ] = $value;
		}

		return $assoc;
	}
}

function nevo_get_admin_field( $args, $group = false ) {
	return Nevo_Admin_Fields::render_field( $args, $group );
}

function nevo_get_admin_tabs( $obj, $section, $tabs = array() ) {
	return Nevo_Admin_Fields::render_tabs( $obj, $section, $tabs );
}

function nevo_get_admin_accor( $obj, $section, $accordion = array() ) {
	return Nevo_Admin_Fields::render_accordion( $obj, $section, $accordion );
}