<?php
/**
 * Template for displaying archived orders in My Account page
 *
 * @var array  $orders        Array of archived orders
 * @var int    $current_page  Current page number
 * @var int    $total_pages   Total number of pages
 * @var int    $total_orders  Total number of orders
 * @var string $menu_label    Custom menu label for archived orders
 * @var object $instance      Instance of MyAccountArchivedOrders class
 */

if ( ! defined( 'ABSPATH' ) ) {
    // phpcs:ignore Universal.PHP.RequireExitDieParentheses.Missing
	exit; // Exit if accessed directly.
}
?>
<h2><?php echo esc_html( $menu_label ); ?></h2>

<?php if ( ! empty( $orders ) ) : ?>
    <table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive my_account_orders account-orders-table">
        <thead>
            <tr>
                <th scope="col" class="woocommerce-orders-table__header woocommerce-orders-table__header-order-number">
                    <span class="nobr"><?php esc_html_e( 'Order', 'archive-master' ); ?></span>
                </th>
                <th scope="col" class="woocommerce-orders-table__header woocommerce-orders-table__header-order-date">
                    <span class="nobr"><?php esc_html_e( 'Date', 'archive-master' ); ?></span>
                </th>
                <th scope="col" class="woocommerce-orders-table__header woocommerce-orders-table__header-order-status">
                    <span class="nobr"><?php esc_html_e( 'Status', 'archive-master' ); ?></span>
                </th>
                <th scope="col" class="woocommerce-orders-table__header woocommerce-orders-table__header-archive-status">
                    <span class="nobr"><?php esc_html_e( 'State', 'archive-master' ); ?></span>
                </th>
                <th scope="col" class="woocommerce-orders-table__header woocommerce-orders-table__header-order-total">
                    <span class="nobr"><?php esc_html_e( 'Total', 'archive-master' ); ?></span>
                </th>
                <th scope="col" class="woocommerce-orders-table__header woocommerce-orders-table__header-order-actions">
                    <span class="nobr"><?php esc_html_e( 'Actions', 'archive-master' ); ?></span>
                </th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ( $orders as $archived_order ) { ?>
                <?php
                $order_status        = isset( $archived_order['order_status'] ) ? $archived_order['order_status'] : '';
                $order_status_class  = $order_status ? sanitize_html_class( $order_status ) : 'unknown';
                $order_id            = isset( $archived_order['archived_order_id'] ) ? $archived_order['archived_order_id'] : '';
                $order_record_id     = isset( $archived_order['id'] ) ? (int) $archived_order['id'] : 0;
                $order_date_string   = isset( $archived_order['order_date'] ) ? $archived_order['order_date'] : '';
                $order_date_time     = $order_date_string ? strtotime( $order_date_string ) : false;
                $order_date_datetime = $order_date_time ? gmdate( 'c', $order_date_time ) : gmdate( 'c' );
                $order_date_display  = $order_date_time ? date_i18n( get_option( 'date_format' ), $order_date_time ) : '';
                $products_count      = isset( $archived_order['products_count'] ) ? (int) $archived_order['products_count'] : 0;

                /* translators: %s: order number. */
                $view_order_number_label = sprintf( __( 'View order number %s', 'archive-master' ), $order_id );

                /* translators: %s: order number. */
                $view_order_label = sprintf( __( 'View order %s', 'archive-master' ), $order_id );
                ?>
                <tr class="woocommerce-orders-table__row woocommerce-orders-table__row--status-<?php echo esc_attr( $order_status_class ); ?> order">
                    <th class="woocommerce-orders-table__cell woocommerce-orders-table__cell-order-number" data-title="<?php esc_attr_e( 'Order', 'archive-master' ); ?>" scope="row">
                        <a href="#" onclick="openOrderModal(<?php echo esc_attr( $order_record_id ); ?>); return false;" aria-label="<?php echo esc_attr( $view_order_number_label ); ?>">
                            #<?php echo esc_html( $order_id ); ?>
                        </a>
                    </th>
                    <td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-order-date" data-title="<?php esc_attr_e( 'Date', 'archive-master' ); ?>">
                        <time datetime="<?php echo esc_attr( $order_date_datetime ); ?>">
                            <?php echo esc_html( $order_date_display ); ?>
                        </time>
                    </td>
                    <td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-order-status" data-title="<?php esc_attr_e( 'Status', 'archive-master' ); ?>">
                        <?php echo esc_html( ucfirst( str_replace( '-', ' ', $order_status_class ) ) ); ?>
                    </td>
                    <td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-archive-status" data-title="<?php esc_attr_e( 'State', 'archive-master' ); ?>">
                        <span style="color: #2e4453; font-weight: bold; text-transform: capitalize;">
                            <?php esc_html_e( 'Archived', 'archive-master' ); ?>
                        </span>
                    </td>
                    <td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-order-total" data-title="<?php esc_attr_e( 'Total', 'archive-master' ); ?>">
                        <?php echo wp_kses_post( $instance->format_price( isset( $archived_order['order_total'] ) ? $archived_order['order_total'] : '', isset( $archived_order['order_currency'] ) ? $archived_order['order_currency'] : '' ) ); ?>
                        <?php if ( 0 < $products_count ) : ?>
                            <?php
                            /* translators: %s: number of items. */
                            $items_label = _n( 'for %s item', 'for %s items', $products_count, 'archive-master' );
                            printf(
                                ' %s',
                                esc_html(
                                    sprintf(
                                        $items_label,
                                        number_format_i18n( $products_count )
                                    )
                                )
                            );
                            ?>
                        <?php endif; ?>
                    </td>
                    <td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-order-actions" data-title="<?php esc_attr_e( 'Actions', 'archive-master' ); ?>">
                        <a href="#" onclick="openOrderModal(<?php echo esc_attr( $order_record_id ); ?>); return false;" class="woocommerce-button button view" aria-label="<?php echo esc_attr( $view_order_label ); ?>">
                            <?php esc_html_e( 'View', 'archive-master' ); ?>
                        </a>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
    </table>

    <?php if ( $total_pages > 1 ) : ?>
    <div class="woocommerce-pagination">
        <?php
            // Get the base URL for pagination.
            $base_url = wc_get_account_endpoint_url( 'archived-orders' );

            // Ensure we have a proper URL.
		if ( empty( $base_url ) ) {
			$base_url = home_url( '/my-account/archived-orders/' );
		}

            // Remove trailing slash and ensure proper format.
            $base_url = untrailingslashit( $base_url );

            // Check if using pretty permalinks (not plain).
            $using_pretty_permalinks = ( '' !== get_option( 'permalink_structure' ) );

		if ( $using_pretty_permalinks ) {
			// For pretty permalinks, use /page/%#%/ format.
			$pagination_base = $base_url . '/page/%#%/';
			$pagination_format = '';
		} else {
			// For plain permalinks, use query string format.
			$pagination_base = add_query_arg( 'paged', '%#%', $base_url );
			$pagination_format = '';
		}

            // Build pagination arguments.
            $pagination_args = [
                'base'      => $pagination_base,
                'format'    => $pagination_format,
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' => '&lsaquo; ' . esc_html__( 'Previous', 'archive-master' ),
                'next_text' => esc_html__( 'Next', 'archive-master' ) . ' &rsaquo;',
                'type'      => 'list',
            ];
            echo wp_kses_post( paginate_links( $pagination_args ) );
            ?>
    </div>
    <?php endif; ?>

    <?php else : ?>
    <div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
        <?php esc_html_e( 'No archived orders found.', 'archive-master' ); ?>
    </div>
    <?php endif; ?>


    <!-- Order Details Modal -->
    <div id="order-details-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 10000;">
        <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; max-width: 800px; max-height: 80vh; overflow-y: auto; width: 90%;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid #ddd; padding-bottom: 15px;">
                <h3 id="modal-order-title" style="margin: 0;"></h3>
                <button onclick="closeOrderModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; padding: 0; color: #666;">&times;</button>
            </div>
            <div id="modal-order-content"></div>
        </div>
    </div>

<script>
const orderData = <?php echo wp_json_encode( $orders ); ?>;

function openOrderModal(orderId) {
    const orderIdInt = parseInt(orderId, 10);
    const order = orderData.find((item) => parseInt(item.id, 10) === orderIdInt);

    if (!order) {
        return;
    }

    const titleElement = document.getElementById('modal-order-title');
    const fallbackId = order.archived_order_id || order.order_id || order.id;

    if (titleElement) {
        titleElement.textContent = 'Order #' + fallbackId;
    }

    let content = '<div class="order-details">';

    // Order summary.
    content += '<div style="margin-bottom: 20px;">';
    content += '<h4>Order Summary</h4>';
    content += '<table style="width: 100%; border-collapse: collapse;">';
    content += '<tr><td style="padding: 5px; border: 1px solid #ddd; font-weight: bold;">Customer:</td><td style="padding: 5px; border: 1px solid #ddd;">' + (order.customer_name || 'N/A') + '</td></tr>';
    content += '<tr><td style="padding: 5px; border: 1px solid #ddd; font-weight: bold;">Email:</td><td style="padding: 5px; border: 1px solid #ddd;">' + (order.customer_email || 'N/A') + '</td></tr>';
    content += '<tr><td style="padding: 5px; border: 1px solid #ddd; font-weight: bold;">Status:</td><td style="padding: 5px; border: 1px solid #ddd;">' + (order.order_status || 'N/A') + '</td></tr>';
    content += '<tr><td style="padding: 5px; border: 1px solid #ddd; font-weight: bold;">Total:</td><td style="padding: 5px; border: 1px solid #ddd;">' + (order.order_total || 'N/A') + '</td></tr>';
    content += '<tr><td style="padding: 5px; border: 1px solid #ddd; font-weight: bold;">Payment Method:</td><td style="padding: 5px; border: 1px solid #ddd;">' + (order.payment_method || 'N/A') + '</td></tr>';
    content += '</table>';
    content += '</div>';

    // Products.
    if (Array.isArray(order.products) && order.products.length > 0) {
        content += '<div style="margin-bottom: 20px;">';
        content += '<h4>Products</h4>';
        content += '<table style="width: 100%; border-collapse: collapse;">';
        content += '<thead><tr><th style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; text-align: left;">Product</th><th style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; text-align: left;">Quantity</th><th style="padding: 8px; border: 1px solid #ddd; background: #f9f9f9; text-align: left;">Total</th></tr></thead>';
        content += '<tbody>';
        order.products.forEach((product) => {
            // Get product name, SKU, and URL.
            var productName = product.name || product.product_name || 'N/A';
            var productSku = product.sku || '';
            var productUrl = product.url || '';
            
            // Format product display: name as link, SKU on separate line.
            var productDisplay = '<div>';
            
            // Product name as link (blue, underlined).
            if (productUrl && productUrl !== '') {
                productDisplay += '<a href="' + productUrl + '" style="color: #0073aa; text-decoration: underline;" target="_blank">' + productName + '</a>';
            } else {
                productDisplay += '<span>' + productName + '</span>';
            }
            
            // SKU on separate line (gray).
            if (productSku && productSku !== '') {
                productDisplay += '<br><span style="color: #666; font-size: 0.9em;">SKU: ' + productSku + '</span>';
            }
            
            productDisplay += '</div>';
            
            content += '<tr>';
            content += '<td style="padding: 8px; border: 1px solid #ddd;">' + productDisplay + '</td>';
            content += '<td style="padding: 8px; border: 1px solid #ddd;">' + (product.quantity || product.qty || 1) + '</td>';
            content += '<td style="padding: 8px; border: 1px solid #ddd;">' + (product.total || product.line_total || 'N/A') + '</td>';
            content += '</tr>';
        });
        content += '</tbody></table>';
        content += '</div>';
    }

    // Billing address.
    if (order.billing_address) {
        content += '<div>';
        content += '<h4>Billing Address</h4>';
        content += '<div style="padding: 10px; border: 1px solid #ddd; background: #f9f9f9;">';
        if (order.billing_address.first_name || order.billing_address.last_name) {
            content += '<div>' + (order.billing_address.first_name || '') + ' ' + (order.billing_address.last_name || '') + '</div>';
        }
        if (order.billing_address.address_1) {
            content += '<div>' + order.billing_address.address_1 + '</div>';
        }
        if (order.billing_address.address_2) {
            content += '<div>' + order.billing_address.address_2 + '</div>';
        }
        if (order.billing_address.city || order.billing_address.state || order.billing_address.postcode) {
            content += '<div>' + (order.billing_address.city || '') + ' ' + (order.billing_address.state || '') + ' ' + (order.billing_address.postcode || '') + '</div>';
        }
        if (order.billing_address.phone) {
            content += '<div>Phone: ' + order.billing_address.phone + '</div>';
        }
        content += '</div>';
        content += '</div>';
    }

    content += '</div>';

    const modalContent = document.getElementById('modal-order-content');
    const modalWrapper = document.getElementById('order-details-modal');

    if (modalContent) {
        modalContent.innerHTML = content;
    }

    if (modalWrapper) {
        modalWrapper.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
}

function closeOrderModal() {
    const modalWrapper = document.getElementById('order-details-modal');

    if (modalWrapper) {
        modalWrapper.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
}

// Close modal when clicking outside.
const modalWrapper = document.getElementById('order-details-modal');
if (modalWrapper) {
    modalWrapper.addEventListener('click', function(event) {
        if (event.target === this) {
            closeOrderModal();
        }
    });
}
</script>

