<?php

namespace GriffinForms\Admin\Html\FormControls\Field\FieldOptionsTraits;

trait Payment
{
    private function paymentHtml()
    {
        $products = $this->normalizePaymentProducts($this->value);
        wp_enqueue_media();
        echo '<div class="griffinforms-payment-options">';
        echo '<div class="griffinforms-payment-products-wrapper mb-3">';
        echo '<div id="griffinforms-payment-products" class="accordion griffinforms-payment-products">';

        $index = 1;
        foreach ($products as $product) {
            echo $this->buildPaymentProductCardHtml($product, (string) $index, $product['id'], $index === 1);
            $index++;
        }

        echo '</div>'; // accordion
        echo '</div>'; // wrapper
        echo '<div class="d-flex gap-2 mt-3 justify-content-start griffinforms-payment-actions">';
        echo '<button type="button" class="button button-primary" id="griffinforms-payment-add-product">';
        echo esc_html__('Add product', 'griffinforms-form-builder');
        echo '</button>';
        echo '<button type="button" class="button" id="griffinforms-payment-collapse-products">';
        echo esc_html__('Collapse all', 'griffinforms-form-builder');
        echo '</button>';
        echo '</div>';
        echo '</div>';

        $template_html = $this->buildPaymentProductCardHtml($this->getDefaultPaymentProduct(), '__INDEX__', '__ID__', true);
        echo '<script type="text/plain" id="griffinforms-payment-product-template">' . wp_kses_post($template_html) . '</script>';

        $this->paymentJs();
    }

    private function normalizePaymentProducts($value): array
    {
        if (!is_array($value) || empty($value)) {
            return [$this->getDefaultPaymentProduct()];
        }

        $normalized = [];
        foreach ($value as $product) {
            $normalized[] = $this->mergePaymentProductDefaults($product);
        }

        return $normalized;
    }

    private function getDefaultPaymentProduct(): array
    {
        return array(
            'id'             => 'prod_' . wp_generate_password(6, false, false),
            'name'           => __('Sample Product', 'griffinforms-form-builder'),
            'price'          => 25,
            'description'    => __('Describe the product benefits or what is included.', 'griffinforms-form-builder'),
            'image'          => '',
            'link'           => '',
            'default_qty'    => 1,
            'min_qty'        => 1,
            'max_qty'        => 1,
            'allow_quantity' => 0,
            'featured'       => 0,
        );
    }

    private function mergePaymentProductDefaults($product): array
    {
        $defaults = $this->getDefaultPaymentProduct();
        if (!is_array($product)) {
            return $defaults;
        }

        return array_merge($defaults, array_intersect_key($product, $defaults));
    }

    private function buildPaymentProductCardHtml(array $product, string $index_label, string $product_id, bool $expanded = false): string
    {
        $product = $this->mergePaymentProductDefaults($product);
        $heading_id = 'griffinforms-payment-product-heading-' . $product_id;
        $collapse_id = 'griffinforms-payment-product-body-' . $product_id;
        $button_classes = $expanded ? 'accordion-button' : 'accordion-button collapsed';
        $collapse_classes = $expanded ? 'accordion-collapse collapse show' : 'accordion-collapse collapse';

        ob_start();
        ?>
        <div class="accordion-item griffinforms-payment-product-card mb-2" data-product-id="<?php echo esc_attr($product_id); ?>">
            <h2 class="accordion-header griffinforms-payment-product-header" id="<?php echo esc_attr($heading_id); ?>">
                <span class="griffinforms-payment-product-handle text-muted">
                    <?php echo wp_kses_post($this->mIcon('drag_indicator', 'rounded', 'return')); ?>
                </span>
                <button class="<?php echo esc_attr(trim($button_classes . ' griffinforms-payment-product-toggle')); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?php echo esc_attr($collapse_id); ?>" aria-expanded="<?php echo $expanded ? 'true' : 'false'; ?>" aria-controls="<?php echo esc_attr($collapse_id); ?>">
                    <div class="w-100 text-start d-flex flex-column">
                        <div class="d-flex justify-content-between align-items-center gap-2">
                            <strong class="griffinforms-payment-product-label">
                                <?php printf(esc_html__('Product %s', 'griffinforms-form-builder'), esc_html($index_label)); ?>
                            </strong>
                            <span class="text-muted small griffinforms-payment-product-name-preview">
                                <?php echo esc_html($product['name']); ?>
                            </span>
                        </div>
                    </div>
                </button>
                <button type="button" class="button-link-delete griffinforms-payment-remove-product" aria-label="<?php esc_attr_e('Delete product', 'griffinforms-form-builder'); ?>">
                    <?php esc_html_e('Delete', 'griffinforms-form-builder'); ?>
                </button>
            </h2>
            <div id="<?php echo esc_attr($collapse_id); ?>" class="<?php echo esc_attr($collapse_classes); ?>" aria-labelledby="<?php echo esc_attr($heading_id); ?>">
                <div class="accordion-body">
                    <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label"><?php esc_html_e('Product name', 'griffinforms-form-builder'); ?></label>
                        <input type="text" class="form-control griffinforms-payment-product-name" value="<?php echo esc_attr($product['name']); ?>" placeholder="<?php esc_attr_e('e.g., Premium Consultation', 'griffinforms-form-builder'); ?>" />
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><?php esc_html_e('Price', 'griffinforms-form-builder'); ?></label>
                        <input type="number" min="0" step="0.01" class="form-control griffinforms-payment-product-price" value="<?php echo esc_attr($product['price']); ?>" />
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><?php esc_html_e('Default quantity', 'griffinforms-form-builder'); ?></label>
                        <input type="number" min="1" step="1" class="form-control griffinforms-payment-product-default-qty" value="<?php echo esc_attr($product['default_qty']); ?>" />
                    </div>
                    <div class="col-12">
                        <label class="form-label"><?php esc_html_e('Short description', 'griffinforms-form-builder'); ?></label>
                        <textarea class="form-control griffinforms-payment-product-description" rows="2" placeholder="<?php esc_attr_e('Summarize what the buyer receives.', 'griffinforms-form-builder'); ?>"><?php echo esc_textarea($product['description']); ?></textarea>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label"><?php esc_html_e('Product image', 'griffinforms-form-builder'); ?></label>
                        <div class="griffinforms-payment-product-image-control border rounded p-2">
                            <div class="griffinforms-payment-product-image-preview mb-2 <?php echo empty($product['image']) ? 'is-empty' : ''; ?>">
                                <?php if (!empty($product['image'])) : ?>
                                    <img src="<?php echo esc_url($product['image']); ?>" alt="" class="img-fluid rounded" />
                                <?php else : ?>
                                    <div class="text-muted small"><?php esc_html_e('No image selected', 'griffinforms-form-builder'); ?></div>
                                <?php endif; ?>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="button button-secondary griffinforms-payment-product-image-select">
                                    <?php esc_html_e('Select image', 'griffinforms-form-builder'); ?>
                                </button>
                                <button type="button" class="button griffinforms-payment-product-image-remove" <?php echo empty($product['image']) ? 'disabled' : ''; ?>>
                                    <?php esc_html_e('Remove', 'griffinforms-form-builder'); ?>
                                </button>
                            </div>
                            <input type="hidden" class="griffinforms-payment-product-image" value="<?php echo esc_attr($product['image']); ?>" />
                        </div>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label"><?php esc_html_e('Product page URL', 'griffinforms-form-builder'); ?></label>
                        <input type="text" class="form-control griffinforms-payment-product-link" value="<?php echo esc_attr($product['link']); ?>" placeholder="https://example.com/details" />
                    </div>
                    <div class="col-md-12">
                        <label class="form-label d-flex align-items-end justify-content-start">
                            <span><?php esc_html_e('Internal SKU / ID', 'griffinforms-form-builder'); ?></span>
                            <span class="text-muted small ms-2"><?php esc_html_e('Required; must be unique', 'griffinforms-form-builder'); ?></span>
                        </label>
                        <div class="d-flex gap-2 align-items-center">
                            <input type="text" class="form-control griffinforms-payment-product-sku" value="<?php echo esc_attr($product['id']); ?>" placeholder="prod_123" />
                            <button type="button" class="button button-secondary griffinforms-payment-sku-generate" aria-label="<?php esc_attr_e('Regenerate SKU', 'griffinforms-form-builder'); ?>">
                                <?php esc_html_e('Generate', 'griffinforms-form-builder'); ?>
                            </button>
                        </div>
                        <div class="text-muted small mt-1"><?php esc_html_e('Leave as-is or generate a new SKU. Must not be empty; duplicates will be auto-fixed on save.', 'griffinforms-form-builder'); ?></div>
                    </div>
                    <div class="col-md-12 mt-4">
                        <input type="checkbox" class="griffinforms-payment-product-featured" id="griffinforms-payment-featured-<?php echo esc_attr($product_id); ?>" <?php checked($product['featured']); ?> />
                        <label for="griffinforms-payment-featured-<?php echo esc_attr($product_id); ?>">
                            <?php esc_html_e('Highlight as featured', 'griffinforms-form-builder'); ?>
                        </label>
                    </div>
                    <div class="col-md-8 mt-4 d-flex flex-wrap align-items-center gap-3 griffinforms-payment-quantity-controls">
                        <label class="m-0 griffinforms-payment-allow-qty-label">
                        <input type="checkbox" class="griffinforms-payment-product-allow-qty" id="griffinforms-payment-allow-qty-<?php echo esc_attr($product_id); ?>" <?php checked($product['allow_quantity']); ?> />
                            <?php esc_html_e('Allow buyers to choose quantity', 'griffinforms-form-builder'); ?>
                        </label>
                        <div class="d-flex gap-3 flex-wrap griffinforms-payment-quantity-range">
                            <div>
                                <label class="form-label mb-1"><?php esc_html_e('Min quantity', 'griffinforms-form-builder'); ?></label>
                                <input type="number" min="1" step="1" class="form-control griffinforms-payment-product-min-qty" value="<?php echo esc_attr($product['min_qty']); ?>" <?php disabled(!$product['allow_quantity']); ?> />
                            </div>
                            <div>
                                <label class="form-label mb-1"><?php esc_html_e('Max quantity', 'griffinforms-form-builder'); ?></label>
                                <input type="number" min="1" step="1" class="form-control griffinforms-payment-product-max-qty" value="<?php echo esc_attr($product['max_qty']); ?>" <?php disabled(!$product['allow_quantity']); ?> />
                            </div>
                        </div>
                    </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    private function paymentJs()
    {
        $template_html = wp_json_encode($this->buildPaymentProductCardHtml($this->getDefaultPaymentProduct(), '__INDEX__', '__ID__'));
        ob_start();
        ?>
        jQuery(function($) {
            const productsWrap = $('#griffinforms-payment-products');
            let productCount = productsWrap.children('.griffinforms-payment-product-card').length;
            const productTemplate = <?php echo $template_html; ?>;
            const collapseBtn = $('#griffinforms-payment-collapse-products');
            const CollapseClass = window.bootstrap ? window.bootstrap.Collapse : null;
            const noImageText = '<?php echo esc_js(__('No image selected', 'griffinforms-form-builder')); ?>';

            initSortable();
            updatePaymentProductLabels();
            applyQuantityFieldState();

            $('#griffinforms-payment-add-product')
                .off('click.griffinformsPayment')
                .on('click.griffinformsPayment', function(e) {
                    e.preventDefault();
                    addPaymentProduct();
                });

            collapseBtn
                .off('click.griffinformsPayment')
                .on('click.griffinformsPayment', function(e) {
                    e.preventDefault();
                    toggleAllProducts();
                });

            productsWrap
                .off('click.griffinformsPaymentRemove', '.griffinforms-payment-remove-product')
                .on('click.griffinformsPaymentRemove', '.griffinforms-payment-remove-product', function(e) {
                e.preventDefault();
                const remaining = productsWrap.children('.griffinforms-payment-product-card').length - 1;
                if (remaining < 1) {
                    alert('<?php echo esc_js(__('At least one product is required.', 'griffinforms-form-builder')); ?>');
                    return;
                }
                $(this).closest('.griffinforms-payment-product-card').remove();
                updatePaymentProductLabels();
            });

            productsWrap.on('keyup change', '.griffinforms-payment-product-name', function() {
                const name = $(this).val().trim() || '<?php echo esc_js(__('Unnamed product', 'griffinforms-form-builder')); ?>';
                $(this).closest('.griffinforms-payment-product-card').find('.griffinforms-payment-product-name-preview').text('— ' + name);
            });

            productsWrap.on('click', '.griffinforms-payment-sku-generate', function(e) {
                e.preventDefault();
                const card = $(this).closest('.griffinforms-payment-product-card');
                const input = card.find('.griffinforms-payment-product-sku');
                const newSku = 'prod_' + Math.random().toString(36).substring(2, 8);
                input.val(newSku).trigger('change');
            });

            productsWrap.on('keyup change', '.griffinforms-payment-product-sku', function() {
                var value = $(this).val().trim();
                const card = $(this).closest('.griffinforms-payment-product-card');
                if (value) {
                    card.attr('data-product-id', value);
                } else {
                    card.attr('data-product-id', '');
                }
            });

            productsWrap.on('change', '.griffinforms-payment-product-allow-qty', function() {
                const card = $(this).closest('.griffinforms-payment-product-card');
                toggleQuantityInputs(card);
            });

            productsWrap.on('click', '.griffinforms-payment-product-image-select', function(e) {
                e.preventDefault();
                const card = $(this).closest('.griffinforms-payment-product-card');
                const frame = wp.media({
                    title: '<?php echo esc_js(__('Select product image', 'griffinforms-form-builder')); ?>',
                    button: { text: '<?php echo esc_js(__('Use image', 'griffinforms-form-builder')); ?>' },
                    multiple: false
                });

                frame.on('select', function() {
                    const attachment = frame.state().get('selection').first().toJSON();
                    setProductImage(card, attachment.url);
                    if (typeof frame.close === 'function') {
                        frame.close();
                    }
                    setTimeout(function() {
                        $('.media-modal-close').trigger('click');
                    }, 50);
                });

                frame.open();
            });

            productsWrap.on('click', '.griffinforms-payment-product-image-remove', function(e) {
                e.preventDefault();
                const card = $(this).closest('.griffinforms-payment-product-card');
                setProductImage(card, '');
            });

            function addPaymentProduct() {
                productCount++;
                const productId = 'prod_' + Date.now();
                let cardHtml = productTemplate.replace(/__INDEX__/g, productCount).replace(/__ID__/g, productId);
                const $card = $(cardHtml);
                // lock SKU by default on new cards
                $card.find('.griffinforms-payment-product-sku').prop('readonly', true);
                productsWrap.append($card);
                const collapseEl = $card.find('.accordion-collapse')[0];
                if (CollapseClass && collapseEl) {
                    CollapseClass.getOrCreateInstance(collapseEl, {toggle: false}).show();
                }
                toggleQuantityInputs($card);
                updatePaymentProductLabels();
                collapseBtn.text('<?php echo esc_js(__('Collapse all', 'griffinforms-form-builder')); ?>');
            }

            function updatePaymentProductLabels() {
                productsWrap.children('.griffinforms-payment-product-card').each(function(index) {
                    const label = '<?php echo esc_js(__('Product %s', 'griffinforms-form-builder')); ?>'.replace('%s', index + 1);
                    $(this).find('.griffinforms-payment-product-label').text(label);
                });
            }

            function toggleAllProducts() {
                const openCount = productsWrap.find('.accordion-collapse.show').length;
                if (openCount > 0) {
                    productsWrap.find('.accordion-collapse').each(function() {
                        if (CollapseClass) {
                            CollapseClass.getOrCreateInstance(this, {toggle: false}).hide();
                        }
                    });
                    collapseBtn.text('<?php echo esc_js(__('Expand all', 'griffinforms-form-builder')); ?>');
                } else {
                    productsWrap.find('.accordion-collapse').each(function() {
                        if (CollapseClass) {
                            CollapseClass.getOrCreateInstance(this, {toggle: false}).show();
                        }
                    });
                    collapseBtn.text('<?php echo esc_js(__('Collapse all', 'griffinforms-form-builder')); ?>');
                }
            }

            function setProductImage(card, url) {
                const preview = card.find('.griffinforms-payment-product-image-preview');
                const removeBtn = card.find('.griffinforms-payment-product-image-remove');
                const input = card.find('.griffinforms-payment-product-image');

                input.val(url);
                if (url) {
                    preview.removeClass('is-empty').html('<img src="' + url + '" alt="" class="img-fluid rounded" />');
                    removeBtn.prop('disabled', false);
                } else {
                    preview.addClass('is-empty').html('<div class="text-muted small">' + noImageText + '</div>');
                    removeBtn.prop('disabled', true);
                }
            }

            function toggleQuantityInputs(card) {
                const allow = card.find('.griffinforms-payment-product-allow-qty').is(':checked');
                card.find('.griffinforms-payment-product-min-qty, .griffinforms-payment-product-max-qty').prop('disabled', !allow);
            }

            function applyQuantityFieldState() {
                productsWrap.children('.griffinforms-payment-product-card').each(function() {
                    toggleQuantityInputs($(this));
                });
            }

            function initSortable() {
                if (typeof $.fn.sortable === 'undefined') {
                    return;
                }
                productsWrap.sortable({
                    handle: '.griffinforms-payment-product-handle',
                    opacity: 0.9,
                    placeholder: 'griffinforms-payment-product-placeholder',
                    update: updatePaymentProductLabels
                });
            }
        });
        <?php
        $js = ob_get_clean();
        wp_add_inline_script('griffinforms-global-js', $js);
    }
}
