<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Background;
use Elementor\Icons_Manager;
use Elementor\Repeater;
use Sifency\Traits\Sifency_Elementor_Parity_Controls;
use Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Core_Text_Style;
use Sifency\Traits\Sifency_Button_Style_Controls;

class Sifency_Pricing_Table extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Core_Text_Style;
    use Sifency_Button_Style_Controls;

	public function get_name() {
		return 'sifency_pricing_table';
	}

	public function get_title() {
		return esc_html__( 'Sifency Pricing Table', 'sifency-addons' );
	}

	public function get_icon() {
		return 'eicon-price-table';
	}

	public function get_categories() {
		return [ 'sifency-addons-widgets' ];
	}

	public function get_style_depends() {
		return [ 'sifency-pricing-style', 'sifency-typo-style' ];
	}

	public function get_script_depends() {
		return [ 'sifency-pricing-script' ];
	}

	protected function register_controls() {

		$this->start_controls_section(
			'section_switcher_settings',
			[ 'label' => esc_html__( 'Switcher Settings', 'sifency-addons' ) ]
		);

		$this->add_control( 'show_switcher', [
			'label' => esc_html__( 'Show Switcher?', 'sifency-addons' ),
			'type' => Controls_Manager::SWITCHER,
			'default' => 'yes',
		]);

		$this->add_control( 'label_monthly', [
			'label' => esc_html__( 'Label A (Monthly)', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => 'Monthly',
			'condition' => [ 'show_switcher' => 'yes' ],
		]);

		$this->add_control( 'label_yearly', [
			'label' => esc_html__( 'Label B (Yearly)', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => 'Yearly',
			'condition' => [ 'show_switcher' => 'yes' ],
		]);

		$this->add_control( 'label_badge', [
			'label' => esc_html__( 'Badge Text', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => 'Save 20%',
			'condition' => [ 'show_switcher' => 'yes' ],
		]);

		$this->end_controls_section();

		// ==========================================
		// CONTENT: PRICING CARDS (REPEATER)
		// ==========================================
		$this->start_controls_section(
			'section_cards',
			[ 'label' => esc_html__( 'Pricing Cards', 'sifency-addons' ) ]
		);

		$repeater = new Repeater();

		// --- Header ---
		$repeater->add_control( 'is_featured', [
			'label' => esc_html__( 'Featured?', 'sifency-addons' ),
			'type' => Controls_Manager::SWITCHER,
			'default' => 'no',
		]);

		$repeater->add_control( 'title', [
			'label' => esc_html__( 'Title', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => 'Standard',
		]);

		$repeater->add_control( 'subtitle', [
			'label' => esc_html__( 'Subtitle', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => 'Description here',
		]);

		// --- Pricing ---
		$repeater->add_control( 'currency', [
			'label' => esc_html__( 'Currency', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => '$',
		]);

		$repeater->add_control( 'price_a', [
			'label' => esc_html__( 'Price (Monthly)', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => '19',
		]);
		$repeater->add_control( 'period_a', [
			'label' => esc_html__( 'Period (Monthly)', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => '/mo',
		]);

		$repeater->add_control( 'price_b', [
			'label' => esc_html__( 'Price (Yearly)', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => '199',
		]);
		$repeater->add_control( 'period_b', [
			'label' => esc_html__( 'Period (Yearly)', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => '/yr',
		]);

		// --- Features (Text Area workaround) ---
		$repeater->add_control( 'features_html', [
			'label' => esc_html__( 'Features List', 'sifency-addons' ),
			'type' => Controls_Manager::TEXTAREA,
			'rows' => 10,
			'default' => "10GB Storage\nBandwidth Free\n!No Support",
			'description' => esc_html__( 'One feature per line. Start line with "!" to mark as excluded.', 'sifency-addons' ),
		]);

		// --- Button ---
		$repeater->add_control( 'btn_text', [
			'label' => esc_html__( 'Button Text', 'sifency-addons' ),
			'type' => Controls_Manager::TEXT,
			'default' => 'Get Started',
		]);

		$repeater->add_control( 'btn_link', [
			'label' => esc_html__( 'Link', 'sifency-addons' ),
			'type' => Controls_Manager::URL,
			'default' => [ 'url' => '#' ],
		]);

		$this->add_control(
			'cards_list',
			[
				'label' => esc_html__( 'Cards', 'sifency-addons' ),
				'type' => Controls_Manager::REPEATER,
				'fields' => $repeater->get_controls(),
				'default' => [
					[ 'title' => 'Basic', 'price_a' => '19', 'price_b' => '190' ],
					[ 'title' => 'Pro', 'is_featured' => 'yes', 'price_a' => '49', 'price_b' => '490' ],
					[ 'title' => 'Agency', 'price_a' => '99', 'price_b' => '990' ],
				],
				'title_field' => '{{{ title }}}',
			]
		);

		$this->end_controls_section();

		// ==========================================
		// CONTENT: LAYOUT
		// ==========================================
		$this->start_controls_section(
			'section_layout',
			[ 'label' => esc_html__( 'Grid Layout', 'sifency-addons' ) ]
		);

		$this->add_responsive_control(
			'columns',
			[
				'label' => esc_html__( 'Columns', 'sifency-addons' ),
				'type' => Controls_Manager::SELECT,
				'default' => '3',
				'tablet_default' => '2',
				'mobile_default' => '1',
				'options' => [
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
					'5' => '5',
				],
				'selectors' => [
					'{{WRAPPER}} .sifency-pricing-grid' => 'grid-template-columns: repeat({{VALUE}}, 1fr);',
				],
			]
		);

		$this->add_responsive_control(
			'grid_gap',
			[
				'label' => esc_html__( 'Gap', 'sifency-addons' ),
				'type' => Controls_Manager::SLIDER,
				'default' => [ 'size' => 30 ],
				'selectors' => [
					'{{WRAPPER}} .sifency-pricing-grid' => 'gap: {{SIZE}}px;',
				],
			]
		);

		$this->end_controls_section();

		// ==========================================
		// STYLE TABS START
		// ==========================================
		$this->start_controls_section( 'style_card', [ 'label' => 'Card Container', 'tab' => Controls_Manager::TAB_STYLE ] );
		
		$this->add_group_control( Group_Control_Background::get_type(), [ 'name' => 'card_bg', 'selector' => '{{WRAPPER}} .sifency-pricing-card' ] );
		$this->add_group_control( Group_Control_Border::get_type(), [ 'name' => 'card_border', 'selector' => '{{WRAPPER}} .sifency-pricing-card' ] );
		$this->add_group_control( Group_Control_Box_Shadow::get_type(), [ 'name' => 'card_shadow', 'selector' => '{{WRAPPER}} .sifency-pricing-card' ] );
		$this->add_responsive_control( 'card_radius', [ 'label' => 'Border Radius', 'type' => Controls_Manager::DIMENSIONS, 'selectors' => [ '{{WRAPPER}} .sifency-pricing-card' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ] ] );
		$this->add_responsive_control( 'card_padding', [ 'label' => 'Padding', 'type' => Controls_Manager::DIMENSIONS, 'selectors' => [ '{{WRAPPER}} .sifency-pricing-card' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ] ] );
		
		$this->add_control( 'featured_color', [ 'label' => 'Featured Highlight Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-pricing-card.is-featured' => 'border-color: {{VALUE}};' ] ] );

		$this->end_controls_section();

        $this->add_sifency_advanced_text_style([
            'prefix'   => 'label_style',
            'label'    => 'Price',
            'selector' => '.sifency-label-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'heading_style',
            'label'    => 'Heading',
            'selector' => '.sifency-heading-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'meta_style',
            'label'    => 'Subtitle (Header)',
            'selector' => '.sifency-meta-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'content_style',
            'label'    => 'Feature List',
            'selector' => '.sifency-content-style',
            'target_children' => false,
        ]);
        $this->add_sifency_button_style_controls([
            'prefix'   => 'button_style',
            'label'    => 'Button',
            'selector' => '.sifency-button-style',
            'target_children' => false,
        ]);
        $this->add_sifency_button_style_controls([
            'prefix'   => 'yearly_save_button_style',
            'label'    => 'Yearly Benefit Button',
            'selector' => '.sifency-benefit-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'switcher_style',
            'label'    => 'Switcher Text',
            'selector' => '.sifency-separator-style',
            'target_children' => false,
        ]);
        Sifency_Elementor_Parity_Controls::register( $this );
        $this->add_sifency_animation_controls();
	}

    protected function render() {
		$settings = $this->get_settings_for_display();
		
		$id_unique = $this->get_id(); 

		$wrapper_classes = [ 'sifency-pricing-grid' ];
		$animation_manager = new Sifency_Animation_Manager( $settings );
		$animation_wrapper_attrs = $animation_manager->get_wrapper_attributes( $wrapper_classes );
		?>

		<?php if ( 'yes' === $settings['show_switcher'] ) : ?>
			<div class="sifency-toggle-container">
				<span class="sifency-toggle-text text-monthly active sifency-separator-style">
					<?php echo esc_html( $settings['label_monthly'] ); ?>
				</span>
				
				<input type="checkbox" id="sifency-switch-<?php echo esc_attr( $id_unique ); ?>" class="sifency-toggle-checkbox">
				<label for="sifency-switch-<?php echo esc_attr( $id_unique ); ?>" class="sifency-toggle-label"></label>
				
				<span class="sifency-toggle-text text-yearly">
					<span class="sifency-separator-style"><?php echo esc_html( $settings['label_yearly'] ); ?></span>
					
					<?php if ( ! empty( $settings['label_badge'] ) ) : ?>
						<span class="sifency-toggle-badge sifency-benefit-style">
							<?php echo esc_html( $settings['label_badge'] ); ?>
						</span>
					<?php endif; ?>
				</span>
			</div>
		<?php endif; ?>

		<div <?php echo wp_kses_post ( $animation_wrapper_attrs ); ?>>
			<?php 
			$post_index = 0;
			
			foreach ( $settings['cards_list'] as $index => $card ) : 
				$post_index++;
				
				$card_key     = 'card_' . $index;
				$title_key    = 'title_' . $index;
				$subtitle_key = 'subtitle_' . $index;
				$price_key    = 'price_wrap_' . $index;
				$btn_key      = 'btn_' . $index;

				$parity_class = ( $post_index % 2 !== 0 ) ? 'odd-item' : 'even-item';
				
				$item_classes = [ 
					'sifency-pricing-card', 
					$parity_class,
					'elementor-repeater-item-' . $card['_id']
				];

				if ( 'yes' === $card['is_featured'] ) {
					$item_classes[] = 'is-featured';
				}

				// Animation Attributes for Items
				$animation_item_attrs = $animation_manager->get_item_attributes( $item_classes );

				// Inline Editing
				$this->add_inline_editing_attributes( $title_key, 'none' );
				$this->add_inline_editing_attributes( $subtitle_key, 'none' );
				$this->add_inline_editing_attributes( $btn_key, 'none' );

				// Price Wrapper Attributes (Data for JS)
				$this->add_render_attribute( $price_key, [
					'class'         => 'sifency-price-wrap',
					'data-currency' => $card['currency'],
					'data-price-a'  => $card['price_a'],
					'data-period-a' => $card['period_a'],
					'data-price-b'  => $card['price_b'],
					'data-period-b' => $card['period_b'],
				] );

				// Features Parse
				$features = explode( "\n", $card['features_html'] );
			?>
				<div <?php echo wp_kses_post ( $animation_item_attrs); ?>>
					
					<div class="sifency-pricing-header">
						<h3 class="sifency-pricing-title sifency-heading-style">
							<span <?php echo wp_kses ( $this->get_render_attribute_string( $title_key ), [] ); ?>>
								<?php echo esc_html( $card['title'] ); ?>
							</span>
						</h3>
						<p class="sifency-pricing-subtitle sifency-meta-style">
							<span <?php echo wp_kses ( $this->get_render_attribute_string( $subtitle_key ), [] ); ?>>
								<?php echo esc_html( $card['subtitle'] ); ?>
							</span>
						</p>
					</div>

					<div <?php echo wp_kses ( $this->get_render_attribute_string( $price_key ), [] ); ?>>
						<span class="sifency-price-currency"><?php echo esc_html( $card['currency'] ); ?></span>
						<span class="sifency-price-amount sifency-label-style"><?php echo esc_html( $card['price_a'] ); ?></span>
						<span class="sifency-price-period"><?php echo esc_html( $card['period_a'] ); ?></span>
					</div>

					<div class="sifency-pricing-features">
						<ul>
							<?php foreach ( $features as $feature ) : 
								$feature = trim( $feature );
								if ( empty( $feature ) ) continue;
								
								$is_excluded = ( strpos( $feature, '!' ) === 0 );
								$feature_text = $is_excluded ? substr( $feature, 1 ) : $feature;
								
								$li_class   = $is_excluded ? 'excluded' : 'included';
								$icon_class = $is_excluded ? 'fas fa-times' : 'fas fa-check';
							?>
								<li class="sifency-content-style <?php echo esc_attr( $li_class ); ?>">
									<i class="<?php echo esc_attr( $icon_class ); ?>"></i>
									<span><?php echo esc_html( $feature_text ); ?></span>
								</li>
							<?php endforeach; ?>
						</ul>
					</div>

					<div class="sifency-pricing-footer">
						<a href="<?php echo esc_url( $card['btn_link']['url'] ); ?>" class="sifency-pricing-btn sifency-button-style">
							<span <?php echo wp_kses ( $this->get_render_attribute_string( $btn_key ), [] ); ?>>
								<?php echo esc_html( $card['btn_text'] ); ?>
							</span>
						</a>
					</div>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
	}
}