<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Image_Size;
use Elementor\Repeater;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Query_Arg_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Flex_Controls;
use Sifency\Traits\Sifency_Addons_Section_Header;
use Sifency\Traits\Sifency_Addons_Help_Controls;
use Sifency\Classes\Sifency_Addons_Widget_Base;

class Sifency_Widget_Restaurant_Menu extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Item_Style_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Query_Arg_Controls;
	use Sifency_Addons_Slider_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Flex_Controls;
	use Sifency_Addons_Section_Header;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-restaurant-menu',
			'title'          => 'Restaurant Menu',
			'icon'           => 'eicon-price-list',
			'category'       => 'sifency-advance-widgets',
			'keywords'       => array( 'menu', 'restaurant', 'food', 'price' ),
			'script_depends' => array( 'swiper', 'sifency-rest-menu-style' ),
			'style_depends'  => array( 'sifency-typo-style', 'swiper', 'sifency-frontend-style', 'sifency-rest-menu-style', 'sifency-icon' ),
		);}
	protected function register_controls() {
		$this->add_sifency_addons_section_header_controls();
		$this->start_controls_section( 'section_content', array( 'label' => esc_html__( 'Content', 'sifency-addons' ) ) );

		$this->add_control(
			'source',
			array(
				'label'   => 'Source',
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'posts'  => 'Dynamic Posts (Menu CPT)',
					'custom' => 'Custom Manual List',
				),
				'default' => 'posts',
			)
		);
		$repeater = new Repeater();
		$repeater->add_control(
			'image',
			array(
				'label' => 'Dish Image',
				'type'  => Controls_Manager::MEDIA,
			)
		);
		$repeater->add_control(
			'title',
			array(
				'label'       => 'Dish Name',
				'type'        => Controls_Manager::TEXT,
				'default'     => 'Delicious Dish',
				'label_block' => true,
			)
		);
		$repeater->add_control(
			'description',
			array(
				'label' => 'Description',
				'type'  => Controls_Manager::TEXTAREA,
			)
		);
		$repeater->add_control(
			'price',
			array(
				'label'       => 'Price',
				'type'        => Controls_Manager::TEXT,
				'default'     => '$15.00',
				'description' => 'Enter the full price string (e.g., $15.00)',
			)
		);
		$repeater->add_control(
			'category',
			array(
				'label'       => 'Category Name (For Tabs)',
				'type'        => Controls_Manager::TEXT,
				'default'     => 'Mains',
				'label_block' => true,
				'description' => 'Type a category name (e.g., "Starters"). Items with the same name will be grouped in the same Tab.',
			)
		);

		$repeater->add_control(
			'labels',
			array(
				'label'    => 'Labels/Tags',
				'type'     => Controls_Manager::SELECT2,
				'multiple' => true,
				'options'  => array(
					'vegetarian'  => 'Vegetarian',
					'vegan'       => 'Vegan',
					'gluten_free' => 'Gluten-Free',
					'spicy'       => 'Spicy',
					'new'         => 'New',
					'chef_choice' => 'Chef Choice',
				),
			)
		);

		$repeater->add_control(
			'is_featured',
			array(
				'label' => 'Featured Item?',
				'type'  => Controls_Manager::SWITCHER,
			)
		);

		$this->add_control(
			'menu_items',
			array(
				'label'       => 'Menu Items',
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater->get_controls(),
				'title_field' => '{{{ title }}} - <small>{{{ category }}}</small>',
				'condition'   => array( 'source' => 'custom' ),
			)
		);
		$this->end_controls_section();
		$this->add_sifency_arg_controls(
			array(
				'default_post' => 'restaurant_menu',
				'condition'    => array( 'source' => 'posts' ),
			)
		);
		$this->start_controls_section( 'section_layout', array( 'label' => esc_html__( 'Layout & Style', 'sifency-addons' ) ) );

		$this->add_control(
			'design_style',
			array(
				'label'   => 'Design Style',
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'style-1' => 'Classic List (Dotted)',
					'style-2' => 'Modern Card',
					'style-3' => 'Split (Side Image)',
					'style-4' => 'Minimal Center',
					'style-5' => 'Background Overlay',
				),
				'default' => 'style-1',
			)
		);

		$this->add_control(
			'display_type',
			array(
				'label'   => 'Display Mode',
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'grid'     => 'Grid',
					'carousel' => 'Carousel',
					'tabs'     => 'Tabs',
				),
				'default' => 'grid',
			)
		);

		$this->add_responsive_control(
			'columns',
			array(
				'label'     => 'Columns',
				'type'      => Controls_Manager::SELECT,
				'default'   => '2',
				'options'   => array(
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
				),
				'selectors' => array( '{{WRAPPER}} .sifency-menu-grid, {{WRAPPER}} .sifency-menu-tab-content' => 'grid-template-columns: repeat({{VALUE}}, 1fr);' ),
				'condition' => array( 'display_type!' => 'carousel' ),
			)
		);
		$this->add_responsive_control(
			'gap',
			array(
				'label'     => 'Gap',
				'type'      => Controls_Manager::SLIDER,
				'default'   => array( 'size' => 30 ),
				'selectors' => array( '{{WRAPPER}} .sifency-menu-grid, {{WRAPPER}} .sifency-menu-tab-content' => 'gap: {{SIZE}}px;' ),
			)
		);

		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			array(
				'name'    => 'image_size',
				'default' => 'medium_large',
			)
		);

		$this->end_controls_section();

		$this->start_controls_section( 'section_visibility', array( 'label' => esc_html__( 'Visibility Settings', 'sifency-addons' ) ) );

		$this->add_control(
			'show_image',
			array(
				'label'   => 'Show Image',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_title',
			array(
				'label'   => 'Show Title',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_desc',
			array(
				'label'   => 'Show Description',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_price',
			array(
				'label'   => 'Show Price',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_dots',
			array(
				'label'     => 'Show Separator Dots',
				'type'      => Controls_Manager::SWITCHER,
				'default'   => 'yes',
				'condition' => array( 'design_style' => 'style-1' ),
			)
		);
		$this->add_control(
			'show_labels',
			array(
				'label'   => 'Show Labels (Vegan/Spicy)',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_badge',
			array(
				'label'   => 'Show Featured Badge',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);

		$this->add_sifency_addons_flex_alignment_controls(
			array(
				'prefix'   => 'flex_',
				'label'    => esc_html__( 'Header Flex Layout', 'sifency-addons' ),
				'selector' => '.sifency-menu-header',
			)
		);
		$this->add_sifency_addons_flex_alignment_controls(
			array(
				'prefix'   => 'content_flex_',
				'label'    => esc_html__( 'Content Flex Layout', 'sifency-addons' ),
				'selector' => '.sifency-menu-content',
			)
		);
		$this->end_controls_section();
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_slider_controls( array( 'condition' => array( 'display_type' => 'carousel' ) ) );
		$this->add_sifency_addons_item_style_controls(
			array(
				'selector' => '.sifency-menu-item',
				'label'    => esc_html__( 'Menu Item Wrapper', 'sifency-addons' ),
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'   => 'content_wrapper_style_',
				'label'    => 'Content Wrapper',
				'selector' => '.sifency-menu-content',
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'badge_style_',
				'label'      => 'Badge',
				'selector'   => '.sifency-menu-item__featured-badge',
				'exclude'    => array( 'transition', 'tabs', 'alignment' ),
				'condition'  => array( 'show_badge' => 'yes' ),
				'color_only' => true,
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'title_style_',
				'label'      => 'Title',
				'selector'   => '.sifency-menu-title',
				'color_only' => true,
				'exclude'    => array( 'transition' ),
				'condition'  => array( 'show_title' => 'yes' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'desc_style_',
				'label'      => 'Description',
				'selector'   => '.sifency-menu-desc',
				'color_only' => true,
				'exclude'    => array( 'transition', 'tabs', 'box_model', 'stroke' ),
				'condition'  => array( 'show_desc' => 'yes' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'price_label_style_',
				'label'      => 'Price Label',
				'selector'   => '.price-size',
				'color_only' => true,
				'exclude'    => array( 'transition', 'tabs', 'box_model', 'alignment', 'stroke' ),
				'condition'  => array( 'show_price' => 'yes' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'price_style_',
				'label'      => 'Price',
				'selector'   => '.price-amount',
				'color_only' => true,
				'exclude'    => array( 'transition', 'tabs', 'box_model', 'alignment', 'stroke', 'shadow' ),
				'condition'  => array( 'show_price' => 'yes' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'label_meta_style_',
				'label'      => 'Labels',
				'selector'   => '.sifency-menu-label',
				'color_only' => true,
				'exclude'    => array( 'transition', 'stroke', 'alignment', 'tabs', 'shadow' ),
			)
		);
		$this->add_sifency_addons_image_style_controls(
			array(
				'prefix'    => 'image_',
				'label'     => esc_html__( 'Image', 'sifency-addons' ),
				'selector'  => '.sifency-menu-image',
				'selectors' => array(
					'image'     => '.sifency-menu-image img',
					'container' => '.sifency-menu-image img',
				),
				'condition' => array( 'show_image' => 'yes' ),
			)
		);

		$this->start_controls_section(
			'section_style_dots',
			array(
				'label'     => 'Separator Dots',
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array(
					'design_style' => 'style-1',
					'show_dots'    => 'yes',
				),
			)
		);
		$this->add_control(
			'dots_color',
			array(
				'label'     => 'Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-menu-dots' => 'border-bottom-color: {{VALUE}};' ),
			)
		);
		$this->end_controls_section();

		$this->start_controls_section(
			'section_style_tabs',
			array(
				'label'     => 'Tabs Filter',
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'display_type' => 'tabs' ),
			)
		);
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'tab_typo',
				'selector' => '{{WRAPPER}} .sifency-tab-btn',
			)
		);
		$this->add_responsive_control(
			'tab_radius',
			array(
				'label'     => 'Radius',
				'type'      => Controls_Manager::DIMENSIONS,
				'selectors' => array( '{{WRAPPER}} .sifency-tab-btn' => 'border-radius: {{TOP}}px {{RIGHT}}px {{BOTTOM}}px {{LEFT}}px;' ),
			)
		);

		$this->start_controls_tabs( 'tabs_filter_style' );

		$this->start_controls_tab( 'tab_filter_normal', array( 'label' => 'Normal' ) );
		$this->add_control(
			'tab_color',
			array(
				'label'     => 'Text Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-tab-btn' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'tab_bg',
			array(
				'label'     => 'Background',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-tab-btn' => 'background-color: {{VALUE}};' ),
			)
		);
		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'tab_border',
				'selector' => '{{WRAPPER}} .sifency-tab-btn',
			)
		);
		$this->end_controls_tab();

		$this->start_controls_tab( 'tab_filter_active', array( 'label' => 'Active' ) );
		$this->add_control(
			'tab_active_color',
			array(
				'label'     => 'Text Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-tab-btn.active' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'tab_active_bg',
			array(
				'label'     => 'Background',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-tab-btn.active' => 'background-color: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'tab_active_border_color',
			array(
				'label'     => 'Border Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-tab-btn.active' => 'border-color: {{VALUE}};' ),
			)
		);
		$this->end_controls_tab();

		$this->end_controls_tabs();
		$this->end_controls_section();
		$this->add_Sifency_Addons_Animation_Controls();
	}
	protected function render_dom( array $context ) {
		$wrapper_id        = esc_attr( $context['dom_id'] );
		$settings          = $this->get_settings_for_display();
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );

		$menu_data = array();
		$query     = null;

		if ( 'posts' === $settings['source'] ) {
			$query_args              = $this->get_sifency_addons_query_args();
			$query_args['post_type'] = $settings['query_post_type'] ?? 'restaurant_menu';
			$query                   = new \WP_Query( $query_args );

			if ( $query->have_posts() ) {
				while ( $query->have_posts() ) {
					$query->the_post();
					$menu_data[] = $this->_prepare_dynamic_item_data( $settings );
				}
				wp_reset_postdata();
			}
		} elseif ( ! empty( $settings['menu_items'] ) ) {
			foreach ( $settings['menu_items'] as $item ) {
				$menu_data[] = $this->_prepare_custom_item_data( $item, $settings );
			}
		}

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

		$wrapper_classes = array(
			'sifency-menu-wrapper',
			'sifency-display-' . $settings['display_type'],
			'sifency-menu--' . $settings['design_style'],
		);

		$this->add_render_attribute( 'wrapper', 'class', $wrapper_classes );
		$this->add_render_attribute( 'wrapper', $animation_manager->get_wrapper_attributes( array() ) );

		?>
		<?php $this->render_sifency_section_header_elements( $settings ); ?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>" <?php echo wp_kses_post( $this->get_render_attribute_string( 'wrapper' ) ); ?>>
			<?php
			if ( 'tabs' === $settings['display_type'] ) {
				$this->_render_tabs_layout( $settings, $menu_data, $animation_manager );
			} elseif ( 'carousel' === $settings['display_type'] ) {
				$this->_render_carousel_layout( $settings, $menu_data, $animation_manager );
			} else {
				$this->_render_grid_layout( $settings, $menu_data, $animation_manager );
			}

			if ( 'posts' === $settings['source'] && $query ) {
				$this->render_sifency_addons_numeric_pagination( $query, $settings, 'query_pagination_' );
			}
			?>
		</div>
		<?php
	}

	private function _prepare_dynamic_item_data( $settings ) {
		$terms = get_the_terms( get_the_ID(), 'menu_category' );
		return array(
			'id'          => get_the_ID(),
			'title'       => get_the_title(),
			'description' => get_the_excerpt(),
			'image_html'  => get_the_post_thumbnail( get_the_ID(), $settings['image_size_size'] ),
			'category'    => ( $terms && ! is_wp_error( $terms ) ) ? $terms[0]->name : 'Others',
			'pricing'     => sifency_get_field( 'menu_item_pricing' ),
			'labels'      => sifency_get_field( 'menu_item_labels' ),
			'is_featured' => ( 'yes' === sifency_get_field( 'menu_item_featured' ) ),
			'link'        => get_permalink(),
		);
	}

	private function _prepare_custom_item_data( $item, $settings ) {
		$img_html = '';
		if ( ! empty( $item['image']['id'] ) ) {
			$img_html = \Elementor\Group_Control_Image_Size::get_attachment_image_html( $item, 'image_size', 'image' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor already escapes content internally.
		}
		return array(
			'id'          => $item['_id'],
			'title'       => $item['title'],
			'description' => $item['description'],
			'image_html'  => $img_html,
			'category'    => ! empty( $item['category'] ) ? $item['category'] : 'Others',
			'pricing'     => array(
				array(
					'size'  => '',
					'price' => $item['price'],
				),
			),
			'labels'      => (array) $item['labels'],
			'is_featured' => ( 'yes' === $item['is_featured'] ),
			'link'        => '#',
		);
	}

	private function _render_grid_layout( $settings, $data, $animation_manager ) {
		echo '<div class="sifency-menu-grid">';
		foreach ( $data as $item ) {
			$this->_render_single_item( $settings, $item, $animation_manager );
		}
		echo '</div>';
	}

	private function _render_carousel_layout( $settings, $data, $animation_manager ) {
		echo '<div class="sifency-swiper-container swiper"><div class="swiper-wrapper">';
		foreach ( $data as $item ) {
			echo '<div class="swiper-slide">';
			$this->_render_single_item( $settings, $item, $animation_manager );
			echo '</div>';
		}
		echo '</div><div class="swiper-pagination"></div></div>';
	}

	private function _render_tabs_layout( $settings, $data, $animation_manager ) {
		$all_cats = array_unique( array_column( $data, 'category' ) );

		echo '<div class="sifency-menu-filter">';
		echo '<button class="sifency-tab-btn active" data-filter="all">' . esc_html__( 'All', 'sifency-addons' ) . '</button>';
		foreach ( $all_cats as $cat ) {
			echo '<button class="sifency-tab-btn" data-filter="' . esc_attr( sanitize_title( $cat ) ) . '">' . esc_html( $cat ) . '</button>';
		}
		echo '</div>';

		echo '<div class="sifency-menu-tab-content active sifency-menu-grid">';
		foreach ( $data as $item ) {
			$cat_slug = sanitize_title( $item['category'] );
			$this->_render_single_item( $settings, $item, $animation_manager, $cat_slug );
		}
		echo '</div>';
	}
	private function _render_single_item( $settings, $item, $animation_manager, $extra_class = '' ) {
		$item_key = 'item_' . $item['id'];
		$this->add_render_attribute( $item_key, 'class', array( 'sifency-menu-item', 'sifency-item-style' ) );
		if ( $extra_class ) {
			$this->add_render_attribute( $item_key, 'class', 'cat-' . $extra_class );
		}

		?>
		<article <?php echo wp_kses_post( $this->get_render_attribute_string( $item_key ) ); ?> <?php echo wp_kses_post( $animation_manager->get_item_attributes() ); ?>>
			<?php if ( 'yes' === $settings['show_badge'] && $item['is_featured'] ) : ?>
				<span class="sifency-menu-item__featured-badge"><?php echo esc_html__( 'Featured', 'sifency-addons' ); ?></span>
			<?php endif; ?>
			
			<?php if ( 'yes' === $settings['show_image'] && ! empty( $item['image_html'] ) ) : ?>
				<div class="sifency-menu-image sifency-image-style">
					<?php echo wp_kses_post( $item['image_html'] ); ?>
				</div>
			<?php endif; ?>

			<div class="sifency-menu-content sifency-content_wrapper_style">
				<div class="sifency-menu-header sifency-flex-layout">
					<?php if ( 'yes' === $settings['show_title'] ) : ?>
						<h3 class="sifency-menu-title sifency-title_style"><?php echo esc_html( $item['title'] ); ?></h3>
					<?php endif; ?>
					
					<?php if ( 'yes' === $settings['show_dots'] && 'style-1' === $settings['design_style'] ) : ?>
						<span class="sifency-menu-dots"></span>
					<?php endif; ?>

					<?php if ( 'yes' === $settings['show_price'] && ! empty( $item['pricing'] ) ) : ?>
						<div class="sifency-menu-price">
							<?php foreach ( $item['pricing'] as $p ) : ?>
								<span class="price-unit">
									<?php
									if ( ! empty( $p['size'] ) ) {
										echo '<span class="price-size sifency-price_label_style">' . esc_html( $p['size'] ) . '</span>';}
									?>
									<span class="price-amount sifency-price_style"><?php echo esc_html( $p['price'] ); ?></span>
								</span>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>
				</div>
				
				<?php if ( 'yes' === $settings['show_desc'] && ! empty( $item['description'] ) ) : ?>
					<div class="sifency-menu-desc sifency-desc_style"><?php echo wp_kses_post( $item['description'] ); ?></div>
				<?php endif; ?>

				<?php if ( 'yes' === $settings['show_labels'] && ! empty( $item['labels'] ) ) : ?>
					<div class="sifency-menu-labels">
						<?php foreach ( $item['labels'] as $label ) : ?>
							<span class="sifency-menu-label sifency-label_meta_style label--<?php echo esc_attr( $label ); ?>">
								<?php echo esc_html( ucwords( str_replace( array( '_', '-' ), ' ', $label ) ) ); ?>
							</span>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>
			</div>
		</article>
		<?php
	}
}
