<?php
/**
 * Cart Display Widget — Render Functions
 * Standalone prefixed functions; no class required.
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Main render entry point.
 *
 * @param \GGM_Commerce_Widget_Cart_Display $widget
 */
function ggmc_cart_display_render( $widget ) {
    $settings     = $widget->get_settings_for_display();
    $data_handler = new GGM_Commerce_Cart_Display_Data_Handler();
    $cart_items   = $data_handler->get_cart_items();

    echo '<div class="ggmc-cart-container">';

    if ( $data_handler->is_cart_empty() ) {
        ggmc_cart_display_render_empty_cart( $settings, $data_handler );
    } else {
        ggmc_cart_display_render_cart_table( $cart_items, $settings, $data_handler );
        ggmc_cart_display_render_cart_actions( $settings, $data_handler );
    }

    echo '</div>';

    ggmc_cart_display_render_scripts();
}

/**
 * Render empty cart message.
 */
function ggmc_cart_display_render_empty_cart( $settings, $data_handler ) {
    if ( $settings['show_empty_message'] !== 'yes' ) {
        return;
    }

    echo '<div class="ggmc-empty-cart">';
    echo '<p>' . esc_html( $settings['empty_message'] ) . '</p>';

    if ( $settings['show_continue_shopping'] === 'yes' ) {
        $continue_url = ! empty( $settings['continue_shopping_url']['url'] )
            ? $settings['continue_shopping_url']['url']
            : $data_handler->get_default_continue_shopping_url();

        echo '<a href="' . esc_url( $continue_url ) . '" class="ggmc-continue-shopping-btn">';
        echo esc_html( $settings['continue_shopping_text'] );
        echo '</a>';
    }

    echo '</div>';
}

/**
 * Render cart table.
 */
function ggmc_cart_display_render_cart_table( $cart_items, $settings, $data_handler ) {
    echo '<table class="ggmc-cart-table">';
    ggmc_cart_display_render_table_header();
    ggmc_cart_display_render_table_body( $cart_items, $settings, $data_handler );
    ggmc_cart_display_render_table_footer( $data_handler );
    echo '</table>';
}

/**
 * Render table header.
 */
function ggmc_cart_display_render_table_header() {
    echo '<thead>
            <tr>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total</th>
                <th>Actions</th>
            </tr>
          </thead>';
}

/**
 * Render table body.
 */
function ggmc_cart_display_render_table_body( $cart_items, $settings, $data_handler ) {
    echo '<tbody>';

    foreach ( $cart_items as $item ) {
        ggmc_cart_display_render_cart_item( $item, $settings, $data_handler );
    }

    echo '</tbody>';
}

/**
 * Render individual cart item row.
 */
function ggmc_cart_display_render_cart_item( $item, $settings, $data_handler ) {
    echo '<tr class="cart-item" data-cart-item-id="' . esc_attr( $item->cart_key ) . '">';

    // Product column
    echo '<td class="product-info">';
    ggmc_cart_display_render_product_details( $item, $settings, $data_handler );
    echo '</td>';

    // Price column
    echo '<td class="product-price" data-price="' . esc_attr( $item->price ) . '">';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- format_price() returns pre-escaped HTML
    echo $data_handler->format_price( $item->price );
    echo '</td>';

    // Quantity column
    echo '<td class="product-quantity">';
    ggmc_cart_display_render_quantity_controls( $item, $settings );
    echo '</td>';

    // Total column
    echo '<td class="product-total">';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- format_price() returns pre-escaped HTML
    echo $data_handler->format_price( $item->line_total );
    echo '</td>';

    // Actions column
    echo '<td class="product-actions">';
    ggmc_cart_display_render_remove_button( $item );
    echo '</td>';

    echo '</tr>';
}

/**
 * Render product details (image + name + variations).
 */
function ggmc_cart_display_render_product_details( $item, $settings, $data_handler ) {
    echo '<div class="product-details">';

    $show_images = ( $settings['show_product_images'] ?? 'yes' ) === 'yes';

    if ( $show_images ) {
        if ( ! empty( $item->image_id ) ) {
            echo '<div class="product-image">';
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_product_image() returns pre-escaped HTML
            echo $data_handler->get_product_image( $item->image_id );
            echo '</div>';
        } else {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_placeholder_image() returns pre-escaped HTML
            echo $data_handler->get_placeholder_image();
        }
    }

    $link_product = ( $settings['link_product_name'] ?? 'yes' ) === 'yes';
    $product_url  = '';

    if ( $link_product && ! empty( $item->id ) ) {
        $product_url = GGM_Commerce_Helpers::get_product_details_url( $item->id );
    }

    echo '<div class="product-name">';
    if ( $link_product && $product_url ) {
        echo '<a href="' . esc_url( $product_url ) . '" class="product-name-link">';
        echo '<strong>' . esc_html( $item->name ?? 'Unknown Product' ) . '</strong>';
        echo '</a>';
    } else {
        echo '<strong>' . esc_html( $item->name ?? 'Unknown Product' ) . '</strong>';
    }

    if ( ! empty( $item->variation_display ) ) {
        echo '<div class="product-variation">' . esc_html( $item->variation_display ) . '</div>';
    }

    echo '</div>';

    echo '</div>';
}

/**
 * Render quantity controls.
 */
function ggmc_cart_display_render_quantity_controls( $item, $settings ) {
    $quantity_controls_style = $settings['quantity_controls_style'] ?? 'both';

    echo '<div class="quantity-controls ' . esc_attr( $quantity_controls_style ) . '">';

    if ( $quantity_controls_style === 'both' ) {
        echo '<button type="button" class="qty-minus" data-cart-item-id="' . esc_attr( $item->cart_key ) . '">-</button>';
    }

    echo '<input type="number"
                 class="ggmc-cart-quantity"
                 value="' . esc_attr( $item->quantity ) . '"
                 min="0"
                 max="999"
                 data-cart-item-id="' . esc_attr( $item->cart_key ) . '" />';

    if ( $quantity_controls_style === 'both' ) {
        echo '<button type="button" class="qty-plus" data-cart-item-id="' . esc_attr( $item->cart_key ) . '">+</button>';
    }

    echo '</div>';
}

/**
 * Render remove button.
 */
function ggmc_cart_display_render_remove_button( $item ) {
    echo '<button type="button"
                  class="ggmc-remove-from-cart"
                  data-cart-item-id="' . esc_attr( $item->cart_key ) . '"
                  title="Remove from cart">
            &times;
          </button>';
}

/**
 * Render table footer (totals).
 * Shows proper tax breakdown based on admin VAT registration.
 */
function ggmc_cart_display_render_table_footer( $data_handler ) {
    $tax            = ggm_commerce_tax();
    $cart_total     = $data_handler->get_cart_total();
    $admin_has_vat  = $tax->admin_has_vat_number();
    $tax_enabled    = $tax->is_enabled();

    echo '<tfoot>';

    if ( $admin_has_vat && $tax_enabled ) {
        $cart_totals        = $data_handler->get_cart_totals_with_tax();
        $tax_label          = $tax->get_label();
        $is_customer_exempt = false;

        if ( is_user_logged_in() ) {
            $user_id            = get_current_user_id();
            $is_customer_exempt = $tax->is_customer_tax_exempt( $user_id );
        }

        // Subtotal row (ex VAT)
        echo '<tr class="cart-subtotal-row">';
        echo '<td colspan="3">' . esc_html__( 'Subtotal', 'ggm-commerce' ) . ':</td>';
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- format_price() returns pre-escaped HTML
        echo '<td class="cart-subtotal-value">' . $data_handler->format_price( $cart_totals['net'] ) . '</td>';
        echo '<td></td>';
        echo '</tr>';

        // VAT row
        echo '<tr class="cart-tax-row">';
        echo '<td colspan="3">' . esc_html( $tax_label ) . ':</td>';
        if ( $is_customer_exempt ) {
            echo '<td class="cart-tax-value">' . esc_html( $data_handler->format_price( 0 ) ) . ' <span class="tax-exempt-notice">(' . esc_html__( 'Exempt', 'ggm-commerce' ) . ')</span></td>';
        } else {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- format_price() returns pre-escaped HTML
            echo '<td class="cart-tax-value">' . $data_handler->format_price( $cart_totals['tax'] ) . '</td>';
        }
        echo '<td></td>';
        echo '</tr>';

        // Total row (inc VAT or ex VAT for exempt)
        echo '<tr class="cart-total-row">';
        echo '<td colspan="3"><strong>' . esc_html__( 'Total', 'ggm-commerce' ) . ':</strong></td>';
        $display_total = $is_customer_exempt ? $cart_totals['net'] : $cart_totals['gross'];
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- format_price() returns pre-escaped HTML
        echo '<td class="cart-total-value" data-cart-total><strong>' . $data_handler->format_price( $display_total ) . '</strong></td>';
        echo '<td></td>';
        echo '</tr>';
    } else {
        // No VAT registration or tax disabled — simple total, no tax breakdown
        echo '<tr class="cart-total-row">';
        echo '<td colspan="3"><strong>' . esc_html__( 'Total', 'ggm-commerce' ) . ':</strong></td>';
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- format_price() returns pre-escaped HTML
        echo '<td class="cart-total-value" data-cart-total><strong>' . $data_handler->format_price( $cart_total ) . '</strong></td>';
        echo '<td></td>';
        echo '</tr>';
    }

    echo '</tfoot>';
}

/**
 * Render cart actions (buttons below the table).
 */
function ggmc_cart_display_render_cart_actions( $settings, $data_handler ) {
    echo '<div class="ggmc-cart-actions">';

    if ( $settings['show_continue_shopping'] === 'yes' ) {
        $continue_url = ! empty( $settings['continue_shopping_url']['url'] )
            ? $settings['continue_shopping_url']['url']
            : $data_handler->get_default_continue_shopping_url();

        echo '<a href="' . esc_url( $continue_url ) . '" class="ggmc-continue-shopping-btn">';
        echo esc_html( $settings['continue_shopping_text'] );
        echo '</a>';
    }

    $checkout_url = ! empty( $settings['checkout_url']['url'] )
        ? $settings['checkout_url']['url']
        : home_url( '/checkout' );

    echo '<a href="' . esc_url( $checkout_url ) . '" class="ggmc-proceed-checkout-btn">Proceed to Checkout</a>';

    echo '</div>';
}

/**
 * Render JavaScript.
 * Note: render_styles() was a no-op in the original renderer; omitted here.
 */
function ggmc_cart_display_render_scripts() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            // Quantity controls for cart display
            $(document).on('click', '.qty-plus', function() {
                var $input = $(this).siblings('.ggmc-cart-quantity');
                var currentVal = parseInt($input.val()) || 1;
                $input.val(currentVal + 1).trigger('change');
            });

            $(document).on('click', '.qty-minus', function() {
                var $input = $(this).siblings('.ggmc-cart-quantity');
                var currentVal = parseInt($input.val()) || 1;
                if (currentVal > 1) {
                    $input.val(currentVal - 1).trigger('change');
                }
            });

            // Listen for cart updates from other widgets (like mini cart)
            $(document).on('ggm_commerce_cart_updated', function(event, data) {
                // Only refresh if the action came from mini cart or other external sources
                if (data.action === 'remove_from_cart' || data.action === 'add_to_cart') {
                    // For major changes like item removal, reload the page to maintain proper layout
                    if (data.action === 'remove_from_cart') {
                        location.reload();
                    }
                    // For additions, the main cart.js will handle total updates automatically
                    // No need for separate total update function since cart.js handles it properly
                }
            });
        });
    </script>
    <?php
}
