<?php
/**
 * QrCdr Renderer class
 *
 * Handles the HTML output for tabs, features, and inputs.
 *
 * @since  1.0.0
 *
 * @category  WordPress_Plugin
 * @package   QrCdr
 * @author    Nicola Franchini
 * @link      https://veno.es
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'QrCdr_Renderer' ) ) {
	/**
	 * QrCdr_Renderer class
	 */
	class QrCdr_Renderer {
		/**
		 * Holds an instance of the object
		 *
		 * @var instance
		 */
		protected static $instance = null;

		/**
		 * Returns the running object
		 *
		 * @return QrCdr_Renderer
		 */
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Renders the service navigation bar with scrolling capability.
		 *
		 * @param array  $qrcdr_tabs    List of tab keys to be rendered.
		 * @param string $form_id       The unique identifier for the form.
		 * @param string $getsection    The currently active section selector (e.g., '.qrcdr-text').
		 * @param mixed  $hook_data     Data to be passed to the action hooks.
		 *
		 * @return void
		 */
		public function render_service_nav( $qrcdr_tabs, $form_id, $getsection, $hook_data ) {
			$allowed_tags   = qrcdr_plugin()->get_allowed_svg_tags();
			$qrcdr_tab_data = qrcdr_blueprint()->get_tabs();
			$qrcdr_icons    = qrcdr_icons()->get_icons();
			?>
			<div class="qrcdr-features col-12">
				<div class="qrcdr-scrolling-nav-component">
					<div class="qrcdr-scrolling-nav-wrapper">
						<button class="btn btn-glass qrcdr-scroll-btn qrcdr-scroll-btn-left" type="button" aria-label="Prev">
							<?php qrcdr_icons()->the_icon( 'ui', 'chevron-left' ); ?>
						</button>
						<div class="qrcdr-scrolling-nav">
							<ul class="nav nav-pills flex-nowrap" role="tablist">
								<?php
								do_action( 'qrcdr_wp_before_nav_services', $hook_data );

								foreach ( $qrcdr_tabs as $tab_key ) {
									if ( ! isset( $qrcdr_tab_data[ $tab_key ] ) ) {
										continue;
									}

									$current_tab = $qrcdr_tab_data[ $tab_key ];
									$svg = isset( $qrcdr_icons['services'][ $tab_key ] ) ? $qrcdr_icons['services'][ $tab_key ] : '';

									$this->render_service_nav_item( $current_tab, $tab_key, $form_id, $svg, $allowed_tags, $getsection );
								}

								do_action( 'qrcdr_wp_after_nav_services', $hook_data );
								?>
							</ul>
						</div>
						<button class="btn btn-glass qrcdr-scroll-btn qrcdr-scroll-btn-right" type="button" aria-label="Next">
							<?php qrcdr_icons()->the_icon( 'ui', 'chevron-right' ); ?>
						</button>
					</div>
				</div>
			</div>
			<?php
		}

		/**
		 * Renders an individual service navigation tab item.
		 *
		 * @param array  $current_tab   Data for the current tab (e.g., 'label').
		 * @param string $tab_key       The unique key for the service/tab.
		 * @param string $form_id       The unique identifier for the form.
		 * @param string $svg           The SVG icon markup.
		 * @param array  $allowed_tags  The allowed HTML tags for SVG sanitization.
		 * @param string $getsection    The currently active section selector.
		 *
		 * @return void
		 */
		public function render_service_nav_item( $current_tab, $tab_key, $form_id, $svg, $allowed_tags, $getsection ) {
			$section_class = '.qrcdr-' . $tab_key;
			$active_class  = ( $section_class === $getsection ) ? ' active' : '';
			?>
			<li class="nav-item">
				<button
					id="qrcdr-tab-<?php echo esc_attr( $tab_key ); ?>-<?php echo esc_attr( $form_id ); ?>" 
					class="nav-link<?php echo esc_attr( $active_class ); ?>"
					data-bs-target="#qrcdr-<?php echo esc_attr( $tab_key ); ?>-<?php echo esc_attr( $form_id ); ?>"
					type="button"
					role="tab"
					aria-controls="qrcdr-<?php echo esc_attr( $tab_key ); ?>-<?php echo esc_attr( $form_id ); ?>"
					aria-selected="<?php echo $active_class ? 'true' : 'false'; ?>"
					data-bs-toggle="tab"
					data-section="<?php echo esc_attr( $section_class ); ?>">
					<?php echo wp_kses( $svg, $allowed_tags ); ?>
					<span class="d-inline-block"><?php echo esc_html( $current_tab['label'] ); ?></span>
				</button>
			</li>
			<?php
		}

		/**
		 * Renders the single Service tab
		 *
		 * @param array  $current_tab Current tab.
		 * @param string $tab_key  The tab key.
		 * @param string $form_id         The unique identifier for the form.
		 * @param bool   $getsection      The current section.
		 *
		 * @return void
		 */
		public function render_service( $current_tab, $tab_key, $form_id, $getsection ) {
			$is_active = ( ".qrcdr-{$tab_key}" === $getsection );
			$active_class = $is_active ? ' show active' : '';
			$first_template_path = plugin_dir_path( __DIR__ ) . 'template-parts/services/tab-' . $tab_key . '.php';
			$template_path = apply_filters( 'qrcdr_tab_template_path', $first_template_path, $tab_key );
			if ( file_exists( $template_path ) ) {
				$qrcdr_activesection = $active_class;
				include $template_path;
			}
		}

		/**
		 * Renders the single Input
		 *
		 * @param string $input The input.
		 */
		public function render_input( $input ) {
			$type  = isset( $input['type'] ) ? $input['type'] : 'text';
			$class = isset( $input['class'] ) ? ' ' . $input['class'] : '';

			$field = '';

			$skip_label = array( 'checkbox', 'switch', 'range' );

			$label = isset( $input['label'] ) ? $input['label'] : '';

			if ( strlen( $label ) && ! in_array( $type, $skip_label ) ) {
				$field .= '<label>' . esc_html( $input['label'] ) . '</label>';
			}

			$name = isset( $input['name'] ) ? $input['name'] : false;
			$name_attr = $name ? ' name="' . esc_attr( $name ) . '"' : '';

			$attributes = '';

			if ( isset( $input['attributes'] ) && is_array( $input['attributes'] ) ) {
				foreach ( $input['attributes'] as $attr_name => $attr_value ) {
					$attributes .= ' ' . esc_attr( $attr_name ) . '="' . esc_attr( $attr_value ) . '"';
				}
			}

			$value = isset( $input['default'] ) ? esc_attr( $input['default'] ) : '';

			$data_default = strlen( $value ) ? ' data-qrcdr-default="' . $value . '"' : '';

			switch ( $type ) {
				case 'textarea':
					$value = isset( $input['default'] ) ? esc_textarea( $input['default'] ) : '';
					$field .= '<textarea class="form-control' . esc_attr( $class ) . '"' . $name_attr . $attributes . $data_default . '>' . $value . '</textarea>';
					break;

				case 'checkbox':
					$unique_id = wp_unique_id( 'qrcdr-checkbox-' );
					$field .= '<div class="form-check">';
					$field .= '<input type="checkbox" class="form-check-input" id="' . esc_attr( $unique_id ) . '" ' . $name_attr . checked( $value, '1', false ) . $data_default . '>';
					$field .= '<label class="form-check-label" for="' . esc_attr( $unique_id ) . '">' . esc_html( $label ) . '</label>';
					$field .= '</div>';
					break;

				case 'switch':
					$unique_id = wp_unique_id( 'qrcdr-switch-' );
					$field .= '<div class="form-check form-switch mb-2">';
					$field .= '<input type="checkbox" class="form-check-input" id="' . esc_attr( $unique_id ) . '" ' . $name_attr . checked( $value, '1', false ) . $data_default . ' autocomplete="off">';
					$field .= '<label class="form-check-label" for="' . esc_attr( $unique_id ) . '">' . esc_html( $label ) . '</label>';
					$field .= '</div>';
					break;

				case 'radio':
					if ( isset( $input['options'] ) && is_array( $input['options'] ) ) {
						foreach ( $input['options'] as $option_value => $option_label ) {
							$unique_id = wp_unique_id( 'qrcdr-radio-' );
							$field .= '<div class="form-check form-check-inline">';
							$field .= '<input type="radio" class="form-check-input" value="' . esc_attr( $option_value ) . '" id="' . esc_attr( $unique_id ) . '" ' . $name_attr . checked( $value, $option_value, false ) . $data_default . ' autocomplete="off">';
							$field .= '<label class="form-check-label" for="' . esc_attr( $unique_id ) . '">' . esc_html( $option_label ) . '</label>';
							$field .= '</div>';
						}
					}
					break;

				case 'select':
					$field .= '<select class="form-select' . esc_attr( $class ) . '"' . $name_attr . $attributes . $data_default . '>';
					if ( isset( $input['options'] ) && is_array( $input['options'] ) ) {
						foreach ( $input['options'] as $option_value => $option_label ) {
							$field .= '<option value="' . esc_attr( $option_value ) . '" ' . selected( $value, $option_value, false ) . '>' . esc_html( $option_label ) . '</option>';
						}
					}
					$field .= '</select>';
					break;

				case 'range':
					$field .= '<div class="qrcdr-slider">';
					$field .= '<label class="d-flex justify-content-between">' . esc_html( $label ) . ' <span class="small qrcdr-slider-value">' . esc_attr( $value ) . '</span></label>';
					$field .= '<input type="' . esc_attr( $type ) . '" value="' . esc_attr( $value ) . '" class="qrcdr-slider-input"' . $name_attr . $attributes . $data_default . '>';
					$field .= '</div>';
					break;

				case 'countrycodes':
					$field .= '<select class="form-select' . esc_attr( $class ) . '"' . $name_attr . $attributes . $data_default . '>';
					$field .= qrcdr_plugin()->country_code_options();
					$field .= '</select>';
					break;

				case 'datepicker':
					$unique_id = wp_unique_id( 'qrcdr-time-' );
					$field .= '<input type="text" class="form-control qrcdr-datepicker' . esc_attr( $class ) . '" data-timestamp="#' . esc_attr( $unique_id ) . '"' . $name_attr . $attributes . ' autocomplete="off">';
					$field .= '<input type="hidden" class="get-timestamp" value="' . esc_attr( $value ) . '" id="' . esc_attr( $unique_id ) . '" autocomplete="off">';
					break;

				case 'color':
					$unique_id = wp_unique_id( 'qrcdr-time-' );
					$field .= '<input type="text" value="' . esc_attr( $value ) . '" class="form-control qrcolorpicker' . esc_attr( $class ) . '" id="' . esc_attr( $unique_id ) . '"' . $name_attr . $attributes . $data_default . '>';
					break;

				case 'media':
					$field .= '<div class="qrcdr-media-picker"><button type="button" class="btn btn-sm btn-outline-primary open-media-picker-btn d-flex align-items-center" data-target-input="' . $name . '" ' . $attributes . '>' . qrcdr_icons()->get_the_icon( 'ui', 'plus_lg' ) . '<span class="ms-1">' . esc_html__( 'Select File', 'qrcdr' ) . '</span></button>';
					$field .= '<button type="button" class="btn btn-link btn-sm text-danger qrcdr-remove-image" style="display: none;">' . esc_html__( 'Remove', 'qrcdr-pro' ) . '</button><span class="qrcdr_attachment_filename small"></span>';
					$field .= '<input type="hidden" value="' . esc_attr( $value ) . '" class="qrcdr_attachment_source"' . $name_attr . $data_default . '></div>';
					break;

				case 'media_list':
					$field .= '<div class="qrcdr-gallery-images-list mb-3"></div><button type="button" class="btn btn-sm btn-outline-primary open-media-picker-btn d-flex align-items-center" ' . $attributes . '>' . qrcdr_icons()->get_the_icon( 'ui', 'plus_lg' ) . '<span class="ms-1">' . esc_html__( 'Select File', 'qrcdr' ) . '</span></button>';
					$field .= '<input type="hidden" value="' . esc_attr( $value ) . '" class="qrcdr_attachment_source"' . $name_attr . $data_default . '>';
					break;

				default:
					// Input standard (text, email, link, ecc.).
					$value_attr = isset( $input['default'] ) ? ' value="' . esc_attr( $input['default'] ) . '"' : '';
					$field .= '<input type="' . esc_attr( $type ) . '" value="' . esc_attr( $value ) . '" class="form-control' . esc_attr( $class ) . '"' . $name_attr . $attributes . $data_default . '>';
					break;
			}
			return $field;
		}

		/**
		 * Echo the input.
		 *
		 * @param string $input The input.
		 */
		public function the_input( $input ) {
			$output = $this->render_input( $input );
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $output;
		}

		/**
		 * Renders the accordion container for the features settings.
		 *
		 * @param array  $qrcdr_features  List of feature keys to be rendered.
		 * @param string $form_id         The unique identifier for the form.
		 * @param bool   $single          Whether to allow only one item open at a time (data-bs-parent).
		 * @param string $collapsed       The default state class (e.g., ' show' or empty).
		 *
		 * @return void
		 */
		public function render_feature_accordion( $qrcdr_features, $form_id, $single, $collapsed ) {
			$available_features = qrcdr_blueprint()->get_features();
			$accordion_parent = $single ? "#QRCDRcollapseSettings-{$form_id}" : '';
			?>
			<div class="accordion qrcdr-options-collapse" id="QRCDRcollapseSettings-<?php echo esc_attr( $form_id ); ?>">
				<?php
				$feature_count = 0;
				foreach ( $qrcdr_features as $feature_key ) :
					if ( ! isset( $available_features[ $feature_key ] ) ) {
						continue;
					}
					$feature_count++;
					$feature = $available_features[ $feature_key ];
					$is_show = ( $single && 1 !== $feature_count ) ? '' : $collapsed;
					$this->render_feature( $feature, $feature_key, $form_id, $is_show, $accordion_parent );
				endforeach;
				?>
			</div>
			<?php
		}

		/**
		 * Renders a single feature item (button and collapsible content).
		 *
		 * @param array  $feature            Array containing feature details like 'label'.
		 * @param string $feature_key        The unique key of the feature.
		 * @param string $form_id            The unique identifier for the form.
		 * @param string $is_show            The CSS class to handle visibility (' show' or empty).
		 * @param string $accordion_parent   The ID of the parent accordion for Bootstrap's toggle logic.
		 *
		 * @return void
		 */
		public function render_feature( $feature, $feature_key, $form_id, $is_show, $accordion_parent ) {
			$collapse_id = 'collapse' . ucfirst( $feature_key ) . "-{$form_id}";
			$collapsed = strlen( $is_show ) ? '' : ' collapsed';
			?>
			<div class="accordion-item pb-2" data-qrcdr-feature="<?php echo esc_attr( $feature_key ); ?>">
				<div class="d-grid">
					<button class="accordion-button text-primary<?php echo esc_attr( $collapsed ); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?php echo esc_attr( $collapse_id ); ?>">
						<?php qrcdr_icons()->the_icon( 'features', $feature_key ); ?> <span class="vertical-middle ms-2"><?php echo esc_html( $feature['label'] ); ?></span>
					</button>
				</div>
				<div class="collapse<?php echo esc_attr( $is_show ); ?>" id="<?php echo esc_attr( $collapse_id ); ?>" <?php echo $accordion_parent ? 'data-bs-parent="' . esc_attr( $accordion_parent ) . '"' : ''; ?>>
					<?php
					$first_template_path = plugin_dir_path( __DIR__ ) . 'template-parts/features/feature-' . $feature_key . '.php';
					$template_path = apply_filters( 'qrcdr_feature_template_path', $first_template_path, $feature_key );

					if ( file_exists( $template_path ) ) {
						include $template_path;
					}
					?>
				</div>
			</div>
			<?php
		}
	}
}
