<?php
/**
 * Template: wishlist/wishlist.php
 *
 * Renders the customer's wishlist page or a shared (public) wishlist.
 *
 * Available variables:
 *   $items        — Array of wishlist item rows (with product_name, price, thumbnail_url)
 *   $total        — Total item count
 *   $total_pages  — Pagination page count
 *   $current_page — Current page (int)
 *   $customer     — tc_customers row (array), null for shared view
 *   $owner        — {first_name, last_name} row, present on shared view
 *   $share_url    — Shareable URL string (own wishlist only)
 *   $readonly     — bool, true when viewing someone else's shared list
 *
 * Override: copy to your-theme/titancart/wishlist/wishlist.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$readonly    = $readonly    ?? false;
$items       = $items       ?? [];
$total       = $total       ?? 0;
$total_pages = $total_pages ?? 1;
$current_page= $current_page?? 1;
$share_url   = $share_url   ?? '';
$rest_url    = esc_url_raw( rest_url( 'titancart/v1/wishlist' ) );
$cart_url    = esc_url_raw( rest_url( 'titancart/v1/cart/items' ) );

// Title.
if ( $readonly && ! empty( $owner ) ) {
    $owner_name = trim( ( $owner['first_name'] ?? '' ) . ' ' . ( $owner['last_name'] ?? '' ) );
    /* translators: %s: owner's name */
    $page_title = sprintf( __( "%s's Wishlist", 'titancart-lite' ), esc_html( $owner_name ) );
} else {
    $page_title = __( 'My Wishlist', 'titancart-lite' );
}
?>

<div class="tc-wishlist" id="tc-wishlist-app">

    <div class="tc-page-header">
        <?php if ( ! $readonly ) : ?>
            <a href="<?php echo esc_url( home_url( '/my-account/' ) ); ?>" class="tc-back-link">
                ← <?php esc_html_e( 'My Account', 'titancart-lite' ); ?>
            </a>
        <?php endif; ?>
        <h2><?php echo esc_html( $page_title ); ?></h2>

        <?php if ( ! $readonly && $share_url ) : ?>
            <div class="tc-wishlist-share">
                <label><?php esc_html_e( 'Share your wishlist:', 'titancart-lite' ); ?></label>
                <input type="text"
                       class="tc-input tc-input--sm"
                       value="<?php echo esc_attr( $share_url ); ?>"
                       readonly
                       id="tc-share-link" />
                <button class="tc-btn tc-btn--sm js-copy-share"
                        data-target="tc-share-link">
                    <?php esc_html_e( 'Copy', 'titancart-lite' ); ?>
                </button>
            </div>
        <?php endif; ?>
    </div>

    <div class="tc-notice tc-notice--success" id="tc-wl-success" style="display:none;"></div>
    <div class="tc-notice tc-notice--error"   id="tc-wl-error"   style="display:none;"></div>

    <?php if ( empty( $items ) ) : ?>
        <div class="tc-empty-state">
            <p><?php esc_html_e( 'Your wishlist is empty.', 'titancart-lite' ); ?></p>
            <a href="<?php echo esc_url( titancart_shop_url() ); ?>" class="tc-btn tc-btn--primary">
                <?php esc_html_e( 'Start Shopping', 'titancart-lite' ); ?>
            </a>
        </div>

    <?php else : ?>

        <div class="tc-wishlist-grid">
            <?php foreach ( $items as $item ) :
                $product_id  = (int) $item['product_id'];
                $price_str   = number_format( (float) $item['price'], 2 );
                $thumb       = esc_url( $item['thumbnail_url'] ?? '' );
                $product_url = esc_url( $item['product_url']   ?? '' );
                $name        = esc_html( $item['product_name'] ?? '' );
            ?>
                <div class="tc-wishlist-card" data-product-id="<?php echo esc_attr( $product_id ); ?>">

                    <?php if ( $thumb ) : ?>
                        <a href="<?php echo esc_url( $product_url ); ?>" class="tc-wishlist-card__img-wrap">
                            <img src="<?php echo esc_url( $thumb ); ?>"
                                 alt="<?php echo esc_attr( $name ); ?>"
                                 class="tc-wishlist-card__img"
                                 loading="lazy" />
                        </a>
                    <?php endif; ?>

                    <div class="tc-wishlist-card__body">
                        <a href="<?php echo esc_url( $product_url ); ?>" class="tc-wishlist-card__name">
                            <?php echo esc_html( $name ); ?>
                        </a>
                        <div class="tc-wishlist-card__price">
                            <?php echo esc_html( $price_str ); ?>
                        </div>
                        <?php if ( ( $item['stock_status'] ?? 'out_of_stock' ) === 'out_of_stock' ) : ?>
                            <span class="tc-wishlist-card__stock tc-wishlist-card__stock--out"
                                  style="display:inline-block;margin-top:4px;padding:2px 8px;border-radius:4px;font-size:.8rem;font-weight:600;background:#fee2e2;color:#dc2626;">
                                <?php esc_html_e( 'Out of Stock', 'titancart-lite' ); ?>
                            </span>
                        <?php else : ?>
                            <span class="tc-wishlist-card__stock tc-wishlist-card__stock--in"
                                  style="display:inline-block;margin-top:4px;padding:2px 8px;border-radius:4px;font-size:.8rem;font-weight:600;background:#dcfce7;color:#16a34a;">
                                <?php esc_html_e( 'In Stock', 'titancart-lite' ); ?>
                            </span>
                        <?php endif; ?>
                    </div>

                    <div class="tc-wishlist-card__actions">
                        <?php if ( ! $readonly ) : ?>
                            <?php
                            $is_available = ( $item['status'] ?? '' ) === 'active'
                                         && ( $item['stock_status'] ?? 'out_of_stock' ) !== 'out_of_stock';
                            ?>
                            <?php if ( $is_available ) : ?>
                                <button class="tc-btn tc-btn--primary tc-btn--sm js-wl-move-to-cart"
                                        data-product-id="<?php echo esc_attr( $product_id ); ?>">
                                    <?php esc_html_e( 'Add to Cart', 'titancart-lite' ); ?>
                                </button>
                            <?php else : ?>
                                <span class="tc-btn tc-btn--muted tc-btn--sm" style="cursor:default;opacity:.6;">
                                    <?php esc_html_e( 'Currently Unavailable', 'titancart-lite' ); ?>
                                </span>
                            <?php endif; ?>
                            <button class="tc-btn tc-btn--danger tc-btn--sm js-wl-remove"
                                    data-product-id="<?php echo esc_attr( $product_id ); ?>">
                                <?php esc_html_e( 'Remove', 'titancart-lite' ); ?>
                            </button>
                        <?php else : ?>
                            <a href="<?php echo esc_url( $product_url ); ?>" class="tc-btn tc-btn--primary tc-btn--sm">
                                <?php esc_html_e( 'View Product', 'titancart-lite' ); ?>
                            </a>
                        <?php endif; ?>
                    </div>

                    <div class="tc-wishlist-card__date">
                        <?php
                        printf(
                            /* translators: %s: date added */
                            esc_html__( 'Added %s', 'titancart-lite' ),
                            esc_html( titancart_format_date( $item['added_at'] ) )
                        );
                        ?>
                    </div>

                </div><!-- .tc-wishlist-card -->
            <?php endforeach; ?>
        </div><!-- .tc-wishlist-grid -->

        <?php if ( $total_pages > 1 ) : ?>
            <nav class="tc-pagination">
                <?php
                $paged_base = get_permalink() ?: home_url( '/wishlist/' );
                for ( $p = 1; $p <= $total_pages; $p++ ) :
                    $page_url = add_query_arg( 'paged', $p, $paged_base );
                    $active   = $p === $current_page ? ' tc-pagination__btn--active' : '';
                ?>
                    <a href="<?php echo esc_url( $page_url ); ?>"
                       class="tc-pagination__btn<?php echo esc_attr( $active ); ?>">
                        <?php echo esc_html( $p ); ?>
                    </a>
                <?php endfor; ?>
            </nav>
        <?php endif; ?>

    <?php endif; ?>

</div><!-- .tc-wishlist -->

<?php if ( ! $readonly ) :
// WP.org R2: inline JS is built as a PHP string (no output buffering, no markup
// literals) and attached via wp_add_inline_script on a footer stub handle.
// All PHP values enter via one wp_json_encode'd config object (pattern #637).
$tc_wl_cfg = wp_json_encode( array(
    'rest'     => esc_url_raw( $rest_url ),
    'countUrl' => esc_url_raw( rest_url( 'titancart/v1/cart/count' ) ),
    'nonce'    => wp_create_nonce( 'wp_rest' ),
    'i18n'     => array(
        'removed'   => __( 'Item removed from wishlist.', 'titancart-lite' ),
        'adding'    => __( 'Adding…', 'titancart-lite' ),
        'added'     => __( 'Added ✓', 'titancart-lite' ),
        'addToCart' => __( 'Add to Cart', 'titancart-lite' ),
        'addedCart' => __( 'Added to cart!', 'titancart-lite' ),
        'copied'    => __( 'Link copied to clipboard!', 'titancart-lite' ),
        'copiedAlt' => __( 'Link copied!', 'titancart-lite' ),
    ),
) );
$tc_wl_inline_js = <<<'JS'
(function(){
    var CFG     = %%CFG%%;
    var restUrl = CFG.rest;
    var nonce   = CFG.nonce;

    function apiFetch(url, method, data) {
        var opts = {
            method: method || 'GET',
            headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' },
        };
        if (data) opts.body = JSON.stringify(data);
        return fetch(url, opts).then(function(r){
            return r.json().then(function(d){ return {ok: r.ok, data: d, status: r.status}; });
        });
    }

    function showMsg(type, msg) {
        var el = document.getElementById('tc-wl-' + type);
        el.textContent = msg;
        el.style.display = 'block';
        setTimeout(function(){ el.style.display = 'none'; }, 4000);
    }

    function removeCard(productId) {
        var card = document.querySelector('.tc-wishlist-card[data-product-id="' + productId + '"]');
        if (card) card.remove();
    }

    document.addEventListener('click', function(e) {

        // Remove from wishlist.
        if (e.target.classList.contains('js-wl-remove')) {
            var pid = e.target.dataset.productId;
            apiFetch(restUrl + '/items/' + pid, 'DELETE').then(function(r){
                if (r.ok) {
                    removeCard(pid);
                    showMsg('success', CFG.i18n.removed);
                } else {
                    showMsg('error', (r.data && r.data.message) || 'Error');
                }
            });
        }

        // Add to cart (keep item in wishlist).
        if (e.target.classList.contains('js-wl-move-to-cart')) {
            var pid = e.target.dataset.productId;
            var btn = e.target;
            btn.disabled = true;
            btn.textContent = CFG.i18n.adding;
            apiFetch(restUrl + '/items/' + pid + '/move-to-cart', 'POST').then(function(r){
                if (r.ok) {
                    btn.textContent = CFG.i18n.added;
                    setTimeout(function(){
                        btn.textContent = CFG.i18n.addToCart;
                        btn.disabled = false;
                    }, 2000);
                    showMsg('success', CFG.i18n.addedCart);
                    // Update mini-cart count if present.
                    var countBadge = document.querySelector('.tc-cart-count');
                    if (countBadge) {
                        fetch(CFG.countUrl, {
                            headers: { 'X-WP-Nonce': nonce }
                        }).then(function(r){ return r.json(); }).then(function(d){
                            if (countBadge && d.count !== undefined) countBadge.textContent = d.count;
                        });
                    }
                } else {
                    btn.textContent = CFG.i18n.addToCart;
                    btn.disabled = false;
                    showMsg('error', (r.data && r.data.message) || 'Error');
                }
            });
        }

        // Copy share link.
        if (e.target.classList.contains('js-copy-share')) {
            var targetId = e.target.dataset.target;
            var el = document.getElementById(targetId);
            if (el && navigator.clipboard) {
                navigator.clipboard.writeText(el.value).then(function(){
                    showMsg('success', CFG.i18n.copied);
                });
            } else if (el) {
                el.select();
                document.execCommand('copy');
                showMsg('success', CFG.i18n.copiedAlt);
            }
        }
    });
}());
JS;
$tc_wl_inline_js = strtr( $tc_wl_inline_js, [ '%%CFG%%' => $tc_wl_cfg ] );
wp_register_script( 'titancart-wishlist-inline', false, array(), TITANCART_VERSION, true );
wp_enqueue_script( 'titancart-wishlist-inline' );
wp_add_inline_script( 'titancart-wishlist-inline', $tc_wl_inline_js );
endif;
?>
