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

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

use Wpayme\WordPress\Number\Number;
use Wpayme\WordPress\Money\Money;

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

if ( ! isset( $post ) ) {
	return;
}

wp_nonce_field( 'wpayme_pay_save_form_options', 'wpayme_pay_nonce' );

// Debug script to ensure amount choices are submitted with the form
$script = "jQuery(document).ready(function($) {
    // Save original form submit function
    var originalSubmit = $('form#post').submit;
    
    // Override form submit to ensure amount choices are included
    $('form#post').submit(function(e) {
        // Log what we're about to submit
        console.log('Form is being submitted');
        
        // Check if amount choices exist
        var amountChoices = $('input[name=\"_wpayme_payment_form_amount_choices[]\"]');
        console.log('Found ' + amountChoices.length + ' amount choice fields');
        
        // Log their values
        amountChoices.each(function(index) {
            console.log('Amount choice ' + index + ' value: ' + $(this).val());
        });
        
        // Call original submit function
        return originalSubmit.apply(this, arguments);
    });
});";
wp_add_inline_script('wpayme-pay-admin', $script);
?>


<table class="form-table">
	<tr>
		<th scope="row">
			<label for="_wpayme_payment_form_config_id">
				<?php esc_html_e( 'Gateway', 'wpayme' ); ?>
			</label>
		</th>
		<td>
			<div class="wpayme-gateway-selection">
				<?php

				$config_id = get_post_meta( $post->ID, '_wpayme_payment_form_config_id', true );

				\Wpayme\WordPress\Pay\Admin\AdminModule::dropdown_configs(
					[
						'name'     => '_wpayme_payment_form_config_id',
						'selected' => $config_id,
					]
				);

				?>
				<button type="button" id="wpayme-payment-methods-info" class="button button-secondary" title="<?php esc_attr_e('View Payment Methods', 'wpayme'); ?>">
					<span class="dashicons dashicons-info"></span> <?php esc_html_e('View Methods', 'wpayme'); ?>
				</button>
			</div>
		</td>
	</tr>
	
	
	
	<tr>
		<th scope="row">
			<label for="_wpayme_payment_form_description">
				<?php esc_html_e( 'Transaction description', 'wpayme' ); ?>
			</label>
		</th>
		<td>
			<?php $description = get_post_meta( $post->ID, '_wpayme_payment_form_description', true ); ?>

			<input class="regular-text" type="text" name="_wpayme_payment_form_description" value="<?php echo esc_attr( $description ); ?>" />
		</td>
	</tr>
</table>

<!-- Product Description Section -->
<div class="wpayme-pay-form-section">
    <h3><?php esc_html_e('Product Description', 'wpayme'); ?></h3>
    <?php
    wp_editor(
        get_post_meta($post->ID, '_wpayme_product_description', true),
        'wpayme_product_description',
        array(
            'textarea_name' => 'wpayme_product_description',
            'media_buttons' => true,
            'textarea_rows' => 5
        )
    );
    ?>
</div>

<!-- Payment Options Section -->
<div class="wpayme-field-row">
    <h3><?php esc_html_e('Payment Options', 'wpayme'); ?></h3>

    <!-- Payment Type -->
    <div class="wpayme-payment-type">
        <label><?php esc_html_e('Amount Type', 'wpayme'); ?></label>
        <div class="wpayme-radio-group">
            <label class="wpayme-radio-label">
                <input type="radio" 
                       name="wpayme_payment_type" 
                       value="one_time" 
                       <?php checked(get_post_meta($post->ID, '_wpayme_payment_type', true) ?: 'one_time', 'one_time'); ?>>
                <span class="wpayme-radio-checkmark"></span>
                <?php esc_html_e('One-time payment', 'wpayme'); ?>
            </label>
            <label class="wpayme-radio-label">
                <input type="radio" 
                       name="wpayme_payment_type" 
                       value="donation" 
                       <?php checked(get_post_meta($post->ID, '_wpayme_payment_type', true), 'donation'); ?>>
                <span class="wpayme-radio-checkmark"></span>
                <?php esc_html_e('Donation', 'wpayme'); ?>
            </label>
        </div>
    </div>

    <!-- Amount Method -->
    <div class="wpayme-amount-method">
        <label><?php esc_html_e('Amount', 'wpayme'); ?></label>
        <select name="_wpayme_payment_form_amount_method" id="wpayme-amount-method-select">
            <?php
            // Set default to fixed_price if no value is set
            $amount_method = get_post_meta($post->ID, '_wpayme_payment_form_amount_method', true);
            if (empty($amount_method)) {
                $amount_method = 'fixed_price';
            }

            $options = [
                'fixed_price' => __('Set fixed price', 'wpayme'),
                \Wpayme\WordPress\Pay\Forms\FormPostType::AMOUNT_METHOD_INPUT_ONLY => __('Show as input field', 'wpayme'),
                \Wpayme\WordPress\Pay\Forms\FormPostType::AMOUNT_METHOD_CHOICES_ONLY => __('Show as choices', 'wpayme'),
                \Wpayme\WordPress\Pay\Forms\FormPostType::AMOUNT_METHOD_CHOICES_AND_INPUT => __('Show as choices with input field', 'wpayme'),
            ];

            foreach ($options as $value => $name) {
                printf(
                    '<option value="%s" %s>%s</option>',
                    esc_attr($value),
                    selected($value, $amount_method, false),
                    esc_html($name)
                );
            }
            ?>
        </select>
    </div>

    <!-- Dynamic fields will be inserted here directly by JavaScript -->

    <!-- Currency Options -->
    <div class="wpayme-currency-options">
        <label><?php esc_html_e('Currency', 'wpayme'); ?></label>
        <select name="wpayme_currency" class="wpayme-currency-select">
            <?php
            $current_currency = get_post_meta($post->ID, '_wpayme_currency', true) ?: 'EUR';
            $currencies = array(
                'EUR' => 'Euro (€)',
                'USD' => 'US Dollar ($)',
                'GBP' => 'British Pound (£)',
                'AUD' => 'Australian Dollar (A$)',
                'CAD' => 'Canadian Dollar (C$)',
                'JPY' => 'Japanese Yen (¥)',
                'NZD' => 'New Zealand Dollar (NZ$)',
                'CHF' => 'Swiss Franc (CHF)',
                'HKD' => 'Hong Kong Dollar (HK$)',
                'SGD' => 'Singapore Dollar (S$)',
                'SEK' => 'Swedish Krona (kr)',
                'DKK' => 'Danish Krone (kr)',
                'NOK' => 'Norwegian Krone (kr)',
                'MXN' => 'Mexican Peso (MX$)',
                'BRL' => 'Brazilian Real (R$)',
                'PLN' => 'Polish Złoty (zł)',
                'ZAR' => 'South African Rand (R)',
                'INR' => 'Indian Rupee (₹)',
                'AED' => 'UAE Dirham (د.إ)',
                'SAR' => 'Saudi Riyal (﷼)',
                'KRW' => 'South Korean Won (₩)',
                'TWD' => 'New Taiwan Dollar (NT$)',
                'MYR' => 'Malaysian Ringgit (RM)',
                'THB' => 'Thai Baht (฿)',
                'PHP' => 'Philippine Peso (₱)',
                'CZK' => 'Czech Koruna (Kč)',
                'ILS' => 'Israeli New Shekel (₪)',
                'HUF' => 'Hungarian Forint (Ft)',
                'RON' => 'Romanian Leu (lei)',
                'TRY' => 'Turkish Lira (₺)',
            );

            // Sort currencies alphabetically by name
            asort($currencies);

            foreach ($currencies as $code => $name) {
                printf(
                    '<option value="%s" %s>%s</option>',
                    esc_attr($code),
                    selected($code, $current_currency, false),
                    esc_html($name)
                );
            }
            ?>
        </select>

        <div class="wpayme-currency-customer-choice">
            <div class="wpayme-toggle-container">
                <label class="wpayme-toggle-switch">
                    <input type="checkbox" 
                           name="wpayme_allow_currency_choice" 
                           value="1" 
                           <?php checked(get_post_meta($post->ID, '_wpayme_allow_currency_choice', true), '1'); ?>>
                    <span class="wpayme-toggle-slider"></span>
                </label>
                <span class="wpayme-toggle-label"><?php esc_html_e('Allow customers to specify currency', 'wpayme'); ?></span>
            </div>
            <p class="wpayme-field-description">
                <?php esc_html_e('When enabled, it allows the customers to select the currency which is used to make the payment. It does not dynamically change the price. No dynamic currency conversion takes place.', 'wpayme'); ?>
            </p>
        </div>
    </div>
</div>

<div class="wpayme-pay-form-section">
    <h3><?php esc_html_e('Product Options', 'wpayme'); ?></h3>
    
    <!-- Thumbnail Upload -->
    <div class="wpayme-field-row">
        <label><?php esc_html_e('Product Image', 'wpayme'); ?></label>
        <div class="wpayme-thumbnail-upload">
            <?php
            $thumbnail_id = get_post_meta($post->ID, '_wpayme_product_thumbnail', true);
            $thumbnail_url = $thumbnail_id ? wp_get_attachment_url($thumbnail_id) : '';
            ?>
            <input type="hidden" name="wpayme_product_thumbnail" id="wpayme_product_thumbnail" value="<?php echo esc_attr($thumbnail_id); ?>">
            <div class="thumbnail-preview">
                <?php if ($thumbnail_url) : ?>
                    <img src="<?php echo esc_url($thumbnail_url); ?>" alt="">
                <?php endif; ?>
            </div>
            <button type="button" class="button upload-thumbnail"><?php esc_html_e('Upload Image', 'wpayme'); ?></button>
            <button type="button" class="button remove-thumbnail"><?php esc_html_e('Remove Image', 'wpayme'); ?></button>
        </div>
    </div>

    <!-- Variants Section -->
    <div class="wpayme-field-row">
        <label><?php esc_html_e('Product Variants', 'wpayme'); ?></label>
        <div class="wpayme-variants-container">
            <?php
            $variants = get_post_meta($post->ID, '_wpayme_product_variants', true) ?: array();
            foreach ($variants as $index => $variant) :
            ?>
            <div class="variant-row">
                <input type="text" name="wpayme_variants[<?php echo esc_attr( $index ); ?>][name]" 
                       value="<?php echo esc_attr($variant['name']); ?>" placeholder="<?php esc_attr_e('Variant Name', 'wpayme'); ?>">
                <input type="number" step="0.01" name="wpayme_variants[<?php echo esc_attr( $index ); ?>][price]" 
                       value="<?php echo esc_attr($variant['price']); ?>" placeholder="<?php esc_attr_e('Price', 'wpayme'); ?>">
                <button type="button" class="button remove-variant"><?php esc_html_e('Remove', 'wpayme'); ?></button>
            </div>
            <?php endforeach; ?>
            <button type="button" class="button add-variant"><?php esc_html_e('Add Variant', 'wpayme'); ?></button>
        </div>
    </div>

    <!-- Quantity Settings -->
    <div class="wpayme-field-row">
        <label><?php esc_html_e('Quantity Settings', 'wpayme'); ?></label>
        <div class="quantity-settings">
            <p class="wpayme-field-description">
                <?php esc_html_e('By default, if you leave these fields empty, the product quantity will be set to 1.', 'wpayme'); ?>
            </p>
            
            <div class="wpayme-quantity-option">
                <div class="wpayme-toggle-container">
                    <label class="wpayme-toggle-switch">
                        <input type="checkbox" name="wpayme_enable_quantity" value="1" 
                               <?php checked(get_post_meta($post->ID, '_wpayme_enable_quantity', true), '1'); ?>>
                        <span class="wpayme-toggle-slider"></span>
                    </label>
                    <span class="wpayme-toggle-label"><?php esc_html_e('Allow users to specify quantity', 'wpayme'); ?></span>
                </div>
                <p class="wpayme-field-description">
                    <?php esc_html_e('When enabled, users can enter the quantity they want to buy.', 'wpayme'); ?>
                </p>
            </div>
            
            <div class="wpayme-quantity-option">
                <label for="wpayme_min_quantity"><?php esc_html_e('Minimum Quantity:', 'wpayme'); ?></label>
                <p class="wpayme-field-description">
                    <?php esc_html_e('The minimum quantity that can be purchased.', 'wpayme'); ?>
                </p>
                <input type="number" id="wpayme_min_quantity" name="wpayme_min_quantity" min="1" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_min_quantity', true) ?: '1'); ?>">
            </div>
            
            <div class="wpayme-quantity-option">
                <label for="wpayme_max_quantity"><?php esc_html_e('Maximum Quantity:', 'wpayme'); ?></label>
                <p class="wpayme-field-description">
                    <?php esc_html_e('The maximum quantity that can be purchased. Enter 0 for unlimited or leave empty for no limit.', 'wpayme'); ?>
                </p>
                <input type="number" id="wpayme_max_quantity" name="wpayme_max_quantity" min="0" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_max_quantity', true)); ?>">
            </div>
            
            <div class="wpayme-quantity-option">
                <div class="wpayme-toggle-container">
                    <label class="wpayme-toggle-switch">
                        <input type="checkbox" name="wpayme_enable_stock" value="1" 
                               <?php checked(get_post_meta($post->ID, '_wpayme_enable_stock', true), '1'); ?>>
                        <span class="wpayme-toggle-slider"></span>
                    </label>
                    <span class="wpayme-toggle-label"><?php esc_html_e('Enable stock control', 'wpayme'); ?></span>
                </div>
                <p class="wpayme-field-description">
                    <?php esc_html_e('When enabled, you can specify the quantity available for this product. It will be decreased each time the item is purchased. When stock reaches zero, an "Out of stock" message will be displayed instead of the buy button.', 'wpayme'); ?>
                </p>
            </div>
            
            <div class="wpayme-quantity-option wpayme-stock-quantity-option" style="<?php echo get_post_meta($post->ID, '_wpayme_enable_stock', true) ? '' : 'display: none;'; ?>">
                <label for="wpayme_stock_quantity"><?php esc_html_e('Quantity Available:', 'wpayme'); ?></label>
                <p class="wpayme-field-description">
                    <?php esc_html_e('Specify the quantity available for this product.', 'wpayme'); ?>
                </p>
                <input type="number" id="wpayme_stock_quantity" name="wpayme_stock_quantity" min="0" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_stock_quantity', true)); ?>">
            </div>
            
            <div class="wpayme-quantity-option wpayme-stock-quantity-option" style="<?php echo get_post_meta($post->ID, '_wpayme_enable_stock', true) ? '' : 'display: none;'; ?>">
                <div class="wpayme-toggle-container">
                    <label class="wpayme-toggle-switch">
                        <input type="checkbox" name="wpayme_show_stock" value="1" 
                               <?php checked(get_post_meta($post->ID, '_wpayme_show_stock', true), '1'); ?>>
                        <span class="wpayme-toggle-slider"></span>
                    </label>
                    <span class="wpayme-toggle-label"><?php esc_html_e('Show the available quantity in the payment form', 'wpayme'); ?></span>
                </div>
                <p class="wpayme-field-description">
                    <?php esc_html_e('When this is enabled, the number of remaining items is displayed on the payment form.', 'wpayme'); ?>
                </p>
            </div>
        </div>
    </div>

    <!-- Shipping & Tax -->
    <div class="wpayme-field-row">
        <label><?php esc_html_e('Shipping & Tax', 'wpayme'); ?></label>
        <div class="shipping-tax-settings">
            <input type="number" step="0.01" name="wpayme_shipping_fee" 
                   value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_shipping_fee', true)); ?>" 
                   placeholder="<?php esc_attr_e('Shipping Fee', 'wpayme'); ?>">
            <input type="number" step="0.01" name="wpayme_tax_rate" 
                   value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_tax_rate', true)); ?>" 
                   placeholder="<?php esc_attr_e('Tax Rate %', 'wpayme'); ?>">
        </div>
    </div>

    <!-- Thank You Page -->
    <div class="wpayme-field-row">
        <label><?php esc_html_e('Thank You Page', 'wpayme'); ?></label>
        <?php
        wp_dropdown_pages(array(
            'name' => 'wpayme_thank_you_page',
            'selected' => esc_attr( get_post_meta($post->ID, '_wpayme_thank_you_page', true) ),
            'show_option_none' => esc_html__('Default Thank You Page', 'wpayme'),
        ));
        ?>
    </div>

    <!-- Button Appearance -->
    <div class="wpayme-field-row">
        <label><?php esc_html_e('Button Appearance', 'wpayme'); ?></label>
        
        <div class="wpayme-button-settings">
            <!-- Button Text -->
            <div class="wpayme-button-text">
                <label><?php esc_html_e('Button Text', 'wpayme'); ?></label>
                <input type="text" 
                       name="wpayme_button_text" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_button_text', true) ?: __('Buy Now', 'wpayme')); ?>" 
                       placeholder="<?php esc_attr_e('Button Text', 'wpayme'); ?>">
            </div>

            <!-- Button CSS Class -->
            <div class="wpayme-button-class">
                <label><?php esc_html_e('Button CSS Class', 'wpayme'); ?></label>
                <p class="wpayme-field-description">
                    <?php esc_html_e('CSS class to be assigned to the button. This is used for styling purposes.', 'wpayme'); ?>
                </p>
                <input type="text" 
                       name="wpayme_button_class" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_button_class', true)); ?>" 
                       placeholder="<?php esc_attr_e('custom-button-class', 'wpayme'); ?>">
            </div>

            <!-- Button Text Color -->
            <div class="wpayme-button-text-color">
                <label><?php esc_html_e('Button Text Color', 'wpayme'); ?></label>
                <input type="text" 
                       name="wpayme_button_text_color" 
                       class="color-picker" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_button_text_color', true) ?: '#ffffff'); ?>">
            </div>

            <!-- Button Color -->
            <div class="wpayme-button-color">
                <label><?php esc_html_e('Button Color', 'wpayme'); ?></label>
                <input type="text" 
                       name="wpayme_button_color" 
                       class="color-picker" 
                       value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_button_color', true) ?: '#000000'); ?>">
            </div>
        </div>
    </div>
</div>

<div class="wpayme-field-row">
        <h3><?php esc_html_e('Transaction Surcharge', 'wpayme'); ?></h3>
        
        <div class="wpayme-surcharge-type">
            <label><?php esc_html_e('Transaction Surcharge Amount Type:', 'wpayme'); ?></label>
            <select name="wpayme_surcharge_type" id="wpayme-surcharge-type">
                <option value="flat" <?php selected(get_post_meta($post->ID, '_wpayme_surcharge_type', true), 'flat'); ?>>
                    <?php esc_html_e('Flat Rate', 'wpayme'); ?>
                </option>
                <option value="percentage" <?php selected(get_post_meta($post->ID, '_wpayme_surcharge_type', true), 'percentage'); ?>>
                    <?php esc_html_e('Percentage', 'wpayme'); ?>
                </option>
            </select>
        </div>

        <div class="wpayme-surcharge-amount">
            <label><?php esc_html_e('Surcharge Amount', 'wpayme'); ?></label>
            <p class="wpayme-field-description">
                <?php esc_html_e('Numbers only, do not enter any currency symbol. Example: 5', 'wpayme'); ?>
            </p>
            <input type="number" 
                   name="wpayme_surcharge_amount" 
                   value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_surcharge_amount', true)); ?>"
                   step="0.01"
                   min="0">
        </div>

        <div class="wpayme-surcharge-label">
            <label><?php esc_html_e('Surcharge Label', 'wpayme'); ?></label>
            <p class="wpayme-field-description">
                <?php esc_html_e('Specify the label to use for the surcharge. Example: Processing Fee.', 'wpayme'); ?>
            </p>
            <input type="text" 
                   name="wpayme_surcharge_label" 
                   value="<?php echo esc_attr(get_post_meta($post->ID, '_wpayme_surcharge_label', true)); ?>"
                   placeholder="<?php esc_attr_e('Processing Fee', 'wpayme'); ?>">
        </div>
</div>
