<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

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

/**
 * Form
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay\Forms
 */

// Get form ID from parameter or global post
$form_id = isset($args['form_id']) ? $args['form_id'] : (isset($post) && is_object($post) ? $post->ID : 0);

if (!$form_id) {
    return;
}

// Get form data
$product_description = get_post_meta($form_id, '_wpayme_product_description', true);
$thumbnail_id = get_post_meta($form_id, '_wpayme_product_thumbnail', true);
$payment_type = get_post_meta($form_id, '_wpayme_payment_type', true) ?: 'one_time';
$amount_method = get_post_meta($form_id, '_wpayme_payment_form_amount_method', true) ?: 'fixed_price';
$fixed_price = get_post_meta($form_id, '_wpayme_fixed_price', true);
$amount_choices = get_post_meta($form_id, '_wpayme_payment_form_amount_choices', true) ?: array();
$variants = get_post_meta($form_id, '_wpayme_product_variants', true) ?: array();
$enable_quantity = get_post_meta($form_id, '_wpayme_enable_quantity', true);
$min_quantity = get_post_meta($form_id, '_wpayme_min_quantity', true) ?: 1;
$max_quantity = get_post_meta($form_id, '_wpayme_max_quantity', true);
$enable_stock = get_post_meta($form_id, '_wpayme_enable_stock', true);
$stock_quantity = get_post_meta($form_id, '_wpayme_stock_quantity', true);
$show_stock = get_post_meta($form_id, '_wpayme_show_stock', true);
$shipping_fee = get_post_meta($form_id, '_wpayme_shipping_fee', true);
$tax_rate = get_post_meta($form_id, '_wpayme_tax_rate', true);
$surcharge_type = get_post_meta($form_id, '_wpayme_surcharge_type', true);
$surcharge_amount = get_post_meta($form_id, '_wpayme_surcharge_amount', true);
$surcharge_label = get_post_meta($form_id, '_wpayme_surcharge_label', true) ?: __('Processing Fee', 'wpayme');
$button_text = get_post_meta($form_id, '_wpayme_button_text', true) ?: ($payment_type === 'donation' ? __('Donate Now', 'wpayme') : __('Pay Now', 'wpayme'));
$button_color = get_post_meta($form_id, '_wpayme_button_color', true) ?: '#0073aa';
$button_text_color = get_post_meta($form_id, '_wpayme_button_text_color', true) ?: '#ffffff';
$button_class = get_post_meta($form_id, '_wpayme_button_class', true);

// Currency symbol mapping
$currency_symbols = array(
    'EUR' => '€',
    'USD' => '$',
    'GBP' => '£',
    'AUD' => 'A$',
    'CAD' => 'C$',
    'JPY' => '¥',
    // Add more as needed
);

// Get gateway options
$gateway_id = get_post_meta($form_id, '_wpayme_gateway_id', true);
$gateways = apply_filters('wpayme_pay_gateways', array());

// Added for payment methods AJAX
$config_id = get_post_meta($form_id, '_wpayme_payment_form_config_id', true);

// Get currency from form settings or use gateway default
$currency = get_post_meta($form_id, '_wpayme_currency', true);
$allow_currency_choice = get_post_meta($form_id, '_wpayme_allow_currency_choice', true);

// If no currency is set and we have a gateway config, try to get the default currency from the gateway
if (empty($currency) && !empty($config_id)) {
    $gateway = \Wpayme\WordPress\Pay\Plugin::get_gateway($config_id);
    if ($gateway && method_exists($gateway, 'get_default_currency')) {
        $currency = $gateway->get_default_currency();
    }
}

// Default to EUR if still no currency
$currency = $currency ?: 'EUR';

$currency_symbol = isset($currency_symbols[$currency]) ? $currency_symbols[$currency] : $currency;

// Format amount choices for display
$formatted_choices = array();
if (is_array($amount_choices)) {
    foreach ($amount_choices as $choice) {
        $formatted_choices[] = number_format($choice, 2, '.', '');
    }
}

?>

<?php ob_start(); ?>
/* Form Styles */
.wpayme-pay-form-wrap {
    max-width: 600px;
    margin: 0 auto;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}

.wpayme-pay-form {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* Discount Styles */
.wpayme-pay-discounted-price-indicator {
    background-color: #f8fff8;
    border-left: 3px solid #28a745;
    padding: 5px 10px;
    margin-top: 8px;
    font-weight: bold;
    color: #28a745;
    border-radius: 2px;
    display: inline-block;
}

.wpayme-pay-after-discount {
    background-color: #f8fff8;
    border-left: 3px solid #28a745;
    padding: 2px 10px;
    border-radius: 2px;
}

.wpayme-pay-after-discount .wpayme-pay-price-value {
    font-weight: bold;
    color: #28a745;
}

.wpayme-pay-discount .wpayme-pay-price-value {
    color: #28a745;
}

/* Coupon Field Styles */
.wpayme-pay-coupon-field {
    display: flex;
    margin-bottom: 10px;
}

.wpayme-pay-coupon-field input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px 0 0 4px;
}

.wpayme-pay-coupon-field button {
    padding: 8px 15px;
    background-color: #f0f0f0;
    border: 1px solid #ddd;
    border-left: none;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
    transition: background-color 0.2s;
}

.wpayme-pay-coupon-field button:hover {
    background-color: #e0e0e0;
}

.wpayme-pay-coupon-field button.remove {
    background-color: #f8d7da;
    color: #721c24;
}

.wpayme-pay-coupon-field button.remove:hover {
    background-color: #f5c6cb;
}

.wpayme-pay-coupon-message {
    margin-top: 5px;
    font-size: 14px;
}

.wpayme-pay-coupon-message.success {
    color: #28a745;
}

.wpayme-pay-coupon-message.error {
    color: #dc3545;
}

/* Coupon Container Styles */
.wpayme-coupon-container {
    margin-bottom: 20px;
}

.wpayme-coupon-header {
    font-weight: bold;
    margin-bottom: 10px;
}

.wpayme-coupon-applied {
    margin-top: 8px;
    padding: 6px 10px;
    background-color: #f8fff8;
    border-left: 3px solid #28a745;
    border-radius: 3px;
}

.wpayme-coupon-applied .success {
    color: #28a745;
    font-weight: 500;
}

.wpayme-coupon-applied .error {
    color: #dc3545;
    font-weight: 500;
}

/* Submit Button Styles */
.wpayme-pay-submit {
    padding: 15px;
    border-radius: 4px;
    margin-top: 20px;
    text-align: center;
}

.wpayme-pay-button {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: opacity 0.2s;
    background: transparent;
}

.wpayme-pay-button:hover {
    opacity: 0.9;
}

.wpayme-pay-button:focus {
    outline: none;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.5);
}

.wpayme-pay-out-of-stock-button {
    opacity: 0.7;
    cursor: not-allowed;
}
<?php
$css = ob_get_clean();
wp_add_inline_style('wpayme-pay-form-style', $css);
?>

<div class="wpayme-pay-form-wrap">
    <form id="wpayme-pay-form-<?php echo esc_attr($form_id); ?>" class="wpayme-pay-form" method="post" data-form-id="<?php echo esc_attr($form_id); ?>" data-base-price="<?php echo esc_attr($amount); ?>">
        <?php wp_nonce_field('wpayme_pay_submit_form', 'wpayme_pay_nonce'); ?>
        <input type="hidden" name="form_id" value="<?php echo esc_attr($form_id); ?>">
        <input type="hidden" name="wpayme_pay_config_id" value="<?php echo esc_attr($config_id); ?>">
        <input type="hidden" name="wpayme_pay_calculated_amount" value="0"><!-- Added for total amount calculation -->
        <input type="hidden" name="amount" value="<?php echo esc_attr($amount); ?>">
        <input type="hidden" name="currency" value="<?php echo esc_attr($currency); ?>">
        <input type="hidden" name="description" value="<?php echo esc_attr($title); ?>">
        
        <?php 
        // Check if there's a coupon in the session or in the POST data
        $coupon_data = '';
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification is handled on form submission, this is just re-populating data.
        if (isset($_POST['wpayme_pay_coupon_data']) && !empty($_POST['wpayme_pay_coupon_data'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification is handled on form submission.
            $coupon_data = sanitize_text_field(wp_unslash($_POST['wpayme_pay_coupon_data']));
        } elseif (isset($_SESSION['wpayme_coupon_' . $form_id]) && !empty($_SESSION['wpayme_coupon_' . $form_id])) {
            $coupon_data = sanitize_text_field($_SESSION['wpayme_coupon_' . $form_id]);
        }
        ?>
        <input type="hidden" name="wpayme_pay_applied_coupon" id="wpayme-pay-applied-coupon" value="<?php echo esc_attr($coupon_data); ?>">
        <input type="hidden" name="wpayme_pay_coupon_data" id="wpayme_pay_coupon_data" value="<?php echo esc_attr($coupon_data); ?>">
        
        <?php if ($thumbnail_id) : ?>
            <div class="wpayme-pay-product-image">
                <?php echo wp_get_attachment_image($thumbnail_id, 'medium', false, array('class' => 'wpayme-product-thumbnail')); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($product_description) : ?>
            <div class="wpayme-pay-product-description">
                <?php echo wp_kses_post($product_description); ?>
            </div>
        <?php endif; ?>
        
        <fieldset class="wpayme-pay-product-options">
            <legend><?php echo esc_html($payment_type === 'donation' ? __('Donation Options', 'wpayme') : __('Payment Options', 'wpayme')); ?></legend>
            
            <!-- Amount Section -->
            <div class="wpayme-pay-section">
                <h3 class="wpayme-pay-section-title">
                    <?php echo esc_html($payment_type === 'donation' ? __('Donation Amount', 'wpayme') : __('Amount', 'wpayme')); ?>
                </h3>
                
                <?php if ($amount_method === 'fixed_price' && $fixed_price) : ?>
                    <!-- Fixed Price -->
                    <div class="wpayme-pay-fixed-price">
                        <span class="wpayme-pay-price-display" data-base-price="<?php echo esc_attr($fixed_price); ?>">
                            <?php echo esc_html($currency_symbol . number_format($fixed_price, 2)); ?>
                        </span>
                        <input type="hidden" name="wpayme_pay_amount" value="<?php echo esc_attr($fixed_price * 100); ?>">
                    </div>
                
                <?php elseif ($amount_method === 'input_only') : ?>
                    <!-- Input Only -->
                    <div class="wpayme-pay-amount-input-only">
                        <span class="wpayme-pay-currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                        <input type="number" 
                               name="wpayme_pay_amount" 
                               step="0.01" 
                               min="0.01" 
                               required="required" 
                               placeholder="<?php esc_attr_e('Enter amount', 'wpayme'); ?>"
                               class="wpayme-pay-amount-input">
                    </div>
                
                <?php elseif ($amount_method === 'choices_only' && !empty($formatted_choices)) : ?>
                    <!-- Choices Only -->
                    <div class="wpayme-pay-amount-choices">
                        <?php foreach ($formatted_choices as $index => $choice) : ?>
                            <div class="wpayme-pay-amount-choice">
                                <input type="radio" 
                                       id="wpayme-pay-amount-<?php echo esc_attr($index); ?>" 
                                       name="wpayme_pay_amount" 
                                       value="<?php echo esc_attr($choice); ?>" 
                                       <?php checked($index, 0); ?> 
                                       required="required">
                                <label for="wpayme-pay-amount-<?php echo esc_attr($index); ?>">
                                    <?php echo esc_html($currency_symbol . $choice); ?>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                
                <?php elseif ($amount_method === 'choices_and_input' && !empty($formatted_choices)) : ?>
                    <!-- Choices with Input -->
                    <div class="wpayme-pay-amount-choices">
                        <?php foreach ($formatted_choices as $index => $choice) : ?>
                            <div class="wpayme-pay-amount-choice">
                                <input type="radio" 
                                       id="wpayme-pay-amount-<?php echo esc_attr($index); ?>" 
                                       name="wpayme_pay_amount" 
                                       value="<?php echo esc_attr($choice); ?>" 
                                       <?php checked($index, 0); ?> 
                                       required="required">
                                <label for="wpayme-pay-amount-<?php echo esc_attr($index); ?>">
                                    <?php echo esc_html($currency_symbol . $choice); ?>
                                </label>
                            </div>
                        <?php endforeach; ?>
                        
                        <div class="wpayme-pay-amount-choice wpayme-pay-custom-amount">
                            <input type="radio" 
                                   id="wpayme-pay-amount-custom" 
                                   name="wpayme_pay_amount" 
                                   value="custom" 
                                   required="required">
                            <label for="wpayme-pay-amount-custom" class="wpayme-pay-custom-amount-label">
                                <span class="wpayme-pay-currency-symbol"><?php echo esc_html($currency_symbol); ?></span>
                                <input type="number" 
                                       id="wpayme-pay-custom-amount" 
                                       name="wpayme_pay_custom_amount" 
                                       step="0.01" 
                                       min="0.01" 
                                       placeholder="<?php esc_attr_e('Other amount', 'wpayme'); ?>"
                                       class="wpayme-pay-custom-amount-input">
                            </label>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($variants)) : ?>
                <!-- Variants Section -->
                <div class="wpayme-pay-section">
                    <h3 class="wpayme-pay-section-title"><?php esc_html_e('Options', 'wpayme'); ?></h3>
                    <div class="wpayme-pay-variants">
                        <select name="wpayme_pay_variant" class="wpayme-pay-variant-select" required>
                            <option value=""><?php esc_html_e('Select an option', 'wpayme'); ?></option>
                            <?php foreach ($variants as $variant) : ?>
                                <option value="<?php echo esc_attr($variant['name']); ?>" 
                                        data-price="<?php echo esc_attr($variant['price']); ?>">
                                    <?php echo esc_html($variant['name']); ?> 
                                    (<?php echo esc_html($currency_symbol . number_format($variant['price'], 2)); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php if ($enable_quantity) : ?>
                <!-- Quantity Section -->
                <div class="wpayme-pay-section">
                    <h3 class="wpayme-pay-section-title"><?php esc_html_e('Quantity', 'wpayme'); ?></h3>
                    <div class="wpayme-pay-quantity">
                        <?php if ($enable_stock && $stock_quantity !== '' && intval($stock_quantity) <= 0) : ?>
                            <div class="wpayme-pay-out-of-stock">
                                <?php esc_html_e('Out of stock', 'wpayme'); ?>
                            </div>
                        <?php else : ?>
                            <div class="wpayme-pay-quantity-controls">
                                <button type="button" class="wpayme-pay-quantity-minus">-</button>
                                <input type="number" 
                                       name="wpayme_pay_quantity" 
                                       value="<?php echo esc_attr($min_quantity); ?>" 
                                       min="<?php echo esc_attr($min_quantity); ?>" 
                                       <?php echo ($max_quantity && $max_quantity != '0') ? 'max="' . esc_attr($max_quantity) . '"' : ''; ?> 
                                       <?php echo ($enable_stock && $stock_quantity !== '') ? 'max="' . esc_attr($stock_quantity) . '"' : ''; ?>
                                       required="required"
                                       class="wpayme-pay-quantity-input">
                                <button type="button" class="wpayme-pay-quantity-plus">+</button>
                            </div>
                            <?php if ($enable_stock && $show_stock && $stock_quantity !== '') : ?>
                                <div class="wpayme-pay-stock-info">
                                    <?php 
                                    /* translators: %s: Stock quantity */
                                    echo esc_html(sprintf(__('Available: %s', 'wpayme'), $stock_quantity)); 
                                    ?>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php if ($allow_currency_choice) : ?>
                <!-- Currency Selection -->
                <div class="wpayme-pay-section">
                    <h3 class="wpayme-pay-section-title"><?php esc_html_e('Currency', 'wpayme'); ?></h3>
                    <div class="wpayme-pay-currency-selection">
                        <select name="wpayme_pay_currency" class="wpayme-pay-currency-select">
                            <?php
                            $currencies = array(
                                'EUR' => 'Euro (€)',
                                'USD' => 'US Dollar ($)',
                                'GBP' => 'British Pound (£)',
                                'AUD' => 'Australian Dollar (A$)',
                                'CAD' => 'Canadian Dollar (C$)',
                                'JPY' => 'Japanese Yen (¥)',
                                // Add more as needed
                            );
                            
                            foreach ($currencies as $code => $name) {
                                printf(
                                    '<option value="%s" %s>%s</option>',
                                    esc_attr($code),
                                    selected($code, $currency, false),
                                    esc_html($name)
                                );
                            }
                            ?>
                        </select>
                    </div>
                </div>
            <?php else : ?>
                <input type="hidden" name="wpayme_pay_currency" value="<?php echo esc_attr($currency); ?>">
            <?php endif; ?>
            
            <!-- Coupon Section -->
            <div class="wpayme-pay-section">
                <div class="wpayme-coupon-container">
                    <div class="wpayme-coupon-header"><?php esc_html_e('Have a coupon?', 'wpayme'); ?></div>
                    
                    <div class="wpayme-coupon-field">
                        <?php
                        // Check if there's a coupon code to pre-populate
                        $coupon_code = '';
                        if (!empty($coupon_data)) {
                            try {
                                $decoded_coupon = json_decode($coupon_data, true);
                                if (isset($decoded_coupon['code'])) {
                                    $coupon_code = $decoded_coupon['code'];
                                }
                            } catch (Exception $e) {
                                // Silently fail if JSON decode fails
                            }
                        }
                        ?>
                        <input type="text" class="wpayme-coupon-input" 
                            placeholder="<?php esc_attr_e('Enter coupon code', 'wpayme'); ?>"
                            value="<?php echo esc_attr($coupon_code); ?>"
                            <?php echo !empty($coupon_code) ? 'disabled' : ''; ?>>
                        <button type="button" class="wpayme-apply-coupon-btn <?php echo !empty($coupon_code) ? 'remove' : ''; ?>">
                            <?php echo !empty($coupon_code) ? esc_html__('Remove', 'wpayme') : esc_html__('Apply', 'wpayme'); ?>
                        </button>
                    </div>
                    
                    <div class="wpayme-coupon-applied" style="display: <?php echo !empty($coupon_code) ? 'block' : 'none'; ?>;">
                        <?php if (!empty($coupon_code)): ?>
                            <?php 
                            $message = '';
                            if (!empty($decoded_coupon['message']) && is_string($decoded_coupon['message'])) {
                                $message = $decoded_coupon['message'];
                            } elseif (!empty($decoded_coupon['discount_type']) && !empty($decoded_coupon['discount_amount'])) {
                                if ($decoded_coupon['discount_type'] === 'percentage') {
                                    /* translators: %s: Discount amount */
                                    $message = sprintf(__('Coupon applied: %s%% discount', 'wpayme'), $decoded_coupon['discount_amount']);
                                } else {
                                    /* translators: %s: Formatted price */
                                    $message = sprintf(__('Coupon applied: %s discount', 'wpayme'), $currency_symbol . $decoded_coupon['discount_amount']);
                                }
                            } else {
                                $message = __('Coupon applied', 'wpayme');
                            }
                            ?>
                            <span class="success"><?php echo esc_html($message); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <!-- End Coupon Section -->
            
            <?php if ($shipping_fee || $tax_rate || ($surcharge_type && $surcharge_amount)) : ?>
                <!-- Price Breakdown -->
                <div class="wpayme-pay-section wpayme-pay-breakdown-section">
                    <h3 class="wpayme-pay-section-title"><?php esc_html_e('Price Breakdown', 'wpayme'); ?></h3>
                    <div class="wpayme-pay-price-breakdown">
                        <div class="wpayme-pay-price-row wpayme-pay-subtotal">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Subtotal', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                        
                        <?php if ($shipping_fee) : ?>
                            <div class="wpayme-pay-price-row wpayme-pay-shipping">
                                <span class="wpayme-pay-price-label"><?php esc_html_e('Shipping', 'wpayme'); ?></span>
                                <span class="wpayme-pay-price-value">
                                    <?php echo esc_html($currency_symbol . number_format($shipping_fee, 2)); ?>
                                </span>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($tax_rate) : ?>
                            <div class="wpayme-pay-price-row wpayme-pay-tax">
                                <span class="wpayme-pay-price-label">
                                    <?php 
                                    /* translators: %s: Tax rate */
                                    echo esc_html(sprintf(__('Tax (%s%%)', 'wpayme'), $tax_rate)); 
                                    ?>
                                </span>
                                <span class="wpayme-pay-price-value">-</span>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($surcharge_type && $surcharge_amount) : ?>
                            <div class="wpayme-pay-price-row wpayme-pay-surcharge">
                                <span class="wpayme-pay-price-label">
                                    <?php echo esc_html($surcharge_label); ?>
                                    <?php if ($surcharge_type === 'percentage') : ?>
                                        (<?php echo esc_html($surcharge_amount); ?>%)
                                    <?php endif; ?>
                                </span>
                                <span class="wpayme-pay-price-value">-</span>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Coupon Discount Row (Initially Hidden) -->
                        <div class="wpayme-pay-price-row wpayme-pay-discount" style="display: none;">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Discount', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                        
                        <!-- Price After Discount (Initially Hidden) -->
                        <div class="wpayme-pay-price-row wpayme-pay-after-discount" style="display: none;">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Price After Discount', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                        
                        <div class="wpayme-pay-price-row wpayme-pay-total">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Total', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <!-- Hidden Price Breakdown (will show when coupon is applied) -->
                <div class="wpayme-pay-section wpayme-pay-breakdown-section" style="display: <?php echo !empty($coupon_code) ? 'block' : 'none'; ?>;">
                    <h3 class="wpayme-pay-section-title"><?php esc_html_e('Price Breakdown', 'wpayme'); ?></h3>
                    <div class="wpayme-pay-price-breakdown">
                        <div class="wpayme-pay-price-row wpayme-pay-subtotal">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Subtotal', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                        
                        <!-- Coupon Discount Row -->
                        <div class="wpayme-pay-price-row wpayme-pay-discount">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Discount', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                        
                        <!-- Price After Discount -->
                        <div class="wpayme-pay-price-row wpayme-pay-after-discount">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Price After Discount', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                        
                        <div class="wpayme-pay-price-row wpayme-pay-total">
                            <span class="wpayme-pay-price-label"><?php esc_html_e('Total', 'wpayme'); ?></span>
                            <span class="wpayme-pay-price-value">-</span>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </fieldset>
        
        <?php if (!empty($gateways)) : ?>
            <!-- Payment Method Section -->
            <fieldset class="wpayme-pay-payment-method">
                <legend><?php esc_html_e('Payment Method', 'wpayme'); ?></legend>
                
                <!-- Payment Methods Container - Will be populated by JavaScript -->
                <div class="wpayme-pay-payment-methods-container">
                    <p class="wpayme-pay-loading"><?php esc_html_e('Loading payment methods...', 'wpayme'); ?></p>
                </div>
            </fieldset>
        <?php endif; ?>
        
        <div class="wpayme-pay-submit" style="background-color: <?php echo esc_attr($button_color); ?>">
            <?php if ($enable_stock && $stock_quantity !== '' && intval($stock_quantity) <= 0) : ?>
                <button type="button" class="wpayme-pay-button wpayme-pay-out-of-stock-button" style="color: <?php echo esc_attr($button_text_color); ?>" disabled>
                    <?php esc_html_e('Out of Stock', 'wpayme'); ?>
                </button>
            <?php else : ?>
                <button type="submit" class="wpayme-pay-button" style="color: <?php echo esc_attr($button_text_color); ?>" <?php echo !empty($button_class) ? 'class="' . esc_attr($button_class) . '"' : ''; ?>>
                    <?php echo esc_html($button_text); ?>
                </button>
            <?php endif; ?>
            
            <input type="hidden" name="wpayme_pay" value="1">
            <input type="hidden" name="wpayme_pay_source" value="wpayme_payment_form">
            <input type="hidden" name="wpayme_pay_source_id" value="<?php echo esc_attr($form_id); ?>">
            <input type="hidden" name="wpayme_pay_coupon_data" value="">
        </div>
    </form>
</div>

<?php
wp_enqueue_script('wpayme-pay-form-script');
ob_start();
?>
jQuery(document).ready(function($) {
    const form = $('#wpayme-pay-form-<?php echo esc_js($form_id); ?>');
    let currencySymbol = '<?php echo esc_js($currency_symbol); ?>';
    let appliedCoupon = null;
    
    // Helper function to display coupon messages
    function showCouponMessage(message, type) {
        const messageContainer = form.find('#wpayme-pay-coupon-message');
        messageContainer.html(message).removeClass('success error').addClass(type);
    }

    // Check if there's a pre-applied coupon from the hidden field
    const preAppliedCoupon = form.find('input[name="wpayme_pay_applied_coupon"]').val();
    if (preAppliedCoupon) {
        try {
            appliedCoupon = JSON.parse(preAppliedCoupon);
            // If coupon is pre-applied, update the UI
            if (appliedCoupon) {
                form.find('#wpayme-pay-coupon-code').prop('disabled', true).val(appliedCoupon.code);
                form.find('#wpayme-pay-apply-coupon').text('<?php esc_attr_e('Remove', 'wpayme'); ?>').removeClass('apply').addClass('remove');
                showCouponMessage(appliedCoupon.message || '<?php esc_attr_e('Coupon applied', 'wpayme'); ?>', 'success');
                
                // Show the price breakdown section if it's hidden
                form.find('.wpayme-pay-breakdown-section').show();
                
                // Ensure price displays properly reflect the discount
                setTimeout(function() {
                    updatePriceBreakdown();
                    updatePriceDisplay();
                }, 50);
            }
        } catch(e) {
            console.error('Error parsing pre-applied coupon:', e);
            appliedCoupon = null;
        }
    }
    
    // Currency symbols mapping
    const currencySymbols = {
        <?php foreach ($currency_symbols as $code => $symbol) : ?>
        '<?php echo esc_js($code); ?>': '<?php echo esc_js($symbol); ?>',
        <?php endforeach; ?>
    };
    
    // Custom amount handling
    const customAmountRadio = form.find('#wpayme-pay-amount-custom');
    const customAmountInput = form.find('#wpayme-pay-custom-amount');
    
    if (customAmountInput.length) {
        customAmountInput.on('focus click', function() {
            customAmountRadio.prop('checked', true);
        });
        
        customAmountInput.on('input', function() {
            customAmountRadio.prop('checked', true);
            updatePriceBreakdown();
        });
    }
    
    // Quantity controls
    const quantityInput = form.find('.wpayme-pay-quantity-input');
    const minusBtn = form.find('.wpayme-pay-quantity-minus');
    const plusBtn = form.find('.wpayme-pay-quantity-plus');
    const priceDisplay = form.find('.wpayme-pay-price-display');
    
    if (quantityInput.length) {
        minusBtn.on('click', function() {
            const currentVal = parseInt(quantityInput.val()) || 1;
            const minVal = parseInt(quantityInput.attr('min')) || 1;
            if (currentVal > minVal) {
                quantityInput.val(currentVal - 1).trigger('change');
            }
        });
        
        plusBtn.on('click', function() {
            const currentVal = parseInt(quantityInput.val()) || 1;
            const maxVal = parseInt(quantityInput.attr('max')) || 0;
            if (maxVal === 0 || currentVal < maxVal) {
                quantityInput.val(currentVal + 1).trigger('change');
            }
        });
        
        quantityInput.on('change', function() {
            // Validate quantity
            let value = parseInt($(this).val()) || 1;
            const min = parseInt($(this).attr('min')) || 1;
            const max = parseInt($(this).attr('max')) || 0;
            
            // Ensure value is at least the minimum
            if (value < min) {
                value = min;
            }
            
            // If max is not 0 (unlimited), ensure value doesn't exceed max
            if (max !== 0 && value > max) {
                value = max;
            }
            
            // Update the input value if it was changed
            if (value !== parseInt($(this).val())) {
                $(this).val(value);
            }
            
            updatePriceBreakdown();
            updatePriceDisplay();
        });
    }
    
    // Variant selection
    const variantSelect = form.find('.wpayme-pay-variant-select');
    if (variantSelect.length) {
        variantSelect.on('change', function() {
            updatePriceBreakdown();
            updatePriceDisplay();
        });
    }
    
    // Currency selection handling
    const currencySelect = form.find('.wpayme-pay-currency-select');
    if (currencySelect.length) {
        currencySelect.on('change', function() {
            const selectedCurrency = $(this).val();
            // Update currency symbol based on selection
            currencySymbol = currencySymbols[selectedCurrency] || selectedCurrency;
            
            // Update all price displays with new currency symbol
            updatePriceBreakdown();
            updatePriceDisplay();
            
            // Update currency symbol in custom amount input
            form.find('.wpayme-pay-currency-symbol').text(currencySymbol);
        });
    }
    
    // Amount selection
    form.find('input[name="wpayme_pay_amount"]').on('change', updatePriceBreakdown);
    
    // Variable to store the total amount
    let total = 0;
    let subtotal = 0;
    
    // Coupon handling
    $('.wpayme-apply-coupon-btn').on('click', function() {
        const couponInput = $(this).closest('.wpayme-coupon-field').find('.wpayme-coupon-input');
        const couponCode = couponInput.val().trim();
        const couponApplied = $(this).closest('.wpayme-coupon-container').find('.wpayme-coupon-applied');
        
        if (!couponCode) {
            couponApplied.html('<span class="error"><?php esc_attr_e('Please enter a coupon code', 'wpayme'); ?></span>').show();
            return;
        }
        
        // Disable the button during the request
        $(this).prop('disabled', true).text('<?php esc_attr_e('Validating...', 'wpayme'); ?>');
        
        // Send AJAX request to validate coupon
        $.ajax({
            url: '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            data: {
                action: 'wpayme_validate_coupon',
                coupon_code: couponCode,
                form_id: <?php echo esc_js($form_id); ?>,
                nonce: '<?php echo esc_js(wp_create_nonce('wpayme_form_nonce')); ?>'
            },
            success: function(response) {
                if (response.success) {
                    // Store coupon data
                    appliedCoupon = response.data;
                    
                    // Show success message - Fix the message display
                    let message = '';
                    if (typeof response.data.message === 'string') {
                        message = response.data.message;
                    } else if (response.data.discount_type === 'percentage') {
                        message = '<?php esc_attr_e('Coupon applied: ', 'wpayme'); ?>' + response.data.discount_amount + '% discount';
                    } else {
                        message = '<?php esc_attr_e('Coupon applied: ', 'wpayme'); ?>' + currencySymbol + response.data.discount_amount + ' discount';
                    }
                    
                    couponApplied.html('<span class="success">' + message + '</span>').show();
                    
                    // Update the hidden field for submission
                    $('input[name="wpayme_pay_coupon_data"]').val(JSON.stringify(appliedCoupon));
                    
                    // Disable the coupon input and change button to "Remove"
                    couponInput.prop('disabled', true);
                    $('.wpayme-apply-coupon-btn').text('<?php esc_attr_e('Remove', 'wpayme'); ?>').addClass('remove');
                    
                    // Show the price breakdown section if it's hidden
                    form.find('.wpayme-pay-breakdown-section').show();
                    
                    // Update price breakdown
                    updatePriceBreakdown();
                    
                    // Update price display to reflect discount
                    updatePriceDisplay();
                } else {
                    // Show error message
                    let errorMessage = '';
                    if (typeof response.data === 'string') {
                        errorMessage = response.data;
                    } else if (response.data && response.data.message) {
                        errorMessage = response.data.message;
                    } else {
                        errorMessage = '<?php esc_attr_e('Invalid coupon code', 'wpayme'); ?>';
                    }
                    
                    couponApplied.html('<span class="error">' + errorMessage + '</span>').show();
                    appliedCoupon = null;
                    $('input[name="wpayme_pay_coupon_data"]').val('');
                }
            },
            error: function() {
                couponApplied.html('<span class="error"><?php esc_attr_e('Error validating coupon', 'wpayme'); ?></span>').show();
                appliedCoupon = null;
                $('input[name="wpayme_pay_coupon_data"]').val('');
            },
            complete: function() {
                // Re-enable the button
                $('.wpayme-apply-coupon-btn').prop('disabled', false);
                
                if (!appliedCoupon) {
                    $('.wpayme-apply-coupon-btn').text('<?php esc_attr_e('Apply', 'wpayme'); ?>').removeClass('remove');
                }
            }
        });
    });
    
    // Handle coupon removal
    $(document).on('click', '.wpayme-apply-coupon-btn.remove', function() {
        // Clear applied coupon
        appliedCoupon = null;
        
        // Clear the hidden field
        $('input[name="wpayme_pay_coupon_data"]').val('');
        
        // Enable the coupon input and reset values
        const couponInput = $(this).closest('.wpayme-coupon-field').find('.wpayme-coupon-input');
        couponInput.prop('disabled', false).val('');
        
        // Reset the button
        $(this).text('<?php esc_attr_e('Apply', 'wpayme'); ?>').removeClass('remove');
        
        // Hide the applied message
        $(this).closest('.wpayme-coupon-container').find('.wpayme-coupon-applied').hide();
        
        // Hide the price breakdown section if there are no shipping, tax, or surcharges
        <?php if (!$shipping_fee && !$tax_rate && !($surcharge_type && $surcharge_amount)) : ?>
        form.find('.wpayme-pay-breakdown-section').hide();
        <?php endif; ?>
        
        // Update price breakdown and display
        updatePriceBreakdown();
        updatePriceDisplay();
    });
    
    // Update price breakdown
    function updatePriceBreakdown() {
        // Get base price
        let basePrice = 0;
        
        <?php if ($amount_method === 'fixed_price' && $fixed_price) : ?>
            basePrice = <?php echo (float) $fixed_price; ?>;
        <?php else : ?>
            const selectedAmount = form.find('input[name="wpayme_pay_amount"]:checked');
            if (selectedAmount.length && selectedAmount.val() !== 'custom') {
                basePrice = parseFloat(selectedAmount.val()) || 0;
            } else if (customAmountRadio && customAmountRadio.is(':checked')) {
                basePrice = parseFloat(customAmountInput.val()) || 0;
            } else {
                const amountInput = form.find('.wpayme-pay-amount-input');
                if (amountInput.length) {
                    basePrice = parseFloat(amountInput.val()) || 0;
                }
            }
        <?php endif; ?>
        
        // Apply variant price if selected
        if (variantSelect && variantSelect.length) {
            const selectedOption = variantSelect.find('option:selected');
            if (selectedOption.length && selectedOption.val() !== '') {
                basePrice = parseFloat(selectedOption.data('price')) || basePrice;
            }
        }
        
        // Apply quantity
        const quantity = parseInt(quantityInput.val()) || 1;
        subtotal = basePrice * quantity;
        
        // Calculate additional fees
        const shippingFee = <?php echo (float) $shipping_fee; ?>;
        const taxRate = <?php echo (float) $tax_rate; ?>;
        const surchargeType = '<?php echo esc_js($surcharge_type); ?>';
        const surchargeAmount = <?php echo (float) $surcharge_amount; ?>;
        
        let tax = 0;
        if (taxRate > 0) {
            tax = subtotal * (taxRate / 100);
        }
        
        let surcharge = 0;
        if (surchargeType === 'flat' && surchargeAmount > 0) {
            surcharge = surchargeAmount;
        } else if (surchargeType === 'percentage' && surchargeAmount > 0) {
            surcharge = subtotal * (surchargeAmount / 100);
        }
        
        // Calculate total without discount
        total = subtotal + shippingFee + tax + surcharge;
        
        // Apply coupon discount if available
        let discount = 0;
        let discountedSubtotal = subtotal;

        if (appliedCoupon) {
            const discountType = appliedCoupon.discount_type;
            const discountAmount = parseFloat(appliedCoupon.discount_amount);
            
            if (discountType === 'percentage') {
                discount = subtotal * (discountAmount / 100);
            } else {
                discount = Math.min(subtotal, discountAmount); // Don't discount more than the subtotal
            }
            
            discountedSubtotal = subtotal - discount;
            total -= discount;
            
            // Show discount row
            form.find('.wpayme-pay-discount').show();
            form.find('.wpayme-pay-discount .wpayme-pay-price-value').text('-' + formatPrice(discount));
            
            // Show and update the price after discount
            form.find('.wpayme-pay-after-discount').show();
            form.find('.wpayme-pay-after-discount .wpayme-pay-price-value').text(formatPrice(discountedSubtotal));
        } else {
            // Hide discount row and price after discount row
            form.find('.wpayme-pay-discount').hide();
            form.find('.wpayme-pay-after-discount').hide();
        }
        
        // Update display
        form.find('.wpayme-pay-subtotal .wpayme-pay-price-value').text(formatPrice(subtotal));
        
        if (taxRate > 0) {
            form.find('.wpayme-pay-tax .wpayme-pay-price-value').text(formatPrice(tax));
        }
        
        if (surchargeType && surchargeAmount > 0) {
            form.find('.wpayme-pay-surcharge .wpayme-pay-price-value').text(formatPrice(surcharge));
        }
        
        form.find('.wpayme-pay-total .wpayme-pay-price-value').text(formatPrice(total));
    }
    
    // Format price with currency symbol
    function formatPrice(amount) {
        return currencySymbol + amount.toFixed(2);
    }
    
    // Function to update the price display based on quantity
    function updatePriceDisplay() {
        if (priceDisplay.length && priceDisplay.data('base-price')) {
            let basePrice = parseFloat(priceDisplay.data('base-price'));
            
            // Apply variant price if selected
            if (variantSelect && variantSelect.length) {
                const selectedOption = variantSelect.find('option:selected');
                if (selectedOption.length && selectedOption.val() !== '') {
                    basePrice = parseFloat(selectedOption.data('price')) || basePrice;
                }
            }
            
            const quantity = parseInt(quantityInput.val()) || 1;
            let totalPrice = basePrice * quantity;
            let discountedPrice = totalPrice;
            let discountText = '';
            
            // Apply discount if a coupon is applied
            if (appliedCoupon) {
                const discountType = appliedCoupon.discount_type;
                const discountAmount = parseFloat(appliedCoupon.discount_amount);
                
                if (discountType === 'percentage') {
                    const discountValue = totalPrice * (discountAmount / 100);
                    discountedPrice = totalPrice - discountValue;
                    discountText = `(${discountAmount}% off)`;
                } else {
                    // For fixed amount, don't discount more than the total price
                    const discountValue = Math.min(totalPrice, discountAmount);
                    discountedPrice = totalPrice - discountValue;
                    discountText = `(${formatPrice(discountValue)} off)`;
                }
                
                // Add strikethrough to the original price
                priceDisplay.html('<s>' + formatPrice(totalPrice) + '</s>');
                
                // Add the discounted price right after the original price
                if (!priceDisplay.next('.wpayme-pay-discounted-price').length) {
                    priceDisplay.after('<span class="wpayme-pay-discounted-price" style="margin-left: 10px; font-weight: bold; color: #28a745;">' + 
                        formatPrice(discountedPrice) + ' <span style="font-size: 0.85em;">' + discountText + '</span></span>');
                } else {
                    priceDisplay.next('.wpayme-pay-discounted-price').html(formatPrice(discountedPrice) + 
                        ' <span style="font-size: 0.85em;">' + discountText + '</span>');
                }
            } else {
                // Remove any strikethrough and show the original price
                priceDisplay.html(formatPrice(totalPrice));
                
                // Remove the discounted price element
                priceDisplay.next('.wpayme-pay-discounted-price').remove();
            }
        }
    }
    
    // Initialize price breakdown
    updatePriceBreakdown();
    
    // Initialize price display
    updatePriceDisplay();
    
    // Form validation
    form.on('submit', function(e) {
        // Set the calculated total amount in the hidden field
        const calculatedAmount = Math.round(total * 100); // Convert to cents
        form.find('input[name="wpayme_pay_calculated_amount"]').val(calculatedAmount);
        
        if (customAmountRadio && customAmountRadio.is(':checked')) {
            const amount = parseFloat(customAmountInput.val());
            if (!amount || amount <= 0) {
                e.preventDefault();
                alert('<?php echo esc_js(__('Please enter a valid amount', 'wpayme')); ?>');
                customAmountInput.focus();
            }
        }
    });
});
<?php
$js = ob_get_clean();
wp_add_inline_script('wpayme-pay-form-script', $js);
?>


