<?php

use Quicker\Utils\Helper;

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'quicker_pro_tag_markup' ) ) {
	function quicker_pro_tag_markup( $disable, $class = '' ) {
		$pro_only = ! empty( $disable ) ? 'pro-fr' : '';
		$pro      = '';
		if ( $pro_only !== '' ) {
				$pro .= sprintf(
					'<a class="pro-link" target="_blank" href="%1$s"><span class="%2$s">%3$s</span></a>',
					esc_url( 'https://wpbens.com/plugin/quicker' ),
					esc_attr( $pro_only . ' ' . $class ),
					esc_html__( 'Upgrade to Pro', 'quicker' )
				);

		}

		return $pro;
	}
}

if ( ! function_exists( 'quicker_pro_link_markup' ) ) {
	function quicker_pro_link_markup( $disable, $class = '' ) {
		$pro_link_start = '';
		$pro_link_end   = '';
		if ( ! empty( $disable ) ) {
				$pro_link_start = sprintf(
					'<a class="pro-link" target="_blank" href="%s">',
					esc_url( 'https://wpbens.com/plugin/quicker' )
				);
				$pro_link_end   = sprintf(
					'<span class="pro-fr">%s</span></a>',
					esc_html__( 'Upgrade to Pro', 'quicker' )
				);
		}

		return array(
			'pro_link_start' => $pro_link_start,
			'pro_link_end'   => $pro_link_end,
		);
	}
}

if ( ! function_exists( 'quicker_checkbox_field' ) ) {

	function quicker_checkbox_field( $args ) {

		$condition_class = ! empty( $args['condition_class'] ) ? $args['condition_class'] : '';
		$disable         = ( ! empty( $args['disable'] ) && $args['disable'] == true ) ? 'disable' : '';
		$data_label      = ! empty( $args['data_label'] ) ? $args['data_label'] : '';
		$checkbox_label  = ! empty( $args['checkbox_label'] ) ? $args['checkbox_label'] : '';
		$checked         = ( ! empty( $args['checked'] ) && $args['checked'] == 'yes' ) ? 'checked' : '';
		extract( quicker_pro_link_markup( $disable ) );

		// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- kses method sanitizes HTML
		printf(
			'<div class="single-block %1$s">
			   <div class="form-label">%2$s</div>
			   %3$s
			   <div class="check-wrap">
				   <label class="input-section custom-switcher %4$s">
					   <input type="checkbox" class="switcher-ui-toggle" id="%5$s" name="%6$s" value="yes" %7$s data-label="%8$s" />
					   <span class="slider round"></span>
				   </label>
				   <span class="ml-1">%9$s</span>
			   </div>
			   %10$s
		   </div>' . "\n",
			esc_attr( $condition_class ),
			esc_html( $args['label'] ),
			\Quicker\Utils\Helper::kses( $pro_link_start ),
			esc_attr( $disable ),
			esc_attr( $args['id'] ),
			esc_attr( $args['id'] ),
			esc_attr( $checked ),
			esc_attr( $data_label ),
			\Quicker\Utils\Helper::kses( $checkbox_label ),
			\Quicker\Utils\Helper::kses( $pro_link_end )
		);
		// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

/**
 * Select option
 */
if ( ! function_exists( 'quicker_select_field' ) ) {
	function quicker_select_field( $args ) {
		$id            = ! empty( $args['id'] ) ? $args['id'] : '';
		$label         = ! empty( $args['label'] ) ? $args['label'] : '';
		$data_label    = ! empty( $args['data_label'] ) ? $args['data_label'] : '';
		$options_html  = '';
		$disable_flag  = ! empty( $args['disable'] ) && $args['disable'] == true ? 'disable' : '';
		$select_disabled_attr = ! empty( $args['disable'] ) && $args['disable'] == true ? 'disabled="disabled"' : '';
		$disabled_options = ! empty( $args['disabled_options'] ) ? (array) $args['disabled_options'] : array();
		$doc           = ! empty( $args['doc'] ) ? $args['doc'] : '';
		$doc_condition = ! empty( $args['doc_condition'] ) ? $args['doc_condition'] : '';
		$select_type   = ! empty( $args['select_type'] ) ? $args['select_type'] : 'single';
		$multiple_attr = '';
		$selected_val  = '';

		if ( 'single' == $select_type ) {
			$selected = ! empty( $args['selected'] ) ? $args['selected'] : '';
			if ( ! empty( $args['options'] ) ) :
				foreach ( $args['options'] as $key => $item ) :
					$selected_val   = $key == $selected ? 'selected' : '';
					$disabled_attr  = in_array( (string) $key, array_map( 'strval', $disabled_options ), true ) ? 'disabled' : '';
					$options_html  .= '<option ' . esc_attr( $disabled_attr ) . ' value="' . esc_attr( $key ) . '" ' . esc_attr( $selected_val ) . '>' . esc_html( $item ) . '</option>';
				endforeach;
				$selected_val = 'data-selected="' . esc_attr( $selected ) . '"';
			endif;
		} else {
			$selected      = ! empty( $args['selected'] ) ? (array) $args['selected'] : array();
			$selected_val  = 'data-selected="' . esc_attr( wp_json_encode( $selected ) ) . '"';
			$multiple_attr = ' multiple="multiple"';
			if ( ! empty( $args['options'] ) ) :
				foreach ( $args['options'] as $key => $item ) :
					$is_selected   = in_array( (string) $key, array_map( 'strval', $selected ), true ) ? 'selected' : '';
					$disabled_attr = in_array( (string) $key, array_map( 'strval', $disabled_options ), true ) ? 'disabled' : '';
					$options_html .= '<option ' . esc_attr( $disabled_attr ) . ' value="' . esc_attr( $key ) . '" ' . esc_attr( $is_selected ) . '>' . esc_html( $item ) . '</option>';
				endforeach;
			endif;
		}

		$condition_class = ! empty( $args['condition_class'] ) ? $args['condition_class'] : '';
		// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- kses method sanitizes HTML
		printf(
			'<div class="single-block %1$s">
		   	   <div>
				<div class="form-label">%2$s</div>
				<div class="%9$s">%10$s</div>
			   </div>
			   <div class="input-section">
			   <select name="%3$s" id="%4$s" %5$s data-option="%6$s"%11$s %12$s>%7$s</select>
				   %8$s
			   </div>
		   </div>' . "\n",
			esc_attr( $condition_class ),
			esc_html( $label ),
			esc_attr( $id ),
			esc_attr( $id ),
			$selected_val, // Already contains escaped data-selected="..." attribute.
			esc_js( $data_label ),
			\Quicker\Utils\Helper::instance()->kses( $options_html ),
			\Quicker\Utils\Helper::instance()->kses( quicker_pro_tag_markup( $disable_flag, 'select-pro-tag' ) ),
			esc_attr( $doc_condition ),
			\Quicker\Utils\Helper::instance()->kses( $doc ),
			$multiple_attr, // Safe: hardcoded ' multiple="multiple"' or empty string.
			$select_disabled_attr // Safe: either 'disabled="disabled"' or empty string.
		);
		// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

/**
 * Number/Text/Hidden
 */
if ( ! function_exists( 'quicker_number_input_field' ) ) {
	function quicker_number_input_field( $args ) {
		$id                = ! empty( $args['id'] ) ? $args['id'] : '';
		$wrapper_type      = ! empty( $args['wrapper_type'] ) ? $args['wrapper_type'] : '';
		$wrapper_class     = ! empty( $args['wrapper_class'] ) ? $args['wrapper_class'] : 'single-block';
		$label_class       = ! empty( $args['label_class'] ) ? $args['label_class'] : 'form-label';
		$value             = isset( $args['value'] ) && $args['value'] !== '' ? $args['value'] : '';
		$label             = ! empty( $args['label'] ) ? $args['label'] : '';
		$field_type        = ! empty( $args['field_type'] ) ? $args['field_type'] : 'text';
		$condition_class   = ! empty( $args['condition_class'] ) ? $args['condition_class'] : '';
		$disable           = ( ! empty( $args['disable'] ) && $args['disable'] == true ) ? 'disable' : '';
		$extra_label       = ! empty( $args['extra_label'] ) ? $args['extra_label'] : '';
		$placeholder       = ! empty( $args['placeholder'] ) ? $args['placeholder'] : '';
		$data_label        = ! empty( $args['data_label'] ) ? $args['data_label'] : '';
		$extra_label_class = ! empty( $args['extra_label_class'] ) ? $args['extra_label_class'] : '';
		$hidden_class      = $field_type == 'hidden' ? 'd-none' : '';
		extract( quicker_pro_link_markup( $disable ) );

		// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- kses method sanitizes HTML
		printf(
			'<div class="%1$s %2$s %3$s">
			   <div class="%4$s">%5$s</div>
			   %6$s
			   <div class="input-section">
				   <div class="input-wrap %7$s">
					   <input type="%8$s" name="%9$s" id="%10$s" value="%11$s" data-option="%12$s" placeholder="%13$s" />
					   <div class="extra-label %14$s">%15$s</div>
				   </div>
			   </div>
			   %16$s
		   </div>' . "\n",
			esc_attr( $wrapper_class ),
			esc_attr( $condition_class ),
			esc_attr( $hidden_class ),
			esc_attr( $label_class ),
			esc_html( $label ),
			\Quicker\Utils\Helper::kses( $pro_link_start ),
			esc_attr( $disable ), // 7
			esc_attr( $field_type ),
			esc_attr( $id ),
			esc_attr( $wrapper_type . $id ),
			esc_attr( $value ),
			esc_attr( $data_label ),
			esc_attr( $placeholder ),
			esc_attr( $extra_label_class ), // 14
			esc_html( $extra_label ),
			\Quicker\Utils\Helper::kses( $pro_link_end )
		);
		// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

/**
 * Textarea Field
 */
if ( ! function_exists( 'quicker_textarea_field' ) ) {
	function quicker_textarea_field( $args ) {
		$id              = ! empty( $args['id'] ) ? $args['id'] : '';
		$wrapper_class   = ! empty( $args['wrapper_class'] ) ? $args['wrapper_class'] : 'single-block';
		$label_class     = ! empty( $args['label_class'] ) ? $args['label_class'] : 'form-label';
		$value           = isset( $args['value'] ) ? $args['value'] : '';
		$label           = ! empty( $args['label'] ) ? $args['label'] : '';
		$condition_class = ! empty( $args['condition_class'] ) ? $args['condition_class'] : '';
		$disable         = ( ! empty( $args['disable'] ) && $args['disable'] == true ) ? 'disable' : '';
		$placeholder     = ! empty( $args['placeholder'] ) ? $args['placeholder'] : '';
		$extra_label     = ! empty( $args['extra_label'] ) ? $args['extra_label'] : '';
		$extra_label_class = ! empty( $args['extra_label_class'] ) ? $args['extra_label_class'] : '';
		$rows            = ! empty( $args['rows'] ) ? (int) $args['rows'] : 3;
		$cols            = ! empty( $args['cols'] ) ? (int) $args['cols'] : 0; // optional
		extract( quicker_pro_link_markup( $disable ) );

		// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- kses method sanitizes HTML, rows/cols are integers
		printf(
			'<div class="%1$s %2$s">
			   <div class="%3$s">%4$s</div>
			   %5$s
			   <div class="input-section">
				   <div class="input-wrap %6$s">
					   <textarea name="%7$s" id="%8$s" rows="%15$d" %16$s placeholder="%9$s" data-option="%10$s">%11$s</textarea>
					   <div class="extra-label %12$s">%13$s</div>
				   </div>
			   </div>
			   %14$s
		   </div>' . "\n",
			esc_attr( $wrapper_class ),
			esc_attr( $condition_class ),
			esc_attr( $label_class ),
			esc_html( $label ),
			\Quicker\Utils\Helper::kses( $pro_link_start ),
			esc_attr( $disable ),
			esc_attr( $id ),
			esc_attr( $id ),
			esc_attr( $placeholder ),
			esc_attr( $id ),
			esc_textarea( $value ),
			esc_attr( $extra_label_class ),
			esc_html( $extra_label ),
			\Quicker\Utils\Helper::kses( $pro_link_end ),
			$rows,
			$cols ? 'cols="' . intval( $cols ) . '"' : ''
		);
		// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

/**
 * Spacing (Top/Bottom/Left/Right) field
 */
if ( ! function_exists( 'quicker_spacing_field' ) ) {
	function quicker_spacing_field( $args ) {
		$label           = ! empty( $args['label'] ) ? $args['label'] : '';
		$condition_class = ! empty( $args['condition_class'] ) ? $args['condition_class'] : '';
		$disable         = ( ! empty( $args['disable'] ) && $args['disable'] == true ) ? 'disable' : '';
		$disabled_attr   = ! empty( $disable ) ? 'disabled' : '';
		$fields          = ! empty( $args['fields'] ) ? $args['fields'] : array();
		extract( quicker_pro_link_markup( $disable ) );

		$link_svg = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>';

		$html  = '<div class="single-block ' . esc_attr( $condition_class ) . '">';
		$html .= '<div class="form-label">' . esc_html( $label ) . '</div>';
		$html .= $pro_link_start;
		$html .= '<div class="quicker-spacing-control">';

		// Build groups of two (top/bottom, left/right)
		$chunks = array_chunk( $fields, 2 );
		$link_keys = array( 'tb', 'lr' );
		$link_titles = array(
			'tb' => __( 'Link Top & Bottom', 'quicker' ),
			'lr' => __( 'Link Left & Right', 'quicker' ),
		);

		foreach ( $chunks as $i => $group ) {
			$link_key = isset( $link_keys[ $i ] ) ? $link_keys[ $i ] : 'tb';
			$html .= '<div class="quicker-spacing-group">';

			// First field
			if ( isset( $group[0] ) ) {
				$f = $group[0];
				$html .= '<div class="quicker-spacing-field">';
				$html .= '<input type="number" id="' . esc_attr( $f['id'] ) . '" name="' . esc_attr( $f['id'] ) . '" value="' . esc_attr( $f['value'] ) . '" min="0" placeholder="0" ' . esc_attr( $disabled_attr ) . ' />';
				$html .= '<span class="quicker-spacing-label">' . esc_html( $f['label'] ) . '</span>';
				$html .= '</div>';
			}

			// Link button
			$html .= '<button type="button" class="quicker-spacing-link active" data-link="' . esc_attr( $link_key ) . '" title="' . esc_attr( $link_titles[ $link_key ] ?? '' ) . '">' . $link_svg . '</button>';

			// Second field
			if ( isset( $group[1] ) ) {
				$f = $group[1];
				$html .= '<div class="quicker-spacing-field">';
				$html .= '<input type="number" id="' . esc_attr( $f['id'] ) . '" name="' . esc_attr( $f['id'] ) . '" value="' . esc_attr( $f['value'] ) . '" min="0" placeholder="0" ' . esc_attr( $disabled_attr ) . ' />';
				$html .= '<span class="quicker-spacing-label">' . esc_html( $f['label'] ) . '</span>';
				$html .= '</div>';
			}

			$html .= '</div>';
		}

		$html .= '</div>';
		$html .= $pro_link_end;
		$html .= '</div>' . "\n";

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from escaped components above
		echo \Quicker\Utils\Helper::kses( $html );
	}
}

/**
 * Repeater field
 *
 * @param [type] $args
 * @return void
 */
if ( ! function_exists( 'quicker_admin_repeater_field' ) ) {
	function quicker_admin_repeater_field( $type, $args ) {
		$id              = ! empty( $args['id'] ) ? $args['id'] : '';
		$name            = ! empty( $args['name'] ) ? $args['name'] : '';
		$label           = ! empty( $args['label'] ) ? $args['label'] : '';
		$repeat_field    = ! empty( $args['repeat_field'] ) ? $args['repeat_field'] : array();
		$condition_class = ! empty( $args['condition_class'] ) ? $args['condition_class'] : '';
		// We now output only an empty container. Rows will be rendered via JS for better control.
		$repeat_html = '';

		$html = '
		<div class="single-block ' . esc_attr( $condition_class ) . '" id="' . esc_attr( $id ) . '">
			<div class="form-label">' . esc_html( $label ) . '</div>
			<div id="repeater-' . esc_attr( $type ) . '" class="repeat-wrapper" data-group-name="' . esc_attr( $name ) . '">
				<div class="repeat-section template-row" id="structure-' . esc_attr( $type ) . '">';

		// Build template row (hidden) containing all configured sub-fields (index placeholder __index__)
		if ( ! empty( $repeat_field ) ) {
			foreach ( $repeat_field as $value ) {
				$name_part   = $name . '[__index__]';
				$label_class = ! empty( $value['label_class'] ) ? $value['label_class'] : '';
				$html       .= '<div class="repeat-block">';
				$html       .= '<div class="repeat-label ' . esc_attr( $label_class ) . '">' . esc_html( $value['label'] ) . '</div>';
				$html       .= '<div class="repeat-input">' . quicker_repeat_input_field( $name_part, $value, '__index__' ) . '</div>';
				$html       .= '</div>';
			}
		}

		$html .= '</div> <!-- /.repeat-section template -->
				<div class="repeat-rows" id="containerElement-' . esc_attr( $type ) . '"></div>
			</div>
		</div>';

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- kses method sanitizes HTML
		echo \Quicker\Utils\Helper::kses( $html );
	}
}

if ( ! function_exists( 'quicker_repeat_input_field' ) ) {
	function quicker_repeat_input_field( $name_part, $value, $index ) {
		$html            = '';
		$name            = $name_part . '[' . $value['id'] . ']';
		$condition_class = ! empty( $value['condition_class'] ) ? $value['condition_class'] : '';

		switch ( $value['field_type'] ) {
			case 'hidden':
			case 'number':
			case 'text':
				$extra_label_class = ! empty( $value['extra_label_class'] ) ? $value['extra_label_class'] : '';
				$extra_label       = ! empty( $value['extra_label'] ) ? $value['extra_label'] : '';

				$html = '<input data-name="' . esc_js( $value['id'] ) . '" class="' . esc_attr( $value['id'] . '-' . $index ) . '" type="' . esc_attr( $value['field_type'] ) . '" name="' . esc_attr( $name ) . '" />
				<span class="extra-label ' . esc_attr( $extra_label_class ) . '">' . esc_html( $extra_label ) . '</span>';

				break;
			case 'select':
				$options_html = '';
				foreach ( $value['options'] as $key => $item ) {
					$options_html .= "<option value='" . esc_attr( $key ) . "'>" . esc_html( $item ) . '</option>';
				}
				$html = '<select data-name="' . esc_js( $value['id'] ) . '" class=" ' . esc_attr( $value['id'] ) . '" name="' . esc_attr( $name ) . '" data-id="' . esc_js( $index ) . '">' . \Quicker\Utils\Helper::kses( $options_html ) . '</select>';
				break;
			default:
				break;
		}

		return $html;
	}
}
