<?php
/**
 * Mini Cart Widget — Render Functions
 * Standalone functions prefixed ggmc_mini_cart_ for use by the widget class.
 *
 * @package GGM_Commerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Main render entry point. Called from GGM_Commerce_Widget_Mini_Cart::render().
 *
 * @param \GGM_Commerce_Widget_Mini_Cart $widget The widget instance.
 */
function ggmc_mini_cart_render( $widget ) {
    $settings = $widget->get_settings_for_display();

    // Use the proper cart class instead of direct session access
    $cart_instance = GGM_Commerce_Cart::get_instance();
    $cart_items    = $cart_instance->get_cart_items_with_products();
    $cart_count    = $cart_instance->get_cart_count();
    $cart_total    = $cart_instance->get_cart_total();

    $cart_style    = $settings['cart_style'];
    $header_title  = ! empty( $settings['header_title_text'] ) ? $settings['header_title_text'] : __( 'Shopping Cart', 'ggm-commerce' );
    $empty_cart_text = ! empty( $settings['empty_cart_text'] ) ? $settings['empty_cart_text'] : __( 'Your cart is empty', 'ggm-commerce' );
    $show_dropdown = $settings['show_dropdown'] === 'yes';

    // Get cart URL for when dropdown is disabled
    $cart_url = ggmc_mini_cart_resolve_cart_url( $settings );
    ?>

    <div class="ggmc-mini-cart-widget" data-cart-count="<?php echo esc_attr( $cart_count ); ?>" data-show-image="<?php echo esc_attr( $settings['show_product_image'] ); ?>">
        <?php if ( $show_dropdown ) : ?>
        <div class="mini-cart-button" onclick="toggleMiniCart()">
        <?php else : ?>
        <a href="<?php echo esc_url( $cart_url ); ?>" class="mini-cart-button">
        <?php endif; ?>
            <?php if ( $cart_style !== 'text_only' && ! empty( $settings['cart_icon']['value'] ) ) : ?>
                <span class="mini-cart-icon-wrapper">
                    <?php ggmc_render_icon( $settings['cart_icon'], [ 'aria-hidden' => 'true' ] ); ?>
                    <?php if ( $cart_style === 'icon_count' || $cart_style === 'icon_count_total' ) : ?>
                        <span class="cart-count"><?php echo esc_html( $cart_count ); ?></span>
                    <?php endif; ?>
                </span>
            <?php endif; ?>

            <?php if ( $cart_style === 'icon_total' || $cart_style === 'icon_count_total' ) : ?>
                <span class="cart-total">$<?php echo esc_html( number_format( $cart_total, 2 ) ); ?></span>
            <?php endif; ?>

            <?php if ( $cart_style === 'text_only' ) : ?>
                <span class="cart-text"><?php echo esc_html( $settings['cart_text'] ?? 'Cart' ); ?> (<?php echo esc_html( $cart_count ); ?>)</span>
            <?php endif; ?>
        <?php if ( $show_dropdown ) : ?>
        </div>
        <?php else : ?>
        </a>
        <?php endif; ?>

        <?php if ( $show_dropdown ) : ?>
        <div class="mini-cart-dropdown" id="mini-cart-dropdown" style="display: none;">
            <div class="mini-cart-header">
                <h4><?php echo esc_html( $header_title ); ?></h4>
                <button class="close-mini-cart" onclick="toggleMiniCart()">&times;</button>
            </div>

            <div class="mini-cart-items">
                <?php if ( empty( $cart_items ) ) : ?>
                    <p class="empty-cart"><?php echo esc_html( $empty_cart_text ); ?></p>
                <?php else : ?>
                    <?php foreach ( $cart_items as $item ) : ?>
                        <div class="mini-cart-item" data-key="<?php echo esc_attr( $item->cart_key ); ?>">
                            <?php if ( $settings['show_product_image'] === 'yes' ) : ?>
                            <div class="item-image">
                                <?php if ( ! empty( $item->featured_image ) ) : ?>
                                    <img src="<?php echo esc_url( $item->featured_image ); ?>" alt="<?php echo esc_attr( $item->name ); ?>">
                                <?php else : ?>
                                    <div class="placeholder-image"><?php esc_html_e( 'No Image', 'ggm-commerce' ); ?></div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                            <div class="item-details">
                                <h5><?php echo esc_html( $item->name ); ?></h5>
                                <?php if ( ! empty( $item->variation_display ) ) : ?>
                                    <div class="item-variation"><?php echo esc_html( $item->variation_display ); ?></div>
                                <?php endif; ?>
                                <div class="item-price-qty">
                                    <span class="quantity"><?php echo esc_html( sprintf(
                                        /* translators: %d: item quantity */
                                        __( 'Qty: %d', 'ggm-commerce' ),
                                        $item->quantity
                                    ) ); ?></span>
                                    <span class="price">$<?php echo esc_html( number_format( $item->line_total, 2 ) ); ?></span>
                                </div>
                            </div>
                            <button class="remove-item" onclick="removeFromCart('<?php echo esc_js( $item->cart_key ); ?>')" title="<?php esc_attr_e( 'Remove item', 'ggm-commerce' ); ?>">
                                <i class="eicon-close" aria-hidden="true"></i>
                            </button>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <?php if ( ! empty( $cart_items ) ) : ?>
                <?php ggmc_mini_cart_render_footer( $settings, $cart_total ); ?>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <?php ggmc_mini_cart_render_script( $settings ); ?>
    <?php
}

/**
 * Resolve the cart page URL from widget settings or site options.
 *
 * @param array $settings Widget settings.
 * @return string Resolved cart URL.
 */
function ggmc_mini_cart_resolve_cart_url( $settings ) {
    if ( ! empty( $settings['cart_page_url']['url'] ) ) {
        return $settings['cart_page_url']['url'];
    }
    $cart_page_id = get_option( 'ggm_commerce_cart_page_id' );
    return $cart_page_id ? get_permalink( $cart_page_id ) : home_url( '/cart/' );
}

/**
 * Resolve the checkout page URL from widget settings or site options.
 *
 * @param array $settings Widget settings.
 * @return string Resolved checkout URL.
 */
function ggmc_mini_cart_resolve_checkout_url( $settings ) {
    if ( ! empty( $settings['checkout_page_url']['url'] ) ) {
        return $settings['checkout_page_url']['url'];
    }
    $checkout_page_id = get_option( 'ggm_commerce_checkout_page_id' );
    return $checkout_page_id ? get_permalink( $checkout_page_id ) : home_url( '/checkout/' );
}

/**
 * Render the mini cart footer (total + action buttons).
 *
 * @param array $settings   Widget settings.
 * @param float $cart_total Cart total value.
 */
function ggmc_mini_cart_render_footer( $settings, $cart_total ) {
    $cart_url     = ggmc_mini_cart_resolve_cart_url( $settings );
    $checkout_url = ggmc_mini_cart_resolve_checkout_url( $settings );

    $cart_target     = ! empty( $settings['cart_page_url']['is_external'] ) ? 'target="_blank"' : '';
    $checkout_target = ! empty( $settings['checkout_page_url']['is_external'] ) ? 'target="_blank"' : '';
    $cart_nofollow     = ! empty( $settings['cart_page_url']['nofollow'] ) ? 'rel="nofollow"' : '';
    $checkout_nofollow = ! empty( $settings['checkout_page_url']['nofollow'] ) ? 'rel="nofollow"' : '';
    ?>
    <div class="mini-cart-footer">
        <div class="cart-total-display">
            <strong><?php echo esc_html( sprintf(
                /* translators: %s: formatted cart total amount */
                __( 'Total: $%s', 'ggm-commerce' ),
                number_format( $cart_total, 2 )
            ) ); ?></strong>
        </div>
        <div class="cart-actions">
            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $cart_target and $cart_nofollow are sanitized HTML attributes ?>
            <a href="<?php echo esc_url( $cart_url ); ?>" class="view-cart-btn" <?php echo $cart_target; ?> <?php echo $cart_nofollow; ?>><?php esc_html_e( 'View Cart', 'ggm-commerce' ); ?></a>
            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $checkout_target and $checkout_nofollow are sanitized HTML attributes ?>
            <a href="<?php echo esc_url( $checkout_url ); ?>" class="checkout-btn" <?php echo $checkout_target; ?> <?php echo $checkout_nofollow; ?>><?php esc_html_e( 'Checkout', 'ggm-commerce' ); ?></a>
        </div>
    </div>
    <?php
}

/**
 * Render the inline JavaScript block for mini cart interactivity.
 *
 * @param array $settings Widget settings.
 */
function ggmc_mini_cart_render_script( $settings ) {
    ?>
    <script>
    // Mini cart functionality
    function toggleMiniCart() {
        const dropdown = document.getElementById('mini-cart-dropdown');
        if (dropdown.style.display === 'none' || dropdown.style.display === '') {
            dropdown.style.display = 'block';
            // Close when clicking outside
            setTimeout(() => {
                document.addEventListener('click', closeMiniCartOnOutsideClick);
            }, 100);
        } else {
            dropdown.style.display = 'none';
            document.removeEventListener('click', closeMiniCartOnOutsideClick);
        }
    }

    function closeMiniCartOnOutsideClick(event) {
        const miniCart = event.target.closest('.ggmc-mini-cart-widget');
        if (!miniCart) {
            document.getElementById('mini-cart-dropdown').style.display = 'none';
            document.removeEventListener('click', closeMiniCartOnOutsideClick);
        }
    }

    function removeFromCart(cartKey) {
        if (!confirm('Remove this item from your cart?')) {
            return;
        }

        jQuery.ajax({
            url: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
            type: 'POST',
            data: {
                action: 'ggm_commerce_remove_from_cart',
                cart_item_id: cartKey,
                nonce: '<?php echo esc_js( wp_create_nonce( 'ggm_commerce_nonce' ) ); ?>'
            },
            success: function(response) {
                if (response.success) {
                    // Trigger the cart update event instead of page reload
                    jQuery(document).trigger('ggm_commerce_cart_updated', {
                        count: response.data.cart_count,
                        total: response.data.cart_total,
                        items: response.data.cart_items || [],
                        action: 'remove_from_cart',
                        cart_empty: response.data.cart_empty
                    });

                    // Show success message
                    if (typeof showCartMessage === 'function') {
                        showCartMessage(response.data.message, 'success');
                    }
                } else {
                    alert('Error removing item from cart');
                }
            },
            error: function() {
                alert('Error removing item from cart');
            }
        });
    }

    // Listen for cart update events from other widgets
    jQuery(document).ready(function($) {
        $(document).on('ggm_commerce_cart_updated', function(event, data) {
            // Update cart count and total in mini cart
            $('.ggmc-mini-cart-widget .cart-count').text(data.count || 0);

            // Format total - handle both number and string formats
            var totalValue = parseFloat(data.total) || 0;
            $('.ggmc-mini-cart-widget .cart-total').text('$' + totalValue.toFixed(2));
            $('.ggmc-mini-cart-widget').attr('data-cart-count', data.count || 0);

            // Update the mini cart dropdown content if cart items are provided
            if (data.items && Array.isArray(data.items) && data.items.length > 0) {
                refreshMiniCartDropdown(data.items, data.total || 0);
            } else if (data.count === 0) {
                // Handle empty cart case
                refreshMiniCartDropdown([], 0);
            }
        });

        // Function to refresh mini cart dropdown content
        function refreshMiniCartDropdown(cartItems, cartTotal) {
            var $dropdown = $('#mini-cart-dropdown');
            var $itemsContainer = $dropdown.find('.mini-cart-items');
            var $footer = $dropdown.find('.mini-cart-footer');

            // Make sure we have valid arrays
            if (!Array.isArray(cartItems)) {
                cartItems = [];
            }

            if (cartItems.length === 0) {
                // Show empty cart
                $itemsContainer.html('<p class="empty-cart">Your cart is empty</p>');
                $footer.hide();
            } else {
                // Check if images should be shown
                var showImage = $dropdown.closest('.ggmc-mini-cart-widget').data('show-image') === 'yes';

                // Build cart items HTML
                var itemsHtml = '';
                cartItems.forEach(function(item) {
                    var itemName = item.name || item.title || 'Unknown Product';
                    var itemQuantity = parseInt(item.quantity) || 0;
                    var itemLineTotal = parseFloat(item.line_total) || 0;
                    var cartKey = item.cart_key || item.key || '';
                    var featuredImage = item.featured_image || '';
                    var variationDisplay = item.variation_display || '';
                    var imageHtml = '';
                    var variationHtml = '';

                    if (showImage) {
                        imageHtml = '<div class="item-image">' + (featuredImage ?
                            '<img src="' + featuredImage + '" alt="' + itemName + '">' :
                            '<div class="placeholder-image">No Image</div>') + '</div>';
                    }

                    if (variationDisplay) {
                        variationHtml = '<div class="item-variation">' + variationDisplay + '</div>';
                    }

                    itemsHtml += '<div class="mini-cart-item" data-key="' + cartKey + '">' +
                        imageHtml +
                        '<div class="item-details">' +
                            '<h5>' + itemName + '</h5>' +
                            variationHtml +
                            '<div class="item-price-qty">' +
                                '<span class="quantity">Qty: ' + itemQuantity + '</span>' +
                                '<span class="price">$' + itemLineTotal.toFixed(2) + '</span>' +
                            '</div>' +
                        '</div>' +
                        '<button class="remove-item" onclick="removeFromCart(\'' + cartKey + '\')" title="Remove item">' +
                            '<i class="eicon-close" aria-hidden="true"></i>' +
                        '</button>' +
                    '</div>';
                });
                $itemsContainer.html(itemsHtml);

                // Always update the footer total
                var formattedTotal = parseFloat(cartTotal || 0).toFixed(2);

                // Re-query footer in case DOM changed
                $footer = $dropdown.find('.mini-cart-footer');

                if ($footer.length) {
                    $footer.find('.cart-total-display strong').text('Total: $' + formattedTotal);
                    $footer.show();
                } else {
                    // If footer missing, re-create it with links
                    var cartUrl = (typeof ggm_commerce_ajax !== 'undefined' && ggm_commerce_ajax.cart_url) ? ggm_commerce_ajax.cart_url : '/cart/';
                    var checkoutUrl = (typeof ggm_commerce_ajax !== 'undefined' && ggm_commerce_ajax.checkout_url) ? ggm_commerce_ajax.checkout_url : '/checkout/';
                    var footerHtml = '<div class="mini-cart-footer">' +
                        '<div class="cart-total-display"><strong>Total: $' + formattedTotal + '</strong></div>' +
                        '<div class="cart-actions">' +
                            '<a href="' + cartUrl + '" class="view-cart-btn">View Cart</a>' +
                            '<a href="' + checkoutUrl + '" class="checkout-btn">Checkout</a>' +
                        '</div></div>';
                    $itemsContainer.after(footerHtml);
                }
            }
            setTimeout(function() {
                $(document).trigger('mini_cart_refreshed', { items: cartItems, total: cartTotal });
            }, 50);
        }
    });
    </script>
    <?php
}
