<?php
/**
 * Tooto Simple Splide Widget
 */

namespace Tooto_Elementor\Widgets;

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

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

class Simple_Splide extends Widget_Base {
	public function get_name(): string {
		return 'tooto-simple-splide';
	}

	public function get_title(): string {
		return __( 'Tooto Simple Splide', 'tooto-elementor' );
	}

	public function get_icon(): string {
		return 'eicon-slider-album';
	}

	public function get_categories(): array {
		return [ 'tooto' ];
	}

	public function get_keywords(): array {
		return [ 'carousel', 'image', 'slider', 'splide', '轮播', '简单' ];
	}

	public function get_style_depends(): array {
		return [ 'tooto-simple-splide-css' ];
	}

	protected function register_controls(): void {
		// Content Section
		$this->start_controls_section(
			'section_content',
			[
				'label' => __( 'Slides', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'source_type',
			[
				'label'   => __( 'Source Type', 'tooto-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'manual',
				'options' => [
					'manual' => __( 'Manual', 'tooto-elementor' ),
					'scf'    => __( 'SCF Gallery (Meta)', 'tooto-elementor' ),
				],
			]
		);

		$this->add_control(
			'scf_key',
			[
				'label'       => __( 'Meta Key / Data', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'dynamic'     => [
					'active'     => true,
					'categories' => [
						\Elementor\Modules\DynamicTags\Module::TEXT_CATEGORY,
						\Elementor\Modules\DynamicTags\Module::GALLERY_CATEGORY,
						\Elementor\Modules\DynamicTags\Module::IMAGE_CATEGORY,
					],
				],
				'description' => __( 'Enter the meta key (e.g., "my_gallery") OR use Dynamic Tags to retrieve the gallery data directly.', 'tooto-elementor' ),
				'condition'   => [
					'source_type' => 'scf',
				],
			]
		);

		$repeater = new \Elementor\Repeater();

		$repeater->add_control(
			'image',
			[
				'label' => __( 'Image', 'tooto-elementor' ),
				'type' => Controls_Manager::MEDIA,
				'default' => [
					'url' => \Elementor\Utils::get_placeholder_image_src(),
				],
			]
		);

		$repeater->add_control(
			'link',
			[
				'label' => __( 'Link', 'tooto-elementor' ),
				'type' => Controls_Manager::URL,
				'placeholder' => __( 'https://your-link.com', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'slides',
			[
				'label' => __( 'Slides', 'tooto-elementor' ),
				'type' => Controls_Manager::REPEATER,
				'fields' => $repeater->get_controls(),
				'default' => [
					[
						'image' => [
							'url' => \Elementor\Utils::get_placeholder_image_src(),
						],
					],
					[
						'image' => [
							'url' => \Elementor\Utils::get_placeholder_image_src(),
						],
					],
					[
						'image' => [
							'url' => \Elementor\Utils::get_placeholder_image_src(),
						],
					],
				],
				'title_field' => 'Slide',
				'condition'   => [
					'source_type' => 'manual',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			[
				'name' => 'image_size',
				'default' => 'full',
				'separator' => 'none',
			]
		);

		$this->end_controls_section();

		// Settings Section
		$this->start_controls_section(
			'section_settings',
			[
				'label' => __( 'Settings', 'tooto-elementor' ),
			]
		);

		$this->add_responsive_control(
			'slides_per_view',
			[
				'label' => __( 'Slides Per View', 'tooto-elementor' ),
				'type' => Controls_Manager::NUMBER,
				'step' => 0.1,
				'default' => 3,
				'tablet_default' => 2,
				'mobile_default' => 1,
			]
		);

		$this->add_responsive_control(
			'slides_to_scroll',
			[
				'label' => __( 'Slides to Scroll', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT,
				'default' => '1',
				'options' => [
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
				],
			]
		);

		$this->add_responsive_control(
			'gap',
			[
				'label' => __( 'Gap', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'default' => [
					'size' => 20,
				],
				'range' => [
					'px' => [
						'min' => 0,
						'max' => 100,
					],
				],
			]
		);

		$this->add_control(
			'infinite_loop',
			[
				'label' => __( 'Infinite Loop', 'tooto-elementor' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => 'yes',
			]
		);

		$this->add_responsive_control(
			'center_mode',
			[
				'label' => __( 'Center Mode', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT,
				'default' => 'yes',
				'options' => [
					'yes' => __( 'Yes', 'tooto-elementor' ),
					''    => __( 'No', 'tooto-elementor' ),
				],
			]
		);

		$this->add_control(
			'autoplay',
			[
				'label' => __( 'Autoplay', 'tooto-elementor' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => 'yes',
			]
		);

		$this->add_control(
			'autoplay_speed',
			[
				'label' => __( 'Autoplay Speed (ms)', 'tooto-elementor' ),
				'type' => Controls_Manager::NUMBER,
				'default' => 3000,
				'condition' => [
					'autoplay' => 'yes',
				],
			]
		);

		$this->add_control(
			'pause_on_hover',
			[
				'label' => __( 'Pause on Hover', 'tooto-elementor' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => 'yes',
				'condition' => [
					'autoplay' => 'yes',
				],
			]
		);

		$this->add_control(
			'show_arrows',
			[
				'label' => __( 'Show Arrows', 'tooto-elementor' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => 'yes',
			]
		);

		$this->add_control(
			'arrow_prev_icon',
			[
				'label' => __( 'Previous Icon', 'tooto-elementor' ),
				'type' => Controls_Manager::ICONS,
				'default' => [
					'value' => 'fas fa-angle-left',
					'library' => 'fa-solid',
				],
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'arrow_next_icon',
			[
				'label' => __( 'Next Icon', 'tooto-elementor' ),
				'type' => Controls_Manager::ICONS,
				'default' => [
					'value' => 'fas fa-angle-right',
					'library' => 'fa-solid',
				],
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'show_pagination',
			[
				'label' => __( 'Show Pagination', 'tooto-elementor' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => 'yes',
			]
		);

		$this->end_controls_section();

		// Style Section
		$this->start_controls_section(
			'section_style_slides',
			[
				'label' => __( 'Slides', 'tooto-elementor' ),
				'tab' => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'slide_border_radius',
			[
				'label' => __( 'Border Radius', 'tooto-elementor' ),
				'type' => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors' => [
					'{{WRAPPER}} .tooto-simple-splide__image img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->end_controls_section();

		// Arrows Style
		$this->start_controls_section(
			'section_style_arrows',
			[
				'label' => __( 'Arrows', 'tooto-elementor' ),
				'tab' => Controls_Manager::TAB_STYLE,
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'arrow_color',
			[
				'label' => __( 'Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .splide__arrow' => 'color: {{VALUE}};',
					'{{WRAPPER}} .splide__arrow svg' => 'fill: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'arrow_bg_color',
			[
				'label' => __( 'Background Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .splide__arrow' => 'background: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'arrow_size',
			[
				'label' => __( 'Size', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'selectors' => [
					'{{WRAPPER}} .splide__arrow' => 'width: {{SIZE}}px; height: {{SIZE}}px; font-size: {{SIZE}}px;',
				],
			]
		);

		$this->end_controls_section();

		// Pagination Style
		$this->start_controls_section(
			'section_style_pagination',
			[
				'label' => __( 'Pagination', 'tooto-elementor' ),
				'tab' => Controls_Manager::TAB_STYLE,
				'condition' => [
					'show_pagination' => 'yes',
				],
			]
		);

		$this->add_control(
			'pagination_spacing',
			[
				'label' => __( 'Spacing Top', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'default' => [
					'size' => 20,
				],
				'selectors' => [
					'{{WRAPPER}} .splide__pagination' => 'margin-top: {{SIZE}}px;',
				],
			]
		);

		$this->add_control(
			'pagination_color',
			[
				'label' => __( 'Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'default' => '#ccc',
				'selectors' => [
					'{{WRAPPER}} .splide__pagination__page' => 'background: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'pagination_active_color',
			[
				'label' => __( 'Active Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'default' => '#000',
				'selectors' => [
					'{{WRAPPER}} .splide__pagination__page.is-active' => 'background: {{VALUE}};',
				],
			]
		);
		
		$this->add_responsive_control(
			'pagination_dot_size',
			[
				'label' => __( 'Dot Size', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'default' => [
					'size' => 8,
				],
				'selectors' => [
					'{{WRAPPER}} .splide__pagination__page' => 'width: {{SIZE}}px; height: {{SIZE}}px;',
					'{{WRAPPER}} .splide__pagination__page.is-active' => 'height: {{SIZE}}px;', // Active width is handled by specific 24px rule, but height should match
				],
			]
		);

		$this->add_control(
			'arrow_style_heading',
			[
				'label' => __( 'Arrows Style', 'tooto-elementor' ),
				'type' => Controls_Manager::HEADING,
				'separator' => 'before',
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->start_controls_tabs( 'arrow_style_tabs' );

		$this->start_controls_tab(
			'arrow_style_normal',
			[
				'label' => __( 'Normal', 'tooto-elementor' ),
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'arrow_bg_color',
			[
				'label' => __( 'Background Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'default' => 'rgba(255, 255, 255, 0.8)',
				'selectors' => [
					'{{WRAPPER}} .splide__arrow' => 'background: {{VALUE}};',
				],
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'arrow_icon_color',
			[
				'label' => __( 'Icon Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'default' => '#000000',
				'selectors' => [
					'{{WRAPPER}} .splide__arrow svg' => 'fill: {{VALUE}};',
					'{{WRAPPER}} .splide__arrow i' => 'color: {{VALUE}};',
				],
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'arrow_style_hover',
			[
				'label' => __( 'Hover', 'tooto-elementor' ),
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'arrow_bg_color_hover',
			[
				'label' => __( 'Background Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .splide__arrow:hover' => 'background: {{VALUE}};',
				],
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->add_control(
			'arrow_icon_color_hover',
			[
				'label' => __( 'Icon Color', 'tooto-elementor' ),
				'type' => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .splide__arrow:hover svg' => 'fill: {{VALUE}};',
					'{{WRAPPER}} .splide__arrow:hover i' => 'color: {{VALUE}};',
				],
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

		$this->add_control(
			'arrow_size',
			[
				'label' => __( 'Arrow Size', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'size_units' => [ 'px' ],
				'range' => [
					'px' => [
						'min' => 20,
						'max' => 100,
					],
				],
				'default' => [
					'size' => 40,
				],
				'selectors' => [
					'{{WRAPPER}} .splide__arrow' => 'width: {{SIZE}}px; height: {{SIZE}}px;',
				],
				'separator' => 'before',
				'condition' => [
					'show_arrows' => 'yes',
				],
			]
		);


		$this->end_controls_section();
	}

	protected function render(): void {
				$settings = $this->get_settings_for_display();
				$slides   = [];

				if ( 'scf' === $settings['source_type'] && ! empty( $settings['scf_key'] ) ) {
					$slides = $this->get_scf_slides( $settings['scf_key'] );
				} elseif ( ! empty( $settings['slides'] ) ) {
					$slides = $settings['slides'];
				}

				if ( empty( $slides ) ) {
					return;
				}

				// Prepare Splide Options
				$splide_options = [
					'type'       => 'yes' === $settings['infinite_loop'] ? 'loop' : 'slide',
					'perPage'    => (float) $settings['slides_per_view'],
					'perMove'    => (int) $settings['slides_to_scroll'],
					'gap'        => isset($settings['gap']['size']) ? $settings['gap']['size'] . 'px' : '20px',
					'autoplay'   => 'yes' === $settings['autoplay'],
					'interval'   => (int) $settings['autoplay_speed'],
					'pauseOnHover' => 'yes' === $settings['pause_on_hover'],
					'arrows'     => 'yes' === $settings['show_arrows'],
					'pagination' => 'yes' === $settings['show_pagination'],
					'autoScroll' => false, // Explicitly disable marquee mode
					'breakpoints' => [
						1024 => [
							'perPage' => (float) ( ! empty( $settings['slides_per_view_tablet'] ) ? $settings['slides_per_view_tablet'] : 2 ),
							'perMove' => (int) ( ! empty( $settings['slides_to_scroll_tablet'] ) ? $settings['slides_to_scroll_tablet'] : 1 ),
							'gap'     => isset($settings['gap_tablet']['size']) ? $settings['gap_tablet']['size'] . 'px' : '15px',
						],
						767 => [
							'perPage' => (float) ( ! empty( $settings['slides_per_view_mobile'] ) ? $settings['slides_per_view_mobile'] : 1 ),
							'perMove' => (int) ( ! empty( $settings['slides_to_scroll_mobile'] ) ? $settings['slides_to_scroll_mobile'] : 1 ),
							'gap'     => isset($settings['gap_mobile']['size']) ? $settings['gap_mobile']['size'] . 'px' : '10px',
						],
					],
				];

				// Handle Responsive Center Mode
				$center_desktop = $settings['center_mode'];
				$center_tablet = ! empty( $settings['center_mode_tablet'] ) ? $settings['center_mode_tablet'] : $center_desktop;
				$center_mobile = ! empty( $settings['center_mode_mobile'] ) ? $settings['center_mode_mobile'] : $center_tablet;

				// Desktop (Root)
				if ( 'yes' === $center_desktop ) {
					$splide_options['focus'] = 'center';
					$splide_options['trimSpace'] = false;
				} else {
					$splide_options['focus'] = 0; // Left align
					$splide_options['trimSpace'] = true; // Allow trimming
				}

				// Tablet Override
				if ( $center_tablet !== $center_desktop ) {
					$splide_options['breakpoints'][1024]['focus'] = 'yes' === $center_tablet ? 'center' : 0;
					$splide_options['breakpoints'][1024]['trimSpace'] = 'yes' !== $center_tablet;
				}

				// Mobile Override
				// Always set for mobile if we want to be explicit, or check difference
				// Checking difference against Tablet is safer for inheritance chain logic
				if ( $center_mobile !== $center_tablet ) {
					$splide_options['breakpoints'][767]['focus'] = 'yes' === $center_mobile ? 'center' : 0;
					$splide_options['breakpoints'][767]['trimSpace'] = 'yes' !== $center_mobile;
				}

				$this->add_render_attribute( 'wrapper', 'class', 'tooto-simple-splide-widget' );
				$this->add_render_attribute( 'wrapper', 'class', 'splide' );
				$this->add_render_attribute( 'wrapper', 'data-splide', wp_json_encode( $splide_options ) );

				?>
				<div <?php $this->print_render_attribute_string( 'wrapper' ); ?>>
					<?php if ( 'yes' === $settings['show_arrows'] ) : ?>
						<div class="splide__arrows">
							<button class="splide__arrow splide__arrow--prev">
								<?php \Elementor\Icons_Manager::render_icon( $settings['arrow_prev_icon'], [ 'aria-hidden' => 'true' ] ); ?>
							</button>
							<button class="splide__arrow splide__arrow--next">
								<?php \Elementor\Icons_Manager::render_icon( $settings['arrow_next_icon'], [ 'aria-hidden' => 'true' ] ); ?>
							</button>
						</div>
					<?php endif; ?>

					<div class="splide__track">
						<ul class="splide__list">
							<?php foreach ( $slides as $index => $slide ) : ?>
								<li class="splide__slide tooto-simple-splide-widget__slide">
									<div class="tooto-simple-splide-widget__image">
										<?php
										if ( ! empty( $slide['link']['url'] ) ) {
											$this->add_link_attributes( 'slide_link_' . $index, $slide['link'] );
											echo '<a ' . $this->get_render_attribute_string( 'slide_link_' . $index ) . '>';
										}

										// Merge global image size settings into slide settings
										$slide_settings = $slide;
										if ( isset( $settings['image_size_size'] ) ) {
											$slide_settings['image_size_size'] = $settings['image_size_size'];
										}
										if ( isset( $settings['image_size_custom_dimension'] ) ) {
											$slide_settings['image_size_custom_dimension'] = $settings['image_size_custom_dimension'];
										}

										echo \Elementor\Group_Control_Image_Size::get_attachment_image_html( $slide_settings, 'image_size', 'image' );

										if ( ! empty( $slide['link']['url'] ) ) {
											echo '</a>';
										}
										?>
									</div>
								</li>
							<?php endforeach; ?>
						</ul>
					</div>
				</div>
				<?php
			}

			private function get_scf_slides( $source ): array {
				if ( empty( $source ) ) {
					return [];
				}

				// If source is already an array, use it directly (Dynamic Tag returned data)
				if ( is_array( $source ) ) {
					return $this->process_ids( $source );
				}

				// If source is a string
				if ( is_string( $source ) ) {
					// Check if it looks like a list of IDs (e.g. "123,456" or "123")
					// Using regex to check if it contains only numbers and commas
					if ( preg_match( '/^[\d,]+$/', $source ) ) {
						// Treat as data
						return $this->process_ids( explode( ',', $source ) );
					} else {
						// Treat as Meta Key
						$post_id = get_the_ID();
						if ( ! $post_id ) {
							return [];
						}
						$meta = get_post_meta( $post_id, $source, true );
						return $this->get_scf_slides( $meta ); // Recursive call to handle the meta value
					}
				}

				return [];
			}

			private function process_ids( array $ids ): array {
				$slides = [];
				foreach ( $ids as $val ) {
					$id = 0;

					// Handle Elementor Gallery Tag format (array of objects with 'id')
					if ( is_array( $val ) && isset( $val['id'] ) ) {
						$id = (int) $val['id'];
					} elseif ( is_numeric( $val ) ) {
						$id = (int) $val;
					}

					if ( ! $id ) {
						continue;
					}

					$url = wp_get_attachment_image_url( $id, 'full' );
					if ( ! $url ) {
						continue;
					}
					$slides[] = [
						'image' => [
							'id'  => $id,
							'url' => $url,
						],
						'link' => [
							'url' => '',
						],
					];
				}
				return $slides;
			}
}
