<?php
/**
 * Widget Name: Sales Badge
 * Description: Outputs a customizable on-sale badge (Sale text, discount percent
 *              or amount saved) for the current product or a chosen product, with
 *              several badge shapes/styles and full styling controls.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.4.0
 */

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;

/**
 * Class Captwiki_Woo_Sales_Badge
 *
 * @since 1.4.0
 */
class Captwiki_Woo_Sales_Badge extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.4.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-woo-sales-badge';
	}

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

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

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

	/**
	 * Get widget keywords.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'woocommerce', 'woo', 'product', 'sale', 'badge', 'discount', 'flash', 'offer', 'captain-widgets-kit' );
	}

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

	/**
	 * Available visual styles.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Rectangle', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Pill', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Circle', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Ribbon', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Starburst', 'captain-widgets-kit' ),
			'style-6' => esc_html__( 'Style 6 – Outline', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Build a list of published products for the source selector.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	private function captwiki_get_products_options(): array {

		$options = array();

		if ( ! function_exists( 'wc_get_products' ) ) {
			return $options;
		}

		$products = wc_get_products(
			array(
				'status'  => 'publish',
				'limit'   => 50,
				'orderby' => 'title',
				'order'   => 'ASC',
				'return'  => 'objects',
			)
		);

		foreach ( $products as $product ) {
			$options[ $product->get_id() ] = $product->get_name();
		}

		return $options;
	}

	/**
	 * Register controls.
	 *
	 * @since 1.4.0
	 */
	protected function register_controls(): void {
		$this->register_content_controls();
		$this->register_badge_style_controls();
	}

	/**
	 * Content tab controls.
	 *
	 * @since 1.4.0
	 */
	private function register_content_controls(): void {

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

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

		$this->add_control(
			'product_source',
			array(
				'label'   => esc_html__( 'Product', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'current',
				'options' => array(
					'current'  => esc_html__( 'Current Product', 'captain-widgets-kit' ),
					'specific' => esc_html__( 'Select a Product', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'product_id',
			array(
				'label'       => esc_html__( 'Choose Product', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::SELECT2,
				'label_block' => true,
				'options'     => $this->captwiki_get_products_options(),
				'condition'   => array( 'product_source' => 'specific' ),
			)
		);

		$this->add_control(
			'show_when',
			array(
				'label'   => esc_html__( 'Display', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'on_sale_only',
				'options' => array(
					'on_sale_only' => esc_html__( 'Only When On Sale', 'captain-widgets-kit' ),
					'always'       => esc_html__( 'Always', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'badge_type',
			array(
				'label'   => esc_html__( 'Badge Content', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'text',
				'options' => array(
					'text'    => esc_html__( 'Text', 'captain-widgets-kit' ),
					'percent' => esc_html__( 'Discount Percent', 'captain-widgets-kit' ),
					'amount'  => esc_html__( 'Amount Saved', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'badge_text',
			array(
				'label'     => esc_html__( 'Text', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => esc_html__( 'Sale', 'captain-widgets-kit' ),
				'condition' => array( 'badge_type' => 'text' ),
			)
		);

		$this->add_control(
			'percent_tpl',
			array(
				'label'       => esc_html__( 'Percent Template', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( '-{value}%', 'captain-widgets-kit' ),
				'description' => esc_html__( 'Use {value} for the discount number.', 'captain-widgets-kit' ),
				'condition'   => array( 'badge_type' => 'percent' ),
			)
		);

		$this->add_control(
			'amount_tpl',
			array(
				'label'       => esc_html__( 'Amount Template', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Save {value}', 'captain-widgets-kit' ),
				'description' => esc_html__( 'Use {value} for the saved amount.', 'captain-widgets-kit' ),
				'condition'   => array( 'badge_type' => 'amount' ),
			)
		);

		$this->add_control(
			'fallback_text',
			array(
				'label'       => esc_html__( 'Fallback (Not On Sale)', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'description' => esc_html__( 'Shown for percent/amount badges when the product is not on sale (Display = Always).', 'captain-widgets-kit' ),
				'condition'   => array(
					'show_when'   => 'always',
					'badge_type!' => 'text',
				),
			)
		);

		$this->add_responsive_control(
			'badge_align',
			array(
				'label'     => esc_html__( 'Alignment', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'flex-start' => 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',
					),
					'flex-end'   => array(
						'title' => esc_html__( 'Right', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'   => 'flex-start',
				'separator' => 'before',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sbadge' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Badge style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_badge_style_controls(): void {

		$selector = '{{WRAPPER}} .captwiki-sbadge__inner';

		$this->start_controls_section(
			'section_badge_style',
			array(
				'label' => esc_html__( 'Badge', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

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

		$this->add_control(
			'badge_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-1 .captwiki-sbadge__inner' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-2 .captwiki-sbadge__inner' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-3 .captwiki-sbadge__inner' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-4 .captwiki-sbadge__inner' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-4 .captwiki-sbadge__inner::after' => 'border-top-color: {{VALUE}}; border-bottom-color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-5 .captwiki-sbadge__inner' => 'background-color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-6 .captwiki-sbadge__inner' => 'border-color: {{VALUE}}; color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'badge_typography',
				'selector' => $selector,
			)
		);

		$this->add_responsive_control(
			'badge_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					$selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'badge_min_size',
			array(
				'label'       => esc_html__( 'Min Size (Circle/Star)', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::SLIDER,
				'size_units'  => array( 'px' ),
				'range'       => array( 'px' => array( 'min' => 40, 'max' => 160 ) ),
				'selectors'   => array(
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-3 .captwiki-sbadge__inner, {{WRAPPER}} .captwiki-sbadge.captwiki-style-5 .captwiki-sbadge__inner' => 'min-width: {{SIZE}}{{UNIT}}; min-height: {{SIZE}}{{UNIT}};',
				),
				'description' => esc_html__( 'Applies to the Circle and Starburst styles.', 'captain-widgets-kit' ),
			)
		);

		$this->add_responsive_control(
			'badge_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sbadge.captwiki-style-1 .captwiki-sbadge__inner, {{WRAPPER}} .captwiki-sbadge.captwiki-style-6 .captwiki-sbadge__inner' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'badge_border',
				'selector' => $selector,
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'badge_shadow',
				'selector' => $selector,
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Resolve the product.
	 *
	 * @since 1.4.0
	 * @param array $settings Widget settings.
	 * @return \WC_Product|false
	 */
	private function captwiki_resolve_product( array $settings ) {

		$source = ! empty( $settings['product_source'] ) ? $settings['product_source'] : 'current';

		if ( 'specific' === $source && ! empty( $settings['product_id'] ) ) {
			return wc_get_product( absint( $settings['product_id'] ) );
		}

		$product = wc_get_product( get_the_ID() );

		if ( $product ) {
			return $product;
		}

		if ( \Elementor\Plugin::$instance->editor->is_edit_mode() || \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
			$latest = wc_get_products(
				array(
					'status' => 'publish',
					'limit'  => 1,
				)
			);

			if ( ! empty( $latest ) ) {
				return $latest[0];
			}
		}

		return false;
	}

	/**
	 * Compute the discount (amount + percent) for a product on sale.
	 *
	 * @since 1.4.0
	 * @param \WC_Product $product Product.
	 * @return array|null
	 */
	private function captwiki_get_discount( $product ) {

		if ( ! $product->is_on_sale() ) {
			return null;
		}

		$regular = (float) $product->get_regular_price();
		$sale    = (float) $product->get_sale_price();

		if ( $regular <= 0 || $sale < 0 || $sale >= $regular ) {
			return null;
		}

		return array(
			'amount'  => $regular - $sale,
			'percent' => (int) round( ( ( $regular - $sale ) / $regular ) * 100 ),
		);
	}

	/**
	 * Output an editor-only notice.
	 *
	 * @since 1.4.0
	 * @param string $message Notice text.
	 */
	private function captwiki_render_editor_notice( string $message ): void {

		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			return;
		}

		echo '<div class="captwiki-sbadge captwiki-sbadge--notice"><p>' . esc_html( $message ) . '</p></div>';
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.4.0
	 */
	protected function render(): void {

		if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'wc_get_product' ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'WooCommerce is required for the Sales Badge widget.', 'captain-widgets-kit' ) );
			return;
		}

		$settings = $this->get_settings_for_display();
		$product  = $this->captwiki_resolve_product( $settings );

		if ( ! $product instanceof \WC_Product ) {
			$this->captwiki_render_editor_notice( esc_html__( 'No product found. Place this widget on a product template or select a product.', 'captain-widgets-kit' ) );
			return;
		}

		$on_sale   = $product->is_on_sale();
		$show_when = ! empty( $settings['show_when'] ) ? $settings['show_when'] : 'on_sale_only';

		if ( 'on_sale_only' === $show_when && ! $on_sale ) {
			$this->captwiki_render_editor_notice( esc_html__( 'This product is not on sale (badge hidden on the live site).', 'captain-widgets-kit' ) );
			return;
		}

		$type     = ! empty( $settings['badge_type'] ) ? $settings['badge_type'] : 'text';
		$discount = $this->captwiki_get_discount( $product );
		$label    = '';

		if ( 'text' === $type ) {
			$label = ! empty( $settings['badge_text'] ) ? $settings['badge_text'] : esc_html__( 'Sale', 'captain-widgets-kit' );
		} elseif ( 'percent' === $type ) {
			if ( null !== $discount ) {
				$tpl   = ! empty( $settings['percent_tpl'] ) ? $settings['percent_tpl'] : '-{value}%';
				$label = str_replace( '{value}', (string) $discount['percent'], $tpl );
			} else {
				$label = ! empty( $settings['fallback_text'] ) ? $settings['fallback_text'] : esc_html__( 'Sale', 'captain-widgets-kit' );
			}
		} else { // amount.
			if ( null !== $discount ) {
				$tpl   = ! empty( $settings['amount_tpl'] ) ? $settings['amount_tpl'] : 'Save {value}';
				$label = str_replace( '{value}', wp_strip_all_tags( wc_price( $discount['amount'] ) ), $tpl );
			} else {
				$label = ! empty( $settings['fallback_text'] ) ? $settings['fallback_text'] : esc_html__( 'Sale', 'captain-widgets-kit' );
			}
		}

		if ( '' === trim( $label ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'No badge text to display.', 'captain-widgets-kit' ) );
			return;
		}

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = ! empty( $settings['widget_style'] ) && in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';

		wp_enqueue_style(
			'captwiki-woo-sales-badge-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-sales-badge/captwiki-woo-sales-badge-' . $style . '.css',
			array( 'captwiki-woo-sales-badge' ),
			CAPTWIKI_VERSION
		);

		$wrapper_classes = array(
			'captwiki-sbadge',
			'captwiki-' . $style,
			'captwiki-widget-' . $this->get_id(),
		);

		echo '<div class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '">';
		echo '<span class="captwiki-sbadge__inner"><span class="captwiki-sbadge__text">' . esc_html( $label ) . '</span></span>';
		echo '</div>';
	}
}
