<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Sifency Addons Product Stock Widget.
 *
 * A widget that displays the stock status for a WooCommerce product.
 *
 * @since 1.2.0
 */
class Sifency_Widget_Product_Stock extends \Elementor\Widget_Base {

	public function get_name() {
		return 'sifency-product-stock';
	}

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

	public function get_icon() {
		return 'eicon-product-stock';
	}

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

	public function get_keywords() {
		return [ 'product', 'stock', 'inventory', 'woocommerce', 'sifency' ];
	}

	protected function _register_controls() {
		// --- Content Tab: Stock Labels ---
		$this->start_controls_section(
			'section_content',
			[
				'label' => esc_html__( 'Stock Labels', 'sifency-addons' ),
				'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
			]
		);
        
        if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
            $this->add_control(
                'editor_preview_status',
                [
                    'label' => esc_html__( 'Editor Preview Status', 'sifency-addons' ),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'instock',
                    'options' => [
                        'instock' => esc_html__( 'In Stock', 'sifency-addons' ),
                        'outofstock' => esc_html__( 'Out of Stock', 'sifency-addons' ),
                        'onbackorder' => esc_html__( 'On Backorder', 'sifency-addons' ),
                    ],
                    'description' => esc_html__( 'This control is for preview purposes only and has no effect on the live site.', 'sifency-addons' ),
                    'separator' => 'after',
                ]
            );
        }

		$this->add_control(
			'in_stock_text',
			[
				'label'   => esc_html__( 'In Stock Text', 'sifency-addons' ),
				'type'    => \Elementor\Controls_Manager::TEXT,
				'default' => esc_html__( 'In Stock', 'sifency-addons' ),
			]
		);

		$this->add_control(
			'out_of_stock_text',
			[
				'label'   => esc_html__( 'Out of Stock Text', 'sifency-addons' ),
				'type'    => \Elementor\Controls_Manager::TEXT,
				'default' => esc_html__( 'Out of Stock', 'sifency-addons' ),
			]
		);

		$this->add_control(
			'on_backorder_text',
			[
				'label'   => esc_html__( 'On Backorder Text', 'sifency-addons' ),
				'type'    => \Elementor\Controls_Manager::TEXT,
				'default' => esc_html__( 'Available on Backorder', 'sifency-addons' ),
			]
		);

		$this->add_control(
			'show_stock_quantity',
			[
				'label'     => esc_html__( 'Show Stock Quantity', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::SWITCHER,
				'label_on'  => esc_html__( 'Yes', 'sifency-addons' ),
				'label_off' => esc_html__( 'No', 'sifency-addons' ),
                'return_value' => 'yes',
                'default' => 'no',
				'separator' => 'before',
			]
		);

		$this->add_control(
			'stock_quantity_text',
			[
				/* translators: %s: number of items available in stock */
				'label'       => esc_html__( 'Quantity Text', 'sifency-addons' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				/* translators: %s: number of items available in stock */
				'default'     => esc_html__( '(%s available)', 'sifency-addons' ),
				/* translators: %s: Use quantity as a placeholder for the stock number. */
				'description' => esc_html__( 'Use %s as a placeholder for the stock number.', 'sifency-addons' ),
				'condition'   => [
					'show_stock_quantity' => 'yes',
				],
			]
		);

		$this->end_controls_section();

		// --- Style Tab: General Styling ---
		$this->start_controls_section(
			'section_style',
			[
				'label' => esc_html__( 'Style', 'sifency-addons' ),
				'tab'   => \Elementor\Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_responsive_control(
			'text_align',
			[
				'label'     => esc_html__( 'Alignment', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::CHOOSE,
				'options'   => [
					'left'   => [ 'title' => esc_html__( 'Left', 'sifency-addons' ), 'icon' => 'eicon-text-align-left' ],
					'center' => [ 'title' => esc_html__( 'Center', 'sifency-addons' ), 'icon' => 'eicon-text-align-center' ],
					'right'  => [ 'title' => esc_html__( 'Right', 'sifency-addons' ), 'icon' => 'eicon-text-align-right' ],
				],
				'selectors' => [
					'{{WRAPPER}} .sifency-product-stock-wrapper' => 'text-align: {{VALUE}};',
				],
			]
		);
        
        // Consolidated Typography Control
        $this->add_group_control(
			\Elementor\Group_Control_Typography::get_type(),
			[
				'name'     => 'stock_typography',
				'selector' => '{{WRAPPER}} .sifency-stock-status',
                'separator' => 'before',
			]
		);

		$this->start_controls_tabs( 'stock_style_tabs' );

		// Tab: In Stock
		$this->start_controls_tab(
			'tab_in_stock',
			[ 'label' => esc_html__( 'In Stock', 'sifency-addons' ) ]
		);

		$this->add_control(
			'in_stock_color',
			[
				'label'     => esc_html__( 'Text Color', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .sifency-stock-status.in-stock' => 'color: {{VALUE}};' ],
			]
		);
        
        $this->add_control(
			'in_stock_bg_color',
			[
				'label'     => esc_html__( 'Background Color', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .sifency-stock-status.in-stock' => 'background-color: {{VALUE}};' ],
			]
		);

		$this->end_controls_tab();

		// Tab: Out of Stock
		$this->start_controls_tab(
			'tab_out_of_stock',
			[ 'label' => esc_html__( 'Out of Stock', 'sifency-addons' ) ]
		);

		$this->add_control(
			'out_of_stock_color',
			[
				'label'     => esc_html__( 'Text Color', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .sifency-stock-status.out-of-stock' => 'color: {{VALUE}};' ],
			]
		);
        
        $this->add_control(
			'out_of_stock_bg_color',
			[
				'label'     => esc_html__( 'Background Color', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .sifency-stock-status.out-of-stock' => 'background-color: {{VALUE}};' ],
			]
		);

		$this->end_controls_tab();

		// Tab: On Backorder
		$this->start_controls_tab(
			'tab_on_backorder',
			[ 'label' => esc_html__( 'On Backorder', 'sifency-addons' ) ]
		);

		$this->add_control(
			'on_backorder_color',
			[
				'label'     => esc_html__( 'Text Color', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .sifency-stock-status.on-backorder' => 'color: {{VALUE}};' ],
			]
		);
        
        $this->add_control(
			'on_backorder_bg_color',
			[
				'label'     => esc_html__( 'Background Color', 'sifency-addons' ),
				'type'      => \Elementor\Controls_Manager::COLOR,
				'selectors' => [ '{{WRAPPER}} .sifency-stock-status.on-backorder' => 'background-color: {{VALUE}};' ],
			]
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();
		$this->end_controls_section();
	}

	protected function render() {
		if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			$this->render_editor_preview();
			return;
		}
		$product = wc_get_product();

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

		$this->render_stock_status( $product );
	}

    /**
     * Renders a fake stock status for live preview in the Elementor editor.
     */
    private function render_editor_preview() {
        $settings = $this->get_settings_for_display();
        $preview_status = $settings['editor_preview_status'];
        $stock_text = '';
        $stock_class = '';
        $dummy_quantity = 15;

        switch ($preview_status) {
            case 'instock':
                $stock_text = $settings['in_stock_text'];
                $stock_class = 'in-stock';
                break;
            case 'outofstock':
                $stock_text = $settings['out_of_stock_text'];
                $stock_class = 'out-of-stock';
                break;
            case 'onbackorder':
                $stock_text = $settings['on_backorder_text'];
                $stock_class = 'on-backorder';
                break;
        }

        if ('yes' === $settings['show_stock_quantity'] && 'instock' === $preview_status) {
            $quantity_text = sprintf($settings['stock_quantity_text'], $dummy_quantity);
            $stock_text .= ' ' . $quantity_text;
        }
        
        if (empty(trim($stock_text))) {
            $this->render_plain_content();
            return;
        }
        
        $this->render_html($stock_class, $stock_text);
    }
    
	/**
	 * Renders the stock status based on a real product object. Used for the live site.
	 */
	private function render_stock_status( $product ) {
		$settings     = $this->get_settings_for_display();
		$stock_status = $product->get_stock_status();
		$stock_text   = '';
		$stock_class  = '';

		switch ( $stock_status ) {
			case 'instock':
				$stock_text  = $settings['in_stock_text'];
				$stock_class = 'in-stock';
				break;
			case 'outofstock':
				$stock_text  = $settings['out_of_stock_text'];
				$stock_class = 'out-of-stock';
				break;
			case 'onbackorder':
				$stock_text  = $settings['on_backorder_text'];
				$stock_class = 'on-backorder';
				break;
		}

		if ( 'yes' === $settings['show_stock_quantity'] && 'instock' === $stock_status && $product->managing_stock() ) {
            $stock_quantity = $product->get_stock_quantity();
			if ( $stock_quantity ) {
				$quantity_text = sprintf( $settings['stock_quantity_text'], $stock_quantity );
				$stock_text   .= ' ' . $quantity_text;
			}
		}

		if ( empty( trim( $stock_text ) ) ) {
			return;
		}

		$this->render_html( $stock_class, $stock_text );
	}
    
    /**
     * Renders the final HTML output. This function is shared by both live and preview modes.
     */
    private function render_html( $class, $text ) {
		?>
		<div class="sifency-product-stock-wrapper">
			<div class="sifency-stock-status <?php echo esc_attr( $class ); ?>">
				<?php echo esc_html( $text ); ?>
			</div>
		</div>
		<?php
    }

	/**
	 * Render a placeholder in the editor when no product is available.
	 */
	public function render_plain_content() {
		echo '<div class="sifency-product-stock-placeholder">' . esc_html__( 'Product Stock Status', 'sifency-addons' ) . '</div>';
	}
}