<?php

namespace Softech_Addons_for_Elementor\Widgets;

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;
use Elementor\Group_Control_Text_Shadow;
use Elementor\Icons_Manager;

class SITSEL_Stripe_Checkout extends Widget_Base
{

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

    public function get_title()
    {
        return __('SITS Stripe Checkout', 'softech-addons-for-elementor');
    }

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

    public function is_editable()
    {
        return true;
    }

    public function show_in_panel()
    {
        return true;
    }

    public function get_categories()
    {
        return ['sits-category'];
    }

    public function get_style_depends()
    {
        self::register_styles();
        return ['sitsel-stripe-checkout'];
    }

    public function get_script_depends()
    {
        self::register_scripts();
        return ['sitsel-stripe-checkout'];
    }

    public static function register_styles()
{
    static $styles_registered = false;
    if ($styles_registered) return;

    wp_register_style(
        'sitsel-stripe-checkout',
        \SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/css/stripe-checkout.css',
        [],
        '1.0.0'
    );

    $styles_registered = true;
}

public static function register_scripts()
{
    static $scripts_registered = false;
    if ($scripts_registered) return;

    wp_register_script(
        'sitsel-stripe-checkout',
        \SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/js/stripe-checkout.js',
        [],
        '1.0.0',
        true // load in footer
    );

    // Pass ajax URL to JS cleanly — no hardcoding in JS file
    wp_localize_script('sitsel-stripe-checkout', 'sitselCheckout', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
    ]);

    $scripts_registered = true;
}

    private static function get_checkout_script()
    {
        return "
        (function() {
            'use strict';

            function initializeCheckout() {
                const buttons = document.querySelectorAll('[data-sitsel-checkout-btn]');
                
                buttons.forEach(button => {
                    if (button.dataset.sitselInitialized) {
                        return;
                    }
                    
                    button.dataset.sitselInitialized = 'true';
                    setupButton(button);
                });
            }

            function setupButton(button) {
                const wrapper = button.closest('.sitsel-btn-wrapper');
                if (!wrapper) return;

                const popup = wrapper.querySelector('.sitsel-popup');
                const closeBtn = wrapper.querySelector('.close-btn');
                const form = wrapper.querySelector('.sitsel-checkout-form');

                if (!popup || !closeBtn || !form) return;

                const buttonId = button.id;

                // Style close button
                const buttonStyles = window.getComputedStyle(button);
                closeBtn.style.background = buttonStyles.backgroundColor;
                closeBtn.style.color = buttonStyles.color;

                // Open popup
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    popup.classList.add('active');
                });

                // Close popup
                closeBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    popup.classList.remove('active');
                });

                // Close on backdrop click
                popup.addEventListener('click', function(e) {
                    if (e.target === popup) {
                        popup.classList.remove('active');
                    }
                });

                // Close on Escape key
                document.addEventListener('keydown', function(e) {
                    if (e.key === 'Escape' && popup.classList.contains('active')) {
                        popup.classList.remove('active');
                    }
                });

                // Form submission
                form.addEventListener('submit', function(e) {
                    e.preventDefault();

                    if (form.dataset.submitting === 'true') {
                        return;
                    }
                    form.dataset.submitting = 'true';

                    const formData = new FormData(form);
                    const priceSource = formData.get('price_source');

                    // Get price
                    let price;
                    if (priceSource === 'user_input') {
                        price = parseFloat(formData.get('price'));
                        const minAmount = parseFloat(button.dataset.minAmount || 0);

                        if (!price || price < minAmount) {
                            alert('Please enter a valid price (minimum: ' + minAmount + ')');
                            form.dataset.submitting = 'false';
                            return;
                        }
                    } else {
                        price = parseFloat(formData.get('price'));
                        if (!price || price <= 0) {
                            alert('Invalid price');
                            form.dataset.submitting = 'false';
                            return;
                        }
                    }

                    // Build request body
                    const nonceFieldName = 'sitsel_nonce_' + buttonId;
                    const body = new URLSearchParams({
                        action: 'sitsel_create_checkout',
                        nonce: formData.get(nonceFieldName),
                        name: formData.get('name'),
                        email: formData.get('email'),
                        page: formData.get('page'),
                        currency: formData.get('currency'),
                        price: price,
                        button_id: buttonId
                    });

                    fetch('" . esc_url(admin_url('admin-ajax.php')) . "', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: body
                    })
                    .then(response => response.json())
                    .then(data => {
                        form.dataset.submitting = 'false';

                        if (data.success && data.data && data.data.url) {
                            window.location.href = data.data.url;
                        } else {
                            alert('Stripe Error: ' + (data.data || JSON.stringify(data)));
                        }
                    })
                    .catch(err => {
                        form.dataset.submitting = 'false';
                        console.error('Checkout Error:', err);
                        alert('An error occurred. Please try again.');
                    });
                });
            }

            // Initialize on DOM ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeCheckout);
} else {
    initializeCheckout();
}

// Re-initialize on dynamic content (for Elementor editor)
if (window.elementorFrontend && window.elementorFrontend.hooks) {
    window.elementorFrontend.hooks.addAction(
        'frontend/element_ready/sitsel_stripe_checkout',
        function() {
            initializeCheckout();
        }
    );
}
        })();
        ";
    }

    protected function register_controls()
    {
        /** PAYMENT TAB **/
        $this->start_controls_section(
            'section_payment',
            [
                'label' => __('Checkout Settings', 'softech-addons-for-elementor'),
            ]
        );

        $opts = get_option('sits_elementor_addons_options', []);
        $secret_key = $opts['stripe_secret_key'] ?? '';
        $publishable = $opts['stripe_publishable_key'] ?? '';
        $webhook = $opts['stripe_webhook_secret'] ?? '';

        if (empty($secret_key) || empty($publishable) || empty($webhook)) {
            $this->add_control(
                'stripe_notice',
                [
                    'type' => \Elementor\Controls_Manager::RAW_HTML,
                    'raw' => '<div style="background:#0a1a3d;color:#d5d8dc;border-left:3px solid #2563eb;margin-bottom:10px;font-size: 12px;font-style: italic;font-weight: 300;line-height: 1.5;padding: 15px;">For this widget to work, you need to set your Stripe API keys in the<br><a style="color:#d5d8dc;font-weight:500;" href="' . admin_url('admin.php?page=softech-addons-for-elementor&tab=settings') . '" target="_blank">Integrations Settings</a>.
                          </div>',
                ]
            );
        }

        $this->add_control(
            'price_source',
            [
                'label' => __('Price Source', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'static',
                'options' => [
                    'static' => __('Static Price', 'softech-addons-for-elementor'),
                    'acf' => __('Custom ACF Field', 'softech-addons-for-elementor'),
                    'user_input' => __('Get Price From User', 'softech-addons-for-elementor'),
                ],
            ]
        );

        $this->add_control(
            'product_price',
            [
                'label' => __('Price', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'default' => 100,
                'description' => __('Price cannot be zero or less', 'softech-addons-for-elementor'),
                'min' => 1,
                'condition' => [
                    'price_source' => 'static',
                ],
            ]
        );

        $this->add_control(
            'acf_price_field',
            [
                'label' => __('ACF Field Name', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => __('e.g., price, product_price', 'softech-addons-for-elementor'),
                'description' => __('Enter the ACF field name/slug that contains the price value', 'softech-addons-for-elementor'),
                'condition' => [
                    'price_source' => 'acf',
                ],
            ]
        );

        if (!function_exists('get_field')) {
            $this->add_control(
                'acf_notice',
                [
                    'type' => \Elementor\Controls_Manager::RAW_HTML,
                    'raw' => '<div style="background:#ffebee;color:#c62828;border-left:3px solid #c62828;margin-top:10px;font-size: 12px;padding: 12px;">
                      <strong>ACF Plugin Required:</strong><br>
                      Advanced Custom Fields must be installed and activated to use this feature.<br>
                      <a href="' . admin_url('plugin-install.php?s=advanced+custom+fields&tab=search&type=term') . '" target="_blank" style="color:#c62828;font-weight:500;">Install ACF Plugin →</a>
                      </div>',
                    'condition' => [
                        'price_source' => 'acf',
                    ],
                ]
            );
        }

        $this->add_control(
            'product_currency',
            [
                'label' => __('Currency', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => '',
                'options' => [
                    '' => __('Use Global Currency', 'softech-addons-for-elementor'),
                    'USD' => __('USD ($)', 'softech-addons-for-elementor'),
                    'EUR' => __('EUR (€)', 'softech-addons-for-elementor'),
                    'GBP' => __('GBP (£)', 'softech-addons-for-elementor'),
                    'INR' => __('INR (₹)', 'softech-addons-for-elementor'),
                    'AUD' => __('AUD (A$)', 'softech-addons-for-elementor'),
                    'CAD' => __('CAD (C$)', 'softech-addons-for-elementor'),
                    'JPY' => __('JPY (¥)', 'softech-addons-for-elementor'),
                    'CNY' => __('CNY (¥)', 'softech-addons-for-elementor'),
                    'CHF' => __('CHF', 'softech-addons-for-elementor'),
                    'AED' => __('AED (د.إ)', 'softech-addons-for-elementor'),
                ],
                'description' => __('If left empty, the global currency from plugin settings will be used.', 'softech-addons-for-elementor'),
            ]
        );

        $this->end_controls_section();

        /** BUTTON CONTENT TAB **/
        $this->start_controls_section(
            'section_button_content',
            [
                'label' => __('Button', 'softech-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'button_text',
            [
                'label' => __('Button Text', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Buy Now', 'softech-addons-for-elementor'),
                'placeholder' => __('Enter button text', 'softech-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'button_id',
            [
                'label' => __('Button ID', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => __('Unique button ID (optional)', 'softech-addons-for-elementor'),
                'description' => __('Please make sure the ID is unique and not used elsewhere on the page. This field accepts A-Z, 0-9 & underscore chars without spaces.', 'softech-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'button_icon',
            [
                'label' => __('Icon', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::ICONS,
            ]
        );

        $this->add_control(
            'icon_position',
            [
                'label' => __('Icon Position', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => __('Left', 'softech-addons-for-elementor'),
                        'icon' => 'eicon-h-align-left',
                    ],
                    'right' => [
                        'title' => __('Right', 'softech-addons-for-elementor'),
                        'icon' => 'eicon-h-align-right',
                    ],
                ],
                'default' => 'left',
                'condition' => [
                    'button_icon[value]!' => '',
                ],
            ]
        );

        $this->add_control(
            'icon_spacing',
            [
                'label' => __('Icon Spacing', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => ['min' => 0, 'max' => 50],
                    'em' => ['min' => 0, 'max' => 5],
                ],
                'default' => ['size' => 8, 'unit' => 'px'],
                'selectors' => [
                    '{{WRAPPER}} .sitsel-btn.icon-left .btn-icon' => 'margin-right: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .sitsel-btn.icon-right .btn-icon' => 'margin-left: {{SIZE}}{{UNIT}};',
                ],
                'condition' => [
                    'button_icon[value]!' => '',
                ],
            ]
        );

        $this->add_control(
            'btn_alignment',
            [
                'label' => __('Alignment', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => __('Left', 'softech-addons-for-elementor'),
                        'icon' => 'eicon-h-align-left',
                    ],
                    'center' => [
                        'title' => __('Center', 'softech-addons-for-elementor'),
                        'icon' => 'eicon-h-align-center',
                    ],
                    'right' => [
                        'title' => __('Right', 'softech-addons-for-elementor'),
                        'icon' => 'eicon-h-align-right',
                    ],
                ],
                'default' => 'center',
                'selectors' => [
                    '{{WRAPPER}} .sitsel-btn-wrapper' => 'text-align: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();

        /** BUTTON STYLE TAB **/
        $this->start_controls_section(
            'section_button_style',
            [
                'label' => __('Button Style', 'softech-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'button_position',
            [
                'label' => __('Position', 'softech-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'static' => __('Static', 'softech-addons-for-elementor'),
                    'relative' => __('Relative', 'softech-addons-for-elementor'),
                    'absolute' => __('Absolute', 'softech-addons-for-elementor'),
                    'fixed' => __('Fixed', 'softech-addons-for-elementor'),
                ],
                'default' => 'static',
                'selectors' => [
                    '{{WRAPPER}} .sitsel-btn-wrapper' => 'position: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'btn_typography',
                'label' => __('Typography', 'softech-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .sitsel-btn, {{WRAPPER}} .sitsel-popup button[type="submit"]',
            ]
        );

        $this->add_group_control(
            Group_Control_Text_Shadow::get_type(),
            [
                'name' => 'btn_text_shadow',
                'label' => __('Text Shadow', 'softech-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .sitsel-btn, {{WRAPPER}} .sitsel-popup button[type="submit"]',
            ]
        );

        $this->start_controls_tabs('button_states_tabs');

        $this->start_controls_tab(
    'button_normal_tab',
    ['label' => __('Normal', 'softech-addons-for-elementor')]
);

$this->add_control(
    'btn_text_color',
    [
        'label' => __('Text Color', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::COLOR,
        'default' => '#ffffff',
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn' => 'color: {{VALUE}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]' => 'color: {{VALUE}};',
        ],
    ]
);

$this->add_control(
    'btn_bg_color',
    [
        'label' => __('Background Color', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::COLOR,
        'default' => '#2563eb',
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn' => 'background-color: {{VALUE}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]' => 'background-color: {{VALUE}};',
        ],
    ]
);

$this->add_group_control(
    Group_Control_Box_Shadow::get_type(),
    [
        'name' => 'btn_box_shadow',
        'label' => __('Box Shadow', 'softech-addons-for-elementor'),
        'selector' => '{{WRAPPER}} .sitsel-btn, {{WRAPPER}} .sitsel-popup button[type="submit"]',
    ]
);

$this->add_group_control(
    Group_Control_Border::get_type(),
    [
        'name' => 'btn_border',
        'label' => __('Border', 'softech-addons-for-elementor'),
        'selector' => '{{WRAPPER}} .sitsel-btn, {{WRAPPER}} .sitsel-popup button[type="submit"]',
    ]
);

$this->add_responsive_control(
    'btn_border_radius',
    [
        'label' => __('Border Radius', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::DIMENSIONS,
        'size_units' => ['px', '%', 'em'],
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
    ]
);

$this->add_responsive_control(
    'btn_padding',
    [
        'label' => __('Padding', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::DIMENSIONS,
        'size_units' => ['px', 'em', '%'],
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
        'default' => [
            'top' => 12,
            'right' => 12,
            'bottom' => 12,
            'left' => 12,
            'unit' => 'px',
        ],
    ]
);

$this->end_controls_tab();

        $this->start_controls_tab(
    'button_hover_tab',
    ['label' => __('Hover', 'softech-addons-for-elementor')]
);

$this->add_control(
    'btn_hover_text_color',
    [
        'label' => __('Text Color', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::COLOR,
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn:hover' => 'color: {{VALUE}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]:hover' => 'color: {{VALUE}};',
        ],
    ]
);

$this->add_control(
    'btn_hover_bg_color',
    [
        'label' => __('Background Color', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::COLOR,
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn:hover' => 'background-color: {{VALUE}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]:hover' => 'background-color: {{VALUE}};',
        ],
    ]
);

$this->add_group_control(
    Group_Control_Box_Shadow::get_type(),
    [
        'name' => 'btn_hover_box_shadow',
        'label' => __('Box Shadow', 'softech-addons-for-elementor'),
        'selector' => '{{WRAPPER}} .sitsel-btn:hover, {{WRAPPER}} .sitsel-popup button[type="submit"]:hover',
    ]
);

$this->add_group_control(
    Group_Control_Border::get_type(),
    [
        'name' => 'btn_hover_border',
        'label' => __('Border', 'softech-addons-for-elementor'),
        'selector' => '{{WRAPPER}} .sitsel-btn:hover, {{WRAPPER}} .sitsel-popup button[type="submit"]:hover',
    ]
);

$this->add_responsive_control(
    'btn_hover_border_radius',
    [
        'label' => __('Border Radius', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::DIMENSIONS,
        'size_units' => ['px', '%', 'em'],
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn:hover' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]:hover' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
    ]
);

$this->add_responsive_control(
    'btn_hover_padding',
    [
        'label' => __('Padding', 'softech-addons-for-elementor'),
        'type' => Controls_Manager::DIMENSIONS,
        'size_units' => ['px', 'em', '%'],
        'selectors' => [
            '{{WRAPPER}} .sitsel-btn:hover' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
            '{{WRAPPER}} .sitsel-popup button[type="submit"]:hover' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
    ]
);

$this->end_controls_tab();

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

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

        // Get price based on source
        if ($settings['price_source'] === 'acf') {
            $acf_field = sanitize_text_field($settings['acf_price_field']);

            if (function_exists('get_field')) {
                $price = floatval(get_field($acf_field, get_the_ID()));
                if (!$price) {
                    $price = 0;
                }
            } else {
                if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
                    echo '<div style="padding: 15px; background: #ffebee; color: #c62828; border-left: 3px solid #c62828; margin-bottom: 10px;">
                            <strong>ACF Not Active:</strong> Please install and activate Advanced Custom Fields to use ACF price fields.
                          </div>';
                }
                $price = 0;
            }
        } elseif ($settings['price_source'] === 'user_input') {
            $price = 0.01;
        } else {
            $price = floatval($settings['product_price']);
        }

        $opts = get_option('sits_elementor_addons_options', []);
        $global_currency = strtoupper($opts['stripe_currency'] ?? 'USD');

        $currency = !empty($settings['product_currency'])
            ? strtoupper($settings['product_currency'])
            : $global_currency;

        $currency_symbols = [
    'USD' => '$',
    'EUR' => '€',
    'GBP' => '£',
    'INR' => '₹',
    'AUD' => 'A$',
    'CAD' => 'C$',
    'JPY' => '¥',
    'CNY' => '¥',
    'CHF' => 'CHF',
    'AED' => 'د.إ',
];

        $zero_decimal_currencies = ['JPY', 'KRW', 'VND', 'CLP'];
        $is_zero_decimal = in_array($currency, $zero_decimal_currencies);

        $currency_minimums = [
            'USD' => 0.50,
            'EUR' => 0.55,
            'GBP' => 0.46,
            'INR' => 48.00,
            'AUD' => 0.86,
            'CAD' => 0.78,
            'JPY' => 86,
            'CNY' => 4.15,
            'CHF' => 0.52,
            'AED' => 2.13,
        ];

        $min_amount = $currency_minimums[$currency] ?? 0.50;
        $price_too_low = ($settings['price_source'] !== 'user_input') && ($price < $min_amount);
        $display_price = $price;
        $symbol = $currency_symbols[$currency] ?? $currency;

        $button_id = !empty($settings['button_id'])
            ? sanitize_text_field($settings['button_id'])
            : "sitsel-btn-" . wp_rand(100000, 999999);
        ?>

        <div class="sitsel-btn-wrapper">
            <button id="<?php echo esc_attr($button_id); ?>"
                    data-sitsel-checkout-btn="true"
                    class="sitsel-btn <?php echo esc_attr($settings['icon_position'] == 'right' ? 'icon-right' : 'icon-left'); ?>"
                    data-price="<?php echo esc_attr($price); ?>"
                    data-price-source="<?php echo esc_attr($settings['price_source']); ?>"
                    data-currency="<?php echo esc_attr($currency); ?>"
                    data-min-amount="<?php echo esc_attr($min_amount); ?>">

                <span class="sitsel-inner">
                    <?php if ($settings['button_icon'] && $settings['icon_position'] == 'left') : ?>
                        <span class="btn-icon">
                            <?php Icons_Manager::render_icon($settings['button_icon'], ['aria-hidden' => 'true']); ?>
                        </span>
                    <?php endif; ?>

                    <span class="btn-text"><?php echo esc_html($settings['button_text']); ?></span>

                    <?php if ($settings['button_icon'] && $settings['icon_position'] == 'right') : ?>
                        <span class="btn-icon">
                            <?php Icons_Manager::render_icon($settings['button_icon'], ['aria-hidden' => 'true']); ?>
                        </span>
                    <?php endif; ?>
                </span>
            </button>

            <!-- Popup -->
            <div class="sitsel-popup">
                <div class="popup-box">
                    <button type="button" class="close-btn">&times;</button>

                    <?php 
                    if ($price <= 0 && $settings['price_source'] !== 'user_input') : ?>
                        <h3><?php echo esc_html__('Price Missing', 'softech-addons-for-elementor'); ?></h3>
                        <p style="color:red; font-weight:bold;">
                            <?php 
                            if ($settings['price_source'] === 'acf') {
                                echo esc_html__('ACF field is empty or has no value. Please set a valid price in the ACF field.', 'softech-addons-for-elementor');
                            } else {
                                echo esc_html__('Please set a valid price in the widget settings.', 'softech-addons-for-elementor');
                            }
                            ?>
                        </p>

                    <?php elseif ($price_too_low) : ?>

                        <h3><?php echo esc_html__('Price Too Low', 'softech-addons-for-elementor'); ?></h3>
                        <p style="color:red; font-weight:bold;">
                            <?php
                                printf(
                            /* translators: 1: Currency code e.g. USD, 2: Currency symbol e.g. $, 3: Minimum amount e.g. 0.50 */
                        esc_html__(
                            'Minimum price for %1$s is %2$s%3$s. Please update the price.',
                            'softech-addons-for-elementor'
                            ),
                        esc_html($currency),
                        esc_html($symbol),
                        esc_html(number_format($min_amount, $is_zero_decimal ? 0 : 2))
                        );
                            ?>
                        </p>

                    <?php else : ?>

                        <h3><?php echo esc_html__('Enter Details', 'softech-addons-for-elementor'); ?></h3>
                        
                        <form id="sitsel-form-<?php echo esc_attr($button_id); ?>" class="sitsel-checkout-form" data-button-id="<?php echo esc_attr($button_id); ?>">
                            
                            <?php wp_nonce_field('sitsel_checkout_nonce', 'sitsel_nonce_' . $button_id); ?>
                            
                            <input type="hidden" name="page" value="<?php echo esc_attr(get_the_ID()); ?>">
                            <input type="hidden" name="currency" value="<?php echo esc_attr($currency); ?>">
                            <input type="hidden" name="button_id" value="<?php echo esc_attr($button_id); ?>">
                            <input type="hidden" name="price_source" value="<?php echo esc_attr($settings['price_source']); ?>">
                            
                            <input type="text" name="name" placeholder="<?php echo esc_attr__('Name', 'softech-addons-for-elementor'); ?>" required>
                            <input type="email" name="email" placeholder="<?php echo esc_attr__('Email', 'softech-addons-for-elementor'); ?>" required>

                            <?php if ($settings['price_source'] === 'user_input') : ?>

                                <div style="position: relative; margin-bottom: 12px;">
                                    <span style="position: absolute; left: 12px; top: 12px; font-weight: bold; color: #868789; font-size: 14px;">
                                        <?php echo esc_html($symbol); ?>
                                    </span>
                                    <input type="number" name="price" id="sitsel-price-<?php echo esc_attr($button_id); ?>"
                                           placeholder="<?php echo esc_attr('0.00 ' . $currency); ?>" 
                                           step="0.01" 
                                           min="<?php echo esc_attr($min_amount); ?>" 
                                           value="" 
                                           required 
                                           style="width: 100%; padding: 12px; padding-left: 32px; border: 1px solid #ccc; border-radius: 6px; font-size: 16px; box-sizing: border-box;">
                                    <small style="display: block; margin-top: 4px; color: #999; font-size: 12px;">
                                        <?php 
                                        /* translators: 1: Currency symbol, 2: Minimum amount */
                                       printf(
                                     /* translators: 1: Currency symbol e.g. $, 2: Minimum amount e.g. 0.50 */
                                    esc_html__(
                                    'Minimum: %1$s%2$s',
                                    'softech-addons-for-elementor'
                                    ),
                            esc_html($symbol),
                            esc_html(number_format($min_amount, $is_zero_decimal ? 0 : 2))
                            ); 
                                        ?>
                                    </small>
                                </div>
                            <?php else : ?>
                               
                                <input type="hidden" name="price" value="<?php echo esc_attr($price); ?>">
                                <div style="padding:12px;border: 1px solid #ccc;margin-bottom:12px;font-weight:bold;text-align:start;color: #868789;">
                                    <?php echo esc_html($symbol) . esc_html(number_format($display_price, $is_zero_decimal ? 0 : 2)); ?>
                                </div>
                            <?php endif; ?>
                            
                            <button type="submit" class="sitsel-btn">
                                <?php echo esc_html($settings['button_text']); ?>
                            </button>
                        </form>

                    <?php endif; ?>

                </div>
            </div>

            <!-- Error handling for invalid prices -->
            <?php if (($price <= 0 || $price_too_low) && $settings['price_source'] !== 'user_input') : ?>
                <script>
                (function() {
                    const buttonId = '<?php echo esc_js($button_id); ?>';
                    const button = document.getElementById(buttonId);
                    if (button) {
                        button.addEventListener('click', function(e) {
                            e.preventDefault();
                            let errorMsg = '';
                            
                            <?php if ($price <= 0) : ?>
                                errorMsg = '<?php 
                                if ($settings['price_source'] === 'acf') {
                                    echo esc_js(__('Error: ACF field is empty or has no value. Please set a valid price in the ACF field.', 'softech-addons-for-elementor'));
                                } else {
                                    echo esc_js(__('Error: Invalid price. Please set a valid price in widget settings.', 'softech-addons-for-elementor'));
                                }
                                ?>';
                            <?php elseif ($price_too_low) : ?>
                                errorMsg = '<?php 
                            $error_text =
                            /* translators: 1: Currency code e.g. USD, 2: Currency symbol e.g. $, 3: Minimum amount e.g. 0.50 */
                             __('Error: Minimum price for %1$s is %2$s%3$s. Please update the price in widget settings.', 'softech-addons-for-elementor')
                            . "\n\n"
                            . __('Contact admin for assistance.', 'softech-addons-for-elementor');

                                echo esc_js(sprintf(
                                    $error_text,
                                    $currency,
                                    $symbol,
                                    number_format($min_amount, $is_zero_decimal ? 0 : 2)
                                ));
                                ?>';
                            <?php endif; ?>
                            
                            alert(errorMsg);
                        });
                    }
                })();
                </script>
            <?php endif; ?>
        </div>
        <?php
    }
}
// Enqueue stripe checkout assets globally to prevent FOUC
add_action('wp_enqueue_scripts', function() {
    wp_enqueue_style(
        'sitsel-stripe-checkout',
        \SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/css/stripe-checkout.css',
        [],
        '1.0.0'
    );
    wp_enqueue_script(
        'sitsel-stripe-checkout',
        \SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/js/stripe-checkout.js',
        [],
        '1.0.0',
        true
    );
    wp_localize_script('sitsel-stripe-checkout', 'sitselCheckout', [
        'ajaxUrl' => \admin_url('admin-ajax.php'),
    ]);
});