<?php
/**
 * Widget Name: Button
 * Description: A highly customisable single button widget with multiple styles,
 *              tooltip support, icon, border-radius presets, hover effects,
 *              and full spacing controls. Style files load conditionally.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.2.0
 */

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

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;

/**
 * Class Captwiki_Button
 *
 * @since 1.2.0
 */
class Captwiki_Button extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.2.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-button';
	}

	/**
	 * Get widget title.
	 *
	 * @since 1.2.0
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Button', 'captain-widgets-kit' );
	}

	/**
	 * Get widget icon.
	 *
	 * @since 1.2.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-button captwiki-el-logo';
	}

	/**
	 * Get widget categories.
	 *
	 * @since 1.2.0
	 * @return array
	 */
	public function get_categories(): array {
		return array( 'captwiki-essential' );
	}

	/**
	 * Get widget keywords.
	 *
	 * @since 1.2.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'button', 'btn', 'cta', 'link', 'captain-widgets-kit' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.2.0
	 * @return bool
	 */
	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	/**
	 * Style options shared across all styles.
	 *
	 * @since 1.2.0
	 * @return array
	 */
	private function captwiki_btn_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Solid Fill', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Outline', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Gradient', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Icon Left', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Icon Right', 'captain-widgets-kit' ),
			'style-6' => esc_html__( 'Style 6 – Underline', 'captain-widgets-kit' ),
			'style-7' => esc_html__( 'Style 7 – 3D Shadow', 'captain-widgets-kit' ),
			'style-8' => esc_html__( 'Style 8 – Pill Glow', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Register controls.
	 *
	 * @since 1.2.0
	 */
	protected function register_controls(): void {

		/* ═══════════════════════════════════════════════════════
		 * TAB CONTENT
		 * ═══════════════════════════════════════════════════════ */

		// ── Layout ──────────────────────────────────────────────
		$this->start_controls_section(
			'section_layout',
			array(
				'label' => esc_html__( 'Layout', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'btn_style',
			array(
				'label'   => esc_html__( 'Style', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'style-1',
				'options' => $this->captwiki_btn_style_options(),
			)
		);

		$this->add_responsive_control(
			'btn_align',
			array(
				'label'     => esc_html__( 'Alignment', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'left'   => array(
						'title' => esc_html__( 'Left', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => esc_html__( 'Center', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'   => 'left',
				'selectors' => array(
					'{{WRAPPER}} .cw-btn-wrapper' => 'text-align: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Content ─────────────────────────────────────────────
		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Content', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'btn_text',
			array(
				'label'       => esc_html__( 'Button Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Click Here', 'captain-widgets-kit' ),
				'placeholder' => esc_html__( 'Enter button text', 'captain-widgets-kit' ),
				'label_block' => true,
				'dynamic'     => array( 'active' => true ),
			)
		);

		$this->add_control(
			'btn_link',
			array(
				'label'         => esc_html__( 'Link', 'captain-widgets-kit' ),
				'type'          => Controls_Manager::URL,
				'placeholder'   => esc_html__( 'https://example.com', 'captain-widgets-kit' ),
				'default'       => array( 'url' => '#' ),
				'dynamic'       => array( 'active' => true ),
				'label_block'   => true,
			)
		);

		// Icon – shown for all styles; only Style-4/5 change its position via CSS
		$this->add_control(
			'btn_icon',
			array(
				'label'            => esc_html__( 'Icon', 'captain-widgets-kit' ),
				'type'             => Controls_Manager::ICONS,
				'fa4compatibility' => 'icon',
				'skin'             => 'inline',
				'label_block'      => false,
			)
		);

		$this->add_control(
			'icon_spacing',
			array(
				'label'     => esc_html__( 'Icon Gap', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array( 'px' => array( 'min' => 0, 'max' => 30 ) ),
				'default'   => array( 'size' => 8, 'unit' => 'px' ),
				'selectors' => array(
					'{{WRAPPER}} .cw-btn .cw-btn__icon' => 'margin-inline-end: {{SIZE}}{{UNIT}};',
				),
				'condition' => array( 'btn_icon[value]!' => '' ),
			)
		);

		$this->end_controls_section();

		// ── Tooltip ─────────────────────────────────────────────
		$this->start_controls_section(
			'section_tooltip',
			array(
				'label' => esc_html__( 'Tooltip', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'tooltip_enable',
			array(
				'label'        => esc_html__( 'Enable Tooltip', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => '',
			)
		);

		$this->add_control(
			'tooltip_text',
			array(
				'label'       => esc_html__( 'Tooltip Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Tooltip text here', 'captain-widgets-kit' ),
				'placeholder' => esc_html__( 'Enter tooltip text', 'captain-widgets-kit' ),
				'label_block' => true,
				'dynamic'     => array( 'active' => true ),
				'condition'   => array( 'tooltip_enable' => 'yes' ),
			)
		);

		$this->add_control(
			'tooltip_position',
			array(
				'label'     => esc_html__( 'Position', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'top',
				'options'   => array(
					'top'    => esc_html__( 'Top', 'captain-widgets-kit' ),
					'bottom' => esc_html__( 'Bottom', 'captain-widgets-kit' ),
					'left'   => esc_html__( 'Left', 'captain-widgets-kit' ),
					'right'  => esc_html__( 'Right', 'captain-widgets-kit' ),
				),
				'condition' => array( 'tooltip_enable' => 'yes' ),
			)
		);

		$this->end_controls_section();

		/* ═══════════════════════════════════════════════════════
		 * TAB STYLE
		 * ═══════════════════════════════════════════════════════ */

		// ── Button Style ────────────────────────────────────────
		$this->start_controls_section(
			'section_style_button',
			array(
				'label' => esc_html__( 'Button', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		// Normal / Hover tabs
		$this->start_controls_tabs( 'tabs_btn_colors' );

			// Normal tab
			$this->start_controls_tab(
				'tab_btn_normal',
				array( 'label' => esc_html__( 'Normal', 'captain-widgets-kit' ) )
			);

			$this->add_control(
				'btn_text_color',
				array(
					'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
					'type'      => Controls_Manager::COLOR,
					'selectors' => array(
						'{{WRAPPER}} .cw-btn' => 'color: {{VALUE}};',
					),
				)
			);

			$this->add_group_control(
				Group_Control_Background::get_type(),
				array(
					'name'     => 'btn_background',
					'label'    => esc_html__( 'Background', 'captain-widgets-kit' ),
					'types'    => array( 'classic', 'gradient' ),
					'selector' => '{{WRAPPER}} .cw-btn',
					'exclude'  => array( 'image' ),
				)
			);

			$this->end_controls_tab();

			// Hover tab
			$this->start_controls_tab(
				'tab_btn_hover',
				array( 'label' => esc_html__( 'Hover', 'captain-widgets-kit' ) )
			);

			$this->add_control(
				'btn_text_color_hover',
				array(
					'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
					'type'      => Controls_Manager::COLOR,
					'selectors' => array(
						'{{WRAPPER}} .cw-btn:hover, {{WRAPPER}} .cw-btn:focus' => 'color: {{VALUE}};',
					),
				)
			);

			$this->add_group_control(
				Group_Control_Background::get_type(),
				array(
					'name'     => 'btn_background_hover',
					'label'    => esc_html__( 'Background', 'captain-widgets-kit' ),
					'types'    => array( 'classic', 'gradient' ),
					'selector' => '{{WRAPPER}} .cw-btn:hover, {{WRAPPER}} .cw-btn:focus',
					'exclude'  => array( 'image' ),
				)
			);

			$this->add_control(
				'btn_hover_animation',
				array(
					'label'    => esc_html__( 'Hover Animation', 'captain-widgets-kit' ),
					'type'     => Controls_Manager::HOVER_ANIMATION,
					'prefix_class' => 'elementor-animation-',
				)
			);

			$this->end_controls_tab();

		$this->end_controls_tabs();

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

		// ── Border ──────────────────────────────────────────────
		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'btn_border',
				'selector' => '{{WRAPPER}} .cw-btn',
			)
		);

		// ── Border Radius Preset + Custom ───────────────────────
		$this->add_control(
			'btn_radius_preset',
			array(
				'label'   => esc_html__( 'Shape', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'rounded',
				'options' => array(
					'square'  => esc_html__( 'Square (0px)', 'captain-widgets-kit' ),
					'rounded' => esc_html__( 'Rounded (6px)', 'captain-widgets-kit' ),
					'pill'    => esc_html__( 'Pill (50px)', 'captain-widgets-kit' ),
					'custom'  => esc_html__( 'Custom', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_responsive_control(
			'btn_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .cw-btn' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
				'condition'  => array( 'btn_radius_preset' => 'custom' ),
			)
		);

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

		// ── Box Shadow ──────────────────────────────────────────
		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'btn_box_shadow',
				'selector' => '{{WRAPPER}} .cw-btn',
			)
		);

		$this->end_controls_section();

		// ── Typography ──────────────────────────────────────────
		$this->start_controls_section(
			'section_style_typography',
			array(
				'label' => esc_html__( 'Typography', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'btn_typography',
				'selector' => '{{WRAPPER}} .cw-btn',
			)
		);

		$this->end_controls_section();

		// ── Spacing ─────────────────────────────────────────────
		$this->start_controls_section(
			'section_style_spacing',
			array(
				'label' => esc_html__( 'Spacing', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'btn_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'default'    => array(
					'top'    => '12',
					'right'  => '28',
					'bottom' => '12',
					'left'   => '28',
					'unit'   => 'px',
				),
				'selectors'  => array(
					'{{WRAPPER}} .cw-btn' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'btn_margin',
			array(
				'label'      => esc_html__( 'Margin', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'selectors'  => array(
					'{{WRAPPER}} .cw-btn-wrapper' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();

		// ── Tooltip Style ───────────────────────────────────────
		$this->start_controls_section(
			'section_style_tooltip',
			array(
				'label'     => esc_html__( 'Tooltip', 'captain-widgets-kit' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'tooltip_enable' => 'yes' ),
			)
		);

		$this->add_control(
			'tooltip_bg_color',
			array(
				'label'     => esc_html__( 'Background Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#1e293b',
				'selectors' => array(
					'{{WRAPPER}} .cw-btn-tooltip' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .cw-btn-tooltip::after' => 'border-color: {{VALUE}} transparent transparent transparent;',
				),
			)
		);

		$this->add_control(
			'tooltip_text_color',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => array(
					'{{WRAPPER}} .cw-btn-tooltip' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'tooltip_typography',
				'selector' => '{{WRAPPER}} .cw-btn-tooltip',
			)
		);

		$this->add_responsive_control(
			'tooltip_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'default'    => array( 'top' => '5', 'right' => '10', 'bottom' => '5', 'left' => '10', 'unit' => 'px' ),
				'selectors'  => array(
					'{{WRAPPER}} .cw-btn-tooltip' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'tooltip_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 20 ) ),
				'default'    => array( 'size' => 4, 'unit' => 'px' ),
				'selectors'  => array(
					'{{WRAPPER}} .cw-btn-tooltip' => 'border-radius: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * Loads only the style file matching the selected style.
	 * Common wrapper + base CSS always loads.
	 *
	 * @since 1.2.0
	 */
	protected function render(): void {

		$settings = $this->get_settings_for_display();

		$btn_style      = ! empty( $settings['btn_style'] ) ? sanitize_key( $settings['btn_style'] ) : 'style-1';
		$btn_text       = ! empty( $settings['btn_text'] ) ? $settings['btn_text'] : '';
		$tooltip_enable = ! empty( $settings['tooltip_enable'] ) && 'yes' === $settings['tooltip_enable'];
		$tooltip_text   = $tooltip_enable && ! empty( $settings['tooltip_text'] ) ? $settings['tooltip_text'] : '';
		$tooltip_pos    = ! empty( $settings['tooltip_position'] ) ? sanitize_key( $settings['tooltip_position'] ) : 'top';
		$radius_preset  = ! empty( $settings['btn_radius_preset'] ) ? sanitize_key( $settings['btn_radius_preset'] ) : 'rounded';

		// Build CSS classes
		$btn_classes = array(
			'cw-btn',
			'cw-btn--' . $btn_style,
			'cw-btn--radius-' . $radius_preset,
		);

		// Wrapper classes
		$wrapper_classes = array( 'cw-btn-wrapper' );

		// Build link attributes
		$link_url    = ! empty( $settings['btn_link']['url'] ) ? $settings['btn_link']['url'] : '#';
		$link_target = ! empty( $settings['btn_link']['is_external'] ) ? ' target="_blank"' : '';
		$link_norel  = ! empty( $settings['btn_link']['nofollow'] ) ? ' rel="nofollow"' : '';

		// Data attributes for tooltip JS
		$data_attrs = '';
		if ( $tooltip_enable ) {
			$btn_classes[]  = 'cw-btn--has-tooltip';
			$wrapper_classes[] = 'cw-btn-wrapper--tooltip-' . $tooltip_pos;
			$data_attrs     = ' data-cw-tooltip="' . esc_attr( $tooltip_text ) . '" data-cw-tooltip-pos="' . esc_attr( $tooltip_pos ) . '"';
		}

		$btn_class_str     = esc_attr( implode( ' ', $btn_classes ) );
		$wrapper_class_str = esc_attr( implode( ' ', $wrapper_classes ) );

		// Pre-render icon HTML here so style files don't need Icons_Manager in scope.
		$icon_html = '';
		if ( ! empty( $settings['btn_icon']['value'] ) ) {
			ob_start();
			Icons_Manager::render_icon( $settings['btn_icon'], array( 'aria-hidden' => 'true' ) );
			$icon_html = '<span class="cw-btn__icon" aria-hidden="true">' . ob_get_clean() . '</span>';
		}

		// Load style file
		$style_file = CAPTWIKI_PATH . 'includes/elementor/widget-style/button/' . $btn_style . '.php';

		ob_start();

		echo '<div class="' . $wrapper_class_str . '">';
			echo '<a href="' . esc_url( $link_url ) . '" class="' . $btn_class_str . '"' . $link_target . $link_norel . $data_attrs . ' role="button">';

				// Load style-specific inner HTML
				if ( file_exists( $style_file ) ) {
					include $style_file;
				} else {
					// Fallback: just render text
					echo '<span class="cw-btn__text">' . wp_kses_post( $btn_text ) . '</span>';
				}

				// Tooltip element (CSS-driven, JS enhances)
				if ( $tooltip_enable && $tooltip_text ) {
					echo '<span class="cw-btn-tooltip cw-btn-tooltip--' . esc_attr( $tooltip_pos ) . '" role="tooltip" aria-hidden="true">';
					echo esc_html( $tooltip_text );
					echo '</span>';
				}

			echo '</a>';
		echo '</div>';

		echo ob_get_clean(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}
