<?php
/**
 * A reusable Elementor trait for adding a comprehensive set of Swiper.js carousel controls
 * and generating the final options object for the frontend.
 *
 * @package Sifency\Traits
 */

namespace Sifency\Traits;

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

use Elementor\Controls_Manager;
use Sifency\Traits\Sifency_Addons_Slider_Nav;
use Sifency\Traits\Sifency_Addons_Swiper_Slider_Pagination;

trait Sifency_Addons_Slider_Controls {
	use Sifency_Addons_Slider_Nav;
	use Sifency_Addons_Swiper_Slider_Pagination;

	protected function add_sifency_addons_slider_controls( array $args = array() ) {
		$args = wp_parse_args(
			$args,
			array(
				'label'     => esc_html__( 'Carousel Settings', 'sifency-addons' ),
				'condition' => array(),
			)
		);
		$this->start_controls_section( 'section_carousel_settings', $args );
		$this->add_responsive_control(
			'slides_per_view',
			array(
				'label'              => esc_html__( 'Slides Per View', 'sifency-addons' ),
				'type'               => Controls_Manager::NUMBER,
				'min'                => 1,
				'max'                => 10,
				'default'            => 3,
				'tablet_default'     => 2,
				'mobile_default'     => 1,
				'frontend_available' => true,
			)
		);
		$this->add_responsive_control(
			'space_between',
			array(
				'label'              => esc_html__( 'Space Between (px)', 'sifency-addons' ),
				'type'               => Controls_Manager::NUMBER,
				'default'            => 30,
				'tablet_default'     => 20,
				'mobile_default'     => 10,
				'frontend_available' => true,
			)
		);
		$this->add_control(
			'effect',
			array(
				'label'              => esc_html__( 'Effect', 'sifency-addons' ),
				'type'               => Controls_Manager::SELECT,
				'options'            => array(
					'slide'     => esc_html__( 'Slide', 'sifency-addons' ),
					'fade'      => esc_html__( 'Fade', 'sifency-addons' ),
					'cube'      => esc_html__( 'Cube', 'sifency-addons' ),
					'coverflow' => esc_html__( 'Coverflow', 'sifency-addons' ),
					'flip'      => esc_html__( 'Flip', 'sifency-addons' ),
				),
				'default'            => 'slide',
				'frontend_available' => true,
				'help'               => esc_html__( 'Note: The "Fade", "Cube", and "Flip" effects work best with Slides Per View set to 1.', 'sifency-addons' ),
			)
		);

		$this->add_responsive_control(
			'slides_alignment',
			array(
				'label'              => esc_html__( 'Slides Alignment', 'sifency-addons' ),
				'type'               => Controls_Manager::CHOOSE,
				'options'            => array(
					'left'   => array(
						'title' => esc_html__( 'Left', 'sifency-addons' ),
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => esc_html__( 'Center', 'sifency-addons' ),
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'sifency-addons' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'            => 'left',
				'frontend_available' => true,
			)
		);

		$this->add_control(
			'speed',
			array(
				'label'              => esc_html__( 'Speed (ms)', 'sifency-addons' ),
				'type'               => Controls_Manager::NUMBER,
				'default'            => 500,
				'frontend_available' => true,
			)
		);
		$this->add_control(
			'autoplay',
			array(
				'label'              => esc_html__( 'Autoplay', 'sifency-addons' ),
				'type'               => Controls_Manager::SWITCHER,
				'default'            => 'yes',
				'frontend_available' => true,
			)
		);
		$this->add_control(
			'autoplay_delay',
			array(
				'label'              => esc_html__( 'Autoplay Delay (ms)', 'sifency-addons' ),
				'type'               => Controls_Manager::NUMBER,
				'default'            => 5000,
				'condition'          => array( 'autoplay' => 'yes' ),
				'frontend_available' => true,
			)
		);
		$this->add_control(
			'loop',
			array(
				'label'              => esc_html__( 'Infinite Loop', 'sifency-addons' ),
				'type'               => Controls_Manager::SWITCHER,
				'default'            => 'yes',
				'frontend_available' => true,
			)
		);
		$this->add_control(
			'pause_on_hover',
			array(
				'label'              => esc_html__( 'Pause on Hover', 'sifency-addons' ),
				'type'               => Controls_Manager::SWITCHER,
				'default'            => 'yes',
				'frontend_available' => true,
			)
		);

		$this->add_control( 'hr_nav', array( 'type' => Controls_Manager::DIVIDER ) );

		$this->add_control(
			'show_arrows',
			array(
				'label'              => esc_html__( 'Navigation Arrows', 'sifency-addons' ),
				'type'               => Controls_Manager::SWITCHER,
				'default'            => 'no',
				'frontend_available' => true,
			)
		);

		$this->add_control(
			'arrow_prev_icon',
			array(
				'label'     => esc_html__( 'Previous Icon', 'sifency-addons' ),
				'type'      => Controls_Manager::ICONS,
				'default'   => array(
					'value'   => 'icon-left-open-big',
					'library' => 'sifency-icons',
				),
				'condition' => array( 'show_arrows' => 'yes' ),
			)
		);

		$this->add_control(
			'arrow_next_icon',
			array(
				'label'     => esc_html__( 'Next Icon', 'sifency-addons' ),
				'type'      => Controls_Manager::ICONS,
				'default'   => array(
					'value'   => 'icon-right-open-big',
					'library' => 'sifency-icons',
				),
				'condition' => array( 'show_arrows' => 'yes' ),
			)
		);
		$this->add_control(
			'show_pagination',
			array(
				'label'              => esc_html__( 'Pagination', 'sifency-addons' ),
				'type'               => Controls_Manager::SELECT,
				'options'            => array(
					''            => esc_html__( 'None', 'sifency-addons' ),
					'bullets'     => esc_html__( 'Bullets', 'sifency-addons' ),
					'fraction'    => esc_html__( 'Fraction', 'sifency-addons' ),
					'progressbar' => esc_html__( 'Progress Bar', 'sifency-addons' ),
				),
				'default'            => '',
				'frontend_available' => true,
			)
		);

		$this->end_controls_section();

		$nav_condition        = array_merge( $args['condition'], array( 'show_arrows' => 'yes' ) );
		$pagination_condition = array_merge( $args['condition'], array( 'show_pagination!' => '' ) );

		$this->add_sifency_addons_slider_nav_style_controls(
			array(
				'condition' => $nav_condition,
			)
		);
		$this->add_sifency_addons_swiper_slider_pagination_style_controls(
			array(
				'condition'               => $pagination_condition,
				'pagination_control_name' => 'show_pagination',
			)
		);
	}

	/**
	 * Processes widget settings and returns a Swiper.js-compatible options object.
	 * Includes "smart loop" logic and fixes for common effect issues.
	 *
	 * @param array $settings The widget's settings array.
	 * @param int   $post_count The total number of slides.
	 * @return array The options array for Swiper.
	 */
	protected function get_sifency_swiper_options( $settings, $post_count = 0 ) {
		$slides_per_view_desktop = isset( $settings['slides_per_view'] ) && '' !== $settings['slides_per_view'] ? (int) $settings['slides_per_view'] : 3;

		$is_loop_enabled = ( 'yes' === ( $settings['loop'] ?? 'yes' ) );
		if ( $post_count > 0 && $post_count <= $slides_per_view_desktop ) {
			$is_loop_enabled = false;
		}

		$options = array(
			'effect'                   => $settings['effect'] ?? 'slide',
			'speed'                    => (int) ( $settings['speed'] ?? 500 ),
			'loop'                     => $is_loop_enabled,
			'watchSlidesProgress'      => true,
			'observer'                 => true,
			'observeParents'           => true,
			'autoHeight'               => true,
			'watchOverflow'            => true,
			'centerInsufficientSlides' => true,
			'grabCursor'               => true,
		);

		// --- Slides Per View Inheritance (Desktop -> Laptop -> Tablet Extra -> Tablet -> Mobile Extra -> Mobile)
		$desktop_spv      = isset( $settings['slides_per_view'] ) && '' !== $settings['slides_per_view'] ? (int) $settings['slides_per_view'] : 3;
		$laptop_spv       = isset( $settings['slides_per_view_laptop'] ) && '' !== $settings['slides_per_view_laptop'] ? (int) $settings['slides_per_view_laptop'] : $desktop_spv;
		$tablet_extra_spv = isset( $settings['slides_per_view_tablet_extra'] ) && '' !== $settings['slides_per_view_tablet_extra'] ? (int) $settings['slides_per_view_tablet_extra'] : $laptop_spv;
		$tablet_spv       = isset( $settings['slides_per_view_tablet'] ) && '' !== $settings['slides_per_view_tablet'] ? (int) $settings['slides_per_view_tablet'] : $tablet_extra_spv;
		$mobile_extra_spv = isset( $settings['slides_per_view_mobile_extra'] ) && '' !== $settings['slides_per_view_mobile_extra'] ? (int) $settings['slides_per_view_mobile_extra'] : $tablet_spv;
		$mobile_spv       = isset( $settings['slides_per_view_mobile'] ) && '' !== $settings['slides_per_view_mobile'] ? (int) $settings['slides_per_view_mobile'] : $mobile_extra_spv;
		$widescreen_spv   = isset( $settings['slides_per_view_widescreen'] ) && '' !== $settings['slides_per_view_widescreen'] ? (int) $settings['slides_per_view_widescreen'] : $desktop_spv;

		// --- Space Between Inheritance
		$desktop_space      = isset( $settings['space_between'] ) && '' !== $settings['space_between'] ? (int) $settings['space_between'] : 30;
		$laptop_space       = isset( $settings['space_between_laptop'] ) && '' !== $settings['space_between_laptop'] ? (int) $settings['space_between_laptop'] : $desktop_space;
		$tablet_extra_space = isset( $settings['space_between_tablet_extra'] ) && '' !== $settings['space_between_tablet_extra'] ? (int) $settings['space_between_tablet_extra'] : $laptop_space;
		$tablet_space       = isset( $settings['space_between_tablet'] ) && '' !== $settings['space_between_tablet'] ? (int) $settings['space_between_tablet'] : $tablet_extra_space;
		$mobile_extra_space = isset( $settings['space_between_mobile_extra'] ) && '' !== $settings['space_between_mobile_extra'] ? (int) $settings['space_between_mobile_extra'] : $tablet_space;
		$mobile_space       = isset( $settings['space_between_mobile'] ) && '' !== $settings['space_between_mobile'] ? (int) $settings['space_between_mobile'] : $mobile_extra_space;
		$widescreen_space   = isset( $settings['space_between_widescreen'] ) && '' !== $settings['space_between_widescreen'] ? (int) $settings['space_between_widescreen'] : $desktop_space;

		// --- Slides Alignment Inheritance
		$desktop_align      = $settings['slides_alignment'] ?? 'left';
		$laptop_align       = $settings['slides_alignment_laptop'] ?? $desktop_align;
		$tablet_extra_align = $settings['slides_alignment_tablet_extra'] ?? $laptop_align;
		$tablet_align       = $settings['slides_alignment_tablet'] ?? $tablet_extra_align;
		$mobile_extra_align = $settings['slides_alignment_mobile_extra'] ?? $tablet_align;
		$mobile_align       = $settings['slides_alignment_mobile'] ?? $mobile_extra_align;
		$widescreen_align   = $settings['slides_alignment_widescreen'] ?? $desktop_align;

		$options['slidesPerView']        = $mobile_spv;
		$options['spaceBetween']         = $mobile_space;
		$options['centeredSlides']       = ( 'center' === $mobile_align );
		$options['centeredSlidesBounds'] = true;
		$options['breakpoints']          = array();

		$active_breakpoints = \Elementor\Plugin::$instance->breakpoints->get_active_breakpoints();
		$swiper_breakpoints = array();

		$mobile_max  = isset( $active_breakpoints['mobile'] ) ? $active_breakpoints['mobile']->get_value() : 767;
		$current_min = $mobile_max + 1; // Usually 768

		if ( isset( $active_breakpoints['mobile_extra'] ) ) {
			$swiper_breakpoints[ $current_min ] = array(
				'slidesPerView'  => $mobile_extra_spv,
				'spaceBetween'   => $mobile_extra_space,
				'centeredSlides' => ( 'center' === $mobile_extra_align ),
			);
			$current_min                        = $active_breakpoints['mobile_extra']->get_value() + 1;
		}

		$swiper_breakpoints[ $current_min ] = array(
			'slidesPerView'  => $tablet_spv,
			'spaceBetween'   => $tablet_space,
			'centeredSlides' => ( 'center' === $tablet_align ),
		);

		$tablet_max  = isset( $active_breakpoints['tablet'] ) ? $active_breakpoints['tablet']->get_value() : 1024;
		$current_min = $tablet_max + 1;

		if ( isset( $active_breakpoints['tablet_extra'] ) ) {
			$swiper_breakpoints[ $current_min ] = array(
				'slidesPerView'  => $tablet_extra_spv,
				'spaceBetween'   => $tablet_extra_space,
				'centeredSlides' => ( 'center' === $tablet_extra_align ),
			);
			$current_min                        = $active_breakpoints['tablet_extra']->get_value() + 1;
		}

		if ( isset( $active_breakpoints['laptop'] ) ) {
			$swiper_breakpoints[ $current_min ] = array(
				'slidesPerView'  => $laptop_spv,
				'spaceBetween'   => $laptop_space,
				'centeredSlides' => ( 'center' === $laptop_align ),
			);
			$current_min                        = $active_breakpoints['laptop']->get_value() + 1;
		}

		$swiper_breakpoints[ $current_min ] = array(
			'slidesPerView'  => $desktop_spv,
			'spaceBetween'   => $desktop_space,
			'centeredSlides' => ( 'center' === $desktop_align ),
		);

		if ( isset( $active_breakpoints['widescreen'] ) ) {
			$swiper_breakpoints[ $active_breakpoints['widescreen']->get_value() ] = array(
				'slidesPerView'  => $widescreen_spv,
				'spaceBetween'   => $widescreen_space,
				'centeredSlides' => ( 'center' === $widescreen_align ),
			);
		}

		$options['breakpoints'] = $swiper_breakpoints;

		if ( in_array( $options['effect'], array( 'fade', 'cube', 'flip' ) ) ) {
			$options['slidesPerView'] = 1;
			$options['spaceBetween']  = 0;
			foreach ( $options['breakpoints'] as $bp => $vals ) {
				$options['breakpoints'][ $bp ]['slidesPerView'] = 1;
				$options['breakpoints'][ $bp ]['spaceBetween']  = 0;
			}
		}

		// --- Autoplay
		if ( 'yes' === ( $settings['autoplay'] ?? 'yes' ) ) {
			$options['autoplay'] = array(
				'delay'                => (int) ( $settings['autoplay_delay'] ?? 5000 ),
				'disableOnInteraction' => ( 'yes' === ( $settings['pause_on_hover'] ?? 'yes' ) ) ? false : true,
			);
		}

		// --- Navigation
		if ( 'yes' === ( $settings['show_arrows'] ?? 'no' ) ) {
			$options['navigation'] = array(
				'nextEl' => '.sifency-slider-nav-next',
				'prevEl' => '.sifency-slider-nav-prev',
			);
		}

		// --- Pagination
		if ( ! empty( $settings['show_pagination'] ) ) {
			$options['pagination'] = array(
				'el'        => '.swiper-pagination',
				'type'      => $settings['show_pagination'],
				'clickable' => ( 'bullets' === $settings['show_pagination'] ),
			);
		}

		return $options;
	}
}
