<?php

namespace Prodigy\Includes\Support\Addons\Elementor\Widgets;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Plugin;
use Elementor\Widget_Base;
use Prodigy\Includes\Content\Prodigy_Request_Maker;
use Prodigy\Includes\Helpers\Prodigy_Redemption_Rules_Data;
use Prodigy\Includes\Helpers\Prodigy_Template;

if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

/**
 * Elementor widget that displays redemption code rules for the currently logged-in
 * redemption-store user: expiry date/time, per-category item limits, and a
 * live countdown to expiration.
 *
 * @version 1.0.0
 */
class Prodigy_Redemption_Rules extends Widget_Base {

	public function get_name(): string {
		return 'pae-redemption-rules';
	}

	public function get_title(): string {
		return __( 'Redemption Rules', 'prodigy-commerce' );
	}

	public function get_icon(): string {
		return 'prodigy-widget eicon-info-circle-o';
	}

	/**
	 * Appears in both the general Prodigy Commerce category and the Archive category
	 * so the widget can be used on any page.
	 */
	public function get_categories(): array {
		return array( 'prodigy-addons' );
	}

	protected function register_controls(): void {
		/*
		 * ── Style – Widget container ─────────────────────────────────────────
		 */
		$this->start_controls_section(
			'prg_redemption_rules_style_container',
			array(
				'label' => __( 'Container', 'prodigy-commerce' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'prg_redemption_rules_bg_color',
			array(
				'label'     => __( 'Background Color', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#f7f7f7',
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-widget' => 'background-color: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_border_color',
			array(
				'label'     => __( 'Border Color', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#f7f7f7',
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-widget' => 'border-color: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_border_radius',
			array(
				'label'      => __( 'Border Radius', 'prodigy-commerce' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'em' ),
				'default'    => array(
					'size' => 0,
					'unit' => 'px',
				),
				'selectors'  => array(
					'{{WRAPPER}} .prodigy-rules-widget' => 'border-radius: {{SIZE}}{{UNIT}}',
				),
			)
		);

		$this->add_responsive_control(
			'prg_redemption_rules_padding',
			array(
				'label'          => __( 'Padding', 'prodigy-commerce' ),
				'type'           => Controls_Manager::DIMENSIONS,
				'size_units'     => array( 'px', 'em' ),
				'default'        => array(
					'unit'     => 'px',
					'top'      => '16',
					'right'    => '16',
					'bottom'   => '16',
					'left'     => '16',
					'isLinked' => true,
				),
				'selectors'      => array(
					'{{WRAPPER}} .prodigy-rules-widget' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}',
				),
			)
		);

		$this->add_responsive_control(
			'prg_redemption_rules_margin',
			array(
				'label'          => __( 'Margin', 'prodigy-commerce' ),
				'type'           => Controls_Manager::DIMENSIONS,
				'size_units'     => array( 'px', 'em', '%' ),
				'default'        => array(
					'unit'     => 'px',
					'top'      => '0',
					'right'    => '0',
					'bottom'   => '20',
					'left'     => '0',
					'isLinked' => false,
				),
				'tablet_default' => array(
					'unit'     => 'px',
					'top'      => '0',
					'right'    => '0',
					'bottom'   => '20',
					'left'     => '0',
					'isLinked' => false,
				),
				'mobile_default' => array(
					'unit'     => 'px',
					'top'      => '0',
					'right'    => '0',
					'bottom'   => '20',
					'left'     => '0',
					'isLinked' => false,
				),
				'selectors'      => array(
					'{{WRAPPER}} .prodigy-rules-widget' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}',
				),
			)
		);

		$this->end_controls_section();

		/*
		 * ── Style – Text ─────────────────────────────────────────────────────
		 */
		$this->start_controls_section(
			'prg_redemption_rules_style_text',
			array(
				'label' => __( 'Text', 'prodigy-commerce' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'prg_redemption_rules_text_color',
			array(
				'label'     => __( 'Text Color', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#333333',
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-widget' => 'color: {{VALUE}}',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'           => 'prg_redemption_rules_typography',
				'label'          => __( 'Typography', 'prodigy-commerce' ),
				'selector'       => '{{WRAPPER}} .prodigy-rules-widget',
				'fields_options' => array(
					'typography' => array( 'default' => 'yes' ),
					'font_size'  => array(
						'default' => array(
							'unit' => 'px',
							'size' => 14,
						),
					),
					'font_weight' => array( 'default' => 400 ),
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_value_color',
			array(
				'label'     => __( 'Value Color (bold fields)', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#333333',
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules__text-date, {{WRAPPER}} .prodigy-rules__text-time, {{WRAPPER}} .prodigy-rules-countdown-js' => 'color: {{VALUE}}',
				),
			)
		);

		$this->end_controls_section();

		/*
		 * ── Style – Progress bar ─────────────────────────────────────────────
		 */
		$this->start_controls_section(
			'prg_redemption_rules_style_progress',
			array(
				'label'     => __( 'Progress Bar', 'prodigy-commerce' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array(
					'prg_redemption_rules_show_progress_bar' => 'yes',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_track_color',
			array(
				'label'     => __( 'Track Color', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#dddddd',
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-progress' => 'background-color: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_fill_color',
			array(
				'label'     => __( 'Fill Color', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#333333',
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-progress span' => 'background-color: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_height',
			array(
				'label'      => __( 'Height', 'prodigy-commerce' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 1,
						'max' => 20,
					),
				),
				'default'    => array(
					'size' => 2,
					'unit' => 'px',
				),
				'selectors'  => array(
					'{{WRAPPER}} .prodigy-rules-progress' => 'height: {{SIZE}}{{UNIT}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_border_type',
			array(
				'label'     => __( 'Border Type', 'prodigy-commerce' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'none',
				'options'   => array(
					'dotted' => esc_attr( 'dotted' ),
					'dashed' => esc_attr( 'dashed' ),
					'solid'  => esc_attr( 'solid' ),
					'double' => esc_attr( 'double' ),
					'groove' => esc_attr( 'groove' ),
					'ridge'  => esc_attr( 'ridge' ),
					'inset'  => esc_attr( 'inset' ),
					'outset' => esc_attr( 'outset' ),
					'none'   => esc_attr( 'none' ),
					'hidden' => esc_attr( 'hidden' ),
				),
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-progress' => 'border-style: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_border_width',
			array(
				'label'      => __( 'Border Width', 'prodigy-commerce' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 0,
						'max' => 50,
					),
				),
				'default'    => array(
					'unit'     => 'px',
					'top'      => '0',
					'right'    => '0',
					'bottom'   => '0',
					'left'     => '0',
					'isLinked' => true,
				),
				'condition'  => array(
					'prg_redemption_rules_progress_border_type' => array(
						'dotted',
						'dashed',
						'solid',
						'double',
						'groove',
						'ridge',
						'inset',
						'outset',
						'hidden',
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .prodigy-rules-progress' => 'border-width: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_border_color',
			array(
				'label'     => __( 'Border Color', 'prodigy-commerce' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#dddddd',
				'condition' => array(
					'prg_redemption_rules_progress_border_type' => array(
						'dotted',
						'dashed',
						'solid',
						'double',
						'groove',
						'ridge',
						'inset',
						'outset',
					),
				),
				'selectors' => array(
					'{{WRAPPER}} .prodigy-rules-progress' => 'border-color: {{VALUE}}',
				),
			)
		);

		$this->add_control(
			'prg_redemption_rules_progress_border_radius',
			array(
				'label'      => __( 'Border Radius', 'prodigy-commerce' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%' ),
				'default'    => array(
					'size' => 0,
					'unit' => 'px',
				),
				'selectors'  => array(
					'{{WRAPPER}} .prodigy-rules-progress' => 'border-radius: {{SIZE}}{{UNIT}}; overflow: hidden',
					'{{WRAPPER}} .prodigy-rules-progress span' => 'border-radius: inherit',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * @return array{ends_at: string, ends_at_label: string, time_remaining: string, total_capacity: int, order_rules: array}
	 */
	private function get_redemption_rules_data(): array {
		$empty = Prodigy_Redemption_Rules_Data::empty_data();

		try {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only page context for an optional request parameter.
			$order_id      = isset( $_GET['order_id'] ) ? absint( wp_unslash( $_GET['order_id'] ) ) : 0;
			$request_maker = Prodigy_Request_Maker::get_instance();
			$data          = $order_id > 0 ? $request_maker->do_redemption_rules_request( $order_id ) : $request_maker->do_redemption_rules_request();
		} catch ( \Exception $e ) {
			return $empty;
		}

		if ( empty( $data['data']['attributes'] ) ) {
			return $empty;
		}

		return Prodigy_Redemption_Rules_Data::normalize_response( $data );
	}

	/**
	 * Returns preview/placeholder data used while editing in Elementor.
	 */
	private function get_preview_data(): array {
		$now    = new \DateTime( 'now' );
		$future = clone $now;
		$future->modify( '+2 days +3 hours +15 minutes' );

		return array(
			'ends_at'        => $future->format( \DateTime::ATOM ),
			'ends_at_label'  => $future->format( 'M j, Y (g:i A)' ),
			'time_remaining' => '2d 3h 15m',
			'total_capacity' => 7,
			'order_rules'    => array(
				array(
					'category-name'    => 'Clothing / T-Shirts and Polos',
					'capacity'         => 3,
					'ordered-quantity' => 0,
				),
				array(
					'category-name'    => 'Clothing / Coats and Jackets',
					'capacity'         => 4,
					'ordered-quantity' => 2,
				),
			),
		);
	}

	private function is_editor_preview(): bool {
		return class_exists( '\Elementor\Plugin' )
			&& isset( Plugin::$instance->editor )
			&& Plugin::$instance->editor->is_edit_mode();
	}

	protected function render(): void {
		$is_preview = $this->is_editor_preview();

		if ( $is_preview ) {
			$data = $this->get_preview_data();
		} else {
			$data = $this->get_redemption_rules_data();
			if ( empty( $data['ends_at'] ) ) {
				$data       = $this->get_preview_data();
				$is_preview = true;
			}
		}

		// Build template args.
		$args = array(
			'ends_at'               => $data['ends_at'],
			'ends_at_label'         => $data['ends_at_label'],
			'time_remaining'        => $data['time_remaining'],
			'total_capacity'        => $data['total_capacity'],
			'order_rules'           => $data['order_rules'],
			'hide_active_until'     => false,
			'hide_time_remaining'   => false,
			'hide_total_capacity'   => false,
			'hide_progress'         => false,
			'is_preview'            => $is_preview,
		);

		Prodigy_Template::prodigy_get_template( 'redemption-rules-widget.php', $args );
	}
}
