<?php

defined('ABSPATH') || exit('No direct script access allowed');

printf('<div class="eaw-saved-carts"><h2>%s</h2>', esc_html($title));

foreach ($cartsData as $savedCart) {
    $name  = $savedCart['name'] ?? __('New Saved Cart', 'essential-addons-for-woocommerce');
    $items = $savedCart['data'] ?? [];

    echo '<div class="eaw-saved-cart"><h3>' . esc_html($name) . '</h3>';

    if (empty($items)) {
        echo '<p>' . esc_html__('No items in this cart.', 'essential-addons-for-woocommerce') . '</p>';
    } else {
        foreach ($items as $item) {
            if (empty($item)) {
                continue;
            }

            $product = wc_get_product($item['product_id']);

            if (!$product) {
                echo '<div class="eaw-saved-cart-item">' . esc_html__('Product not found.', 'essential-addons-for-woocommerce') . '</div>';
                continue;
            }

            echo '<div class="eaw-saved-cart-item">';
            echo '<div class="eaw-saved-cart-item-name">' . esc_html($product->get_name()) . '</div>';
            echo '<div class="eaw-saved-cart-item-quantity">' . esc_html($item['quantity']) . '</div>';
            echo '<div class="eaw-saved-cart-item-price">' . wp_kses_post(wc_price($product->get_price())) . '</div>';
            echo '</div>';
        }
    }

    echo '<div class="eaw-saved-cart-actions"><div class="eaw-saved-cart-actions-inner">';

    printf(
        '<button class="eaw-delete-button" title="%s" data-savecartid="%s"><span class="eaw-icon-delete"></span></button>',
        esc_attr__('Delete', 'essential-addons-for-woocommerce'),
        esc_attr($savedCart['id'])
    );

    printf(
        '<button class="eaw-share-button eaw-copy-button" title="%s" data-savecartid="%s"><span class="eaw-icon-share"></span></button>',
        esc_attr__('Share this cart', 'essential-addons-for-woocommerce'),
        esc_attr($savedCart['id'])
    );

    printf(
        '<button class="eaw-restore-button" title="%s" data-savecartid="%s"><span class="eaw-icon-reset"></span></button>',
        esc_attr__('Restore this cart', 'essential-addons-for-woocommerce'),
        esc_attr($savedCart['id'])
    );

    printf(
        '<button class="eaw-copy-button" id="eaw-copy-button" title="%s" data-savecartid="%s"><span class="eaw-icon-link-copy"></span></button>',
        esc_attr__('Copy', 'essential-addons-for-woocommerce'),
        esc_attr($savedCart['id'])
    );

    echo '</div></div></div>';
}

echo '</div>'; // Close .eaw-saved-carts
