<?php
/**
 * TitanCart product card — unified Bootstrap style.
 *
 * Used on shop grid, search results, and anywhere products are listed.
 * In grid view: standard vertical card (image, title, price).
 * In list view: 3-column horizontal (image | info | control).
 * Override: {theme}/titancart/product/card.php
 *
 * @var array $product  Product row array.
 * @package TitanCart
 */

defined( 'ABSPATH' ) || exit;

// ── Extract product variables first (needed by extension logic below) ──
$image       = $product['image']       ?? null;
$name        = $product['name']        ?? '';
$slug        = $product['slug']        ?? '';
$product_id  = (int) ( $product['id']  ?? 0 );

// ── Needs a PDP selection? (KI-21 / S283) ──
// Some products can't be added straight from a card: variation-group members
// (Color/Size fixed by membership), shared-variation ("variable") products
// (Color/Size chosen on their own PDP), and products with a required option.
// All of these show a "Choose Options" link to the PDP instead of a direct
// "Add to Cart" (which would silently add an unconfigured / wrong item).
$is_variation = $product_id > 0
    && function_exists( 'titancart_product_requires_options' )
    && titancart_product_requires_options( $product_id );

// ── Effective shelf price (roadmap #4 / KI-08) ──
// Lowest of {manual list-price sale, Bulk-Buys tier, active catalog promo} for
// the current viewer at qty 1. With no tier/promo this equals the raw
// price/list_price, so behaviour is unchanged until a catalog promo exists. The
// base row is passed through to skip a redundant SELECT on listing pages.
// class_exists: Lite strips the Promotions module (R1 §🅰) — base price shape.
if ( class_exists( \TitanCart\Modules\Promotions\CatalogPromotionService::class ) ) {
    $tc_ep = \TitanCart\Modules\Promotions\CatalogPromotionService::instance()
                  ->effective_price_for_viewer( $product_id, 1, [
                      'price'      => (float) ( $product['price'] ?? 0 ),
                      'list_price' => (float) ( $product['list_price'] ?? 0 ),
                  ] );
} else {
    $tc_ep = [
        'price'      => (float) ( $product['price'] ?? 0 ),
        'on_sale'    => false,
        'compare_at' => (float) ( $product['list_price'] ?? 0 ),
    ];
}
$price       = (float) $tc_ep['price'];
$on_sale     = (bool) $tc_ep['on_sale'];
$list_price  = $on_sale ? (float) $tc_ep['compare_at'] : (float) ( $product['list_price'] ?? 0 );

$in_stock    = ( $product['stock_status'] ?? 'out_of_stock' ) === 'in_stock';
$stock_qty   = (int) ( $product['stock_quantity'] ?? 0 );
$currency    = apply_filters( 'titancart_currency_symbol', '$' );
$product_url = $product['url'] ?? titancart_product_url( $slug );
$short_desc  = $product['short_desc']  ?? '';
$sku         = $product['sku']         ?? '';
$rating_avg  = (float) ( $product['rating_avg'] ?? 0 );
$rating_count= (int) ( $product['rating_count'] ?? 0 );
$features    = $product['features']    ?? [];
$brand       = (string) ( $product['brand'] ?? '' );

// ── Settings reads ──
$qv_enabled  = \TitanCart\Services\SettingsService::bool( 'appearance', 'enable_quick_view', true );
$show_stock  = \TitanCart\Services\SettingsService::bool( 'appearance', 'show_number_available', false );
$show_tax_on_catalog = \TitanCart\Services\SettingsService::bool( 'appearance', 'show_tax_on_catalog', false );
$compare_enabled = \TitanCart\Services\SettingsService::bool( 'general', 'catalog_allow_compare', true );
$wishlist_enabled = \TitanCart\REST\Extensions\ExtensionsController::is_active( 'wishlist' );
$catalog_mode_on  = \TitanCart\REST\Extensions\ExtensionsController::is_active( 'catalog-mode' );
$ppu_on           = \TitanCart\REST\Extensions\ExtensionsController::is_active( 'price-per-unit' );
$guest_policy = is_user_logged_in() ? 'allow' : \TitanCart\Services\SettingsService::get( 'checkout', 'allow_shopping_unlogged', 'allow' );
$hide_price  = ( $guest_policy === 'hide_price' );
$deny_cart   = ( $guest_policy === 'hide_price' || $guest_policy === 'deny' );

// Catalog Mode overrides — when active, hide prices and/or cart buttons site-wide.
if ( $catalog_mode_on ) {
    $cm_type       = \TitanCart\Services\SettingsService::get( 'catalog_mode', 'catalog_mode_type', 'catalog' );
    $cm_hide_price = \TitanCart\Services\SettingsService::bool( 'catalog_mode', 'hide_prices', true );
    $cm_inquiry_url  = \TitanCart\Services\SettingsService::get( 'catalog_mode', 'inquiry_url', '/contact/' );
    $cm_inquiry_text = \TitanCart\Services\SettingsService::get( 'catalog_mode', 'inquiry_button_text', 'Request a Quote' );
    if ( $cm_hide_price ) { $hide_price = true; }
    $deny_cart = true; // Always hide Add to Cart in catalog mode.
}

// Price Per Unit — compute per-unit display string for catalog cards.
// Only shows when per-unit price meaningfully differs from the product price.
$ppu_html = '';
if ( $ppu_on && ! $hide_price && $price > 0 ) {
    $ppu_show_catalog = \TitanCart\Services\SettingsService::bool( 'price_per_unit', 'show_on_catalog', true );
    if ( $ppu_show_catalog ) {
        $ppu_units = (float) \TitanCart\Services\SettingsService::get( 'price_per_unit', 'default_units_in_product', 1 );
        $ppu_per_x = (float) \TitanCart\Services\SettingsService::get( 'price_per_unit', 'default_show_per_x', 1 );
        $ppu_unit  = \TitanCart\Services\SettingsService::get( 'price_per_unit', 'default_unit_name', 'kg' );
        if ( $ppu_units > 0 ) {
            $per_unit_price = ( $price / $ppu_units ) * $ppu_per_x;
            // Skip if per-unit price equals the product price (meaningless display).
            if ( abs( $per_unit_price - $price ) > 0.01 ) {
                $ppu_label = $ppu_per_x > 1 ? $ppu_per_x . ' ' . $ppu_unit : $ppu_unit;
                $ppu_html = '<span class="product-card__ppu">(' . esc_html( $currency . number_format( $per_unit_price, 2 ) . ' per ' . $ppu_label ) . ')</span>';
            }
        }
    }
}
?>
<div class="product-card" data-product-id="<?php echo esc_attr( $product_id ); ?>">
    <div class="product-card__image-wrap">
        <a href="<?php echo esc_url( $product_url ); ?>">
            <?php if ( $image && ! empty( $image['url'] ) ) : ?>
                <img src="<?php echo esc_url( $image['url'] ); ?>"
                     alt="<?php echo esc_attr( $image['alt'] ?? $name ); ?>"
                     class="product-img" loading="lazy">
            <?php else : ?>
                <div class="product-img-placeholder">
                    <i class="bi bi-image" style="font-size:2.5rem;color:#d4d4d4"></i>
                </div>
            <?php endif; ?>
        </a>
        <?php
        // Product Ribbons (core) — rule-based stack (Sale -X% / New / Featured /
        // Best Seller), positioned + coloured per Appearance → Product Ribbons.
        // Pass EFFECTIVE price/list_price + on-sale so the Sale ribbon's "-X%"
        // matches this card's displayed discount. Replaces the former hardcoded
        // "Sale" badge and the retired titancart_product_card_ribbons filter.
        echo wp_kses_post( titancart_product_ribbons_html( array_merge( $product, [ 'price' => $price, 'list_price' => $list_price ] ), $on_sale ) ); // WP.org R2 item 6: kses_post at echo (div/span + class/style — safecss allows background).
        ?>
        <div class="product-hover-actions">
            <?php if ( $wishlist_enabled ) : ?>
            <button type="button" class="btn-action-circle tc-wishlist-toggle" data-product-id="<?php echo esc_attr( $product_id ); ?>" title="Wishlist"><i class="bi bi-heart"></i></button>
            <?php endif; ?>
            <?php if ( $qv_enabled ) : ?>
            <button type="button" class="btn-action-circle tc-quickview-btn" data-quickview="<?php echo esc_attr( $product_id ); ?>" title="Quick view"><i class="bi bi-eye"></i></button>
            <?php endif; ?>
            <?php if ( $compare_enabled ) : ?>
            <button type="button" class="btn-action-circle tc-compare-toggle" data-product-id="<?php echo esc_attr( $product_id ); ?>" title="Compare"><i class="bi bi-arrow-left-right"></i></button>
            <?php endif; ?>
        </div>
        <?php if ( $catalog_mode_on && $cm_type === 'inquiry' && $in_stock ) : ?>
            <div class="product-card__cart-overlay product-card__cart-overlay--inquiry">
                <a href="<?php echo esc_url( $cm_inquiry_url ); ?>" class="product-card__cart-btn product-card__inquiry-btn"><i class="bi bi-envelope"></i> <?php echo esc_html( $cm_inquiry_text ); ?></a>
            </div>
        <?php elseif ( $in_stock && ! $deny_cart ) : ?>
            <div class="product-card__cart-overlay">
                <?php if ( $is_variation ) : ?>
                    <a href="<?php echo esc_url( $product_url ); ?>" class="product-card__cart-btn product-card__choose-btn"><?php esc_html_e( 'Choose Options', 'titancart-lite' ); ?></a>
                <?php else : ?>
                    <button type="button" class="product-card__cart-btn tc-add-to-cart-btn" data-product-id="<?php echo esc_attr( $product_id ); ?>">Add to Cart</button>
                <?php endif; ?>
            </div>
        <?php elseif ( ! $in_stock ) : ?>
            <div class="product-card__cart-overlay product-card__cart-overlay--notify">
                <a href="<?php echo esc_url( $product_url ); ?>#tc-notify-wrap" class="product-card__cart-btn product-card__notify-btn"><i class="bi bi-bell"></i> Notify Me</a>
            </div>
        <?php endif; ?>
    </div>

    <!-- ═══ Info column (grid: basic, list: expanded) ═══ -->
    <div class="product-card__body">
        <?php if ( '' !== $brand ) : ?><span class="product-card__brand"><?php echo esc_html( $brand ); ?></span><?php endif; ?>
        <a href="<?php echo esc_url( $product_url ); ?>" class="product-title"><?php echo esc_html( $name ); ?></a>

        <!-- List-only: rating + product code -->
        <div class="product-card__meta-row">
            <?php if ( $rating_count > 0 ) : ?>
            <span class="product-card__stars">
                <?php for ( $s = 1; $s <= 5; $s++ ) : ?>
                    <i class="bi bi-star<?php echo $s <= round( $rating_avg ) ? '-fill' : ''; ?>" style="color:#f59e0b;font-size:12px"></i>
                <?php endfor; ?>
                <span class="product-card__review-count">(<?php echo esc_html( $rating_count ); ?>)</span>
            </span>
            <?php endif; ?>
            <?php if ( $sku ) : ?>
            <span class="product-card__sku">Code: <?php echo esc_html( $sku ); ?></span>
            <?php endif; ?>
        </div>

        <!-- Compact-only: stock status below product code -->
        <span class="product-card__body-stock <?php echo $in_stock ? 'product-card__body-stock--in' : 'product-card__body-stock--out'; ?>">
            <?php echo $in_stock ? esc_html__( 'In Stock', 'titancart-lite' ) : esc_html__( 'Out of Stock', 'titancart-lite' ); ?>
        </span>

        <!-- List-only: description -->
        <?php if ( $short_desc ) : ?>
        <p class="product-card__short-desc"><?php echo esc_html( wp_strip_all_tags( $short_desc ) ); ?></p>
        <?php endif; ?>

        <!-- Feature attributes — honor each attribute's "List Display" (filter_type):
             'color' → swatch dots (grid + list), 'none' → hidden, else → text chip (list view).
             Mirrors assets/js/shop.js COLOR_MAP / buildCardsHtml so the PHP initial-load
             cards and the AJAX-rendered cards look identical. -->
        <?php
        if ( ! function_exists( 'titancart_card_swatch_hex' ) ) {
            /**
             * Resolve a colour-variant label (+ optional stored hex) to a CSS colour.
             * Map values are byte-identical to shop.js COLOR_MAP; unmapped names fall
             * back to a deterministic HSL hash (same algorithm as colorNameToHex()).
             */
            function titancart_card_swatch_hex( $name, $hex = '' ) {
                if ( $hex && preg_match( '/^#[0-9A-Fa-f]{3,6}$/', (string) $hex ) ) {
                    return $hex;
                }
                static $map = [
                    'red'=>'#EF4444','blue'=>'#3B82F6','green'=>'#22C55E','yellow'=>'#EAB308',
                    'orange'=>'#F97316','purple'=>'#A855F7','pink'=>'#EC4899','black'=>'#171717',
                    'white'=>'#FAFAFA','gray'=>'#6B7280','grey'=>'#6B7280','brown'=>'#92400E',
                    'navy'=>'#1E3A5F','beige'=>'#D4B896','cream'=>'#FFFDD0','gold'=>'#D4AF37',
                    'silver'=>'#C0C0C0','teal'=>'#14B8A6','coral'=>'#F87171','indigo'=>'#6366F1',
                    'maroon'=>'#7F1D1D','olive'=>'#84CC16','tan'=>'#D2B48C','turquoise'=>'#06B6D4',
                    'burgundy'=>'#800020','charcoal'=>'#36454F','ivory'=>'#FFFFF0','lavender'=>'#C4B5FD',
                    'mint'=>'#A7F3D0','peach'=>'#FDBA74','rust'=>'#B91C1C','sage'=>'#9CA38F',
                    'slate'=>'#64748B','wine'=>'#722F37','khaki'=>'#C3B091','mauve'=>'#E0B0FF',
                    'mustard'=>'#CEAB07','plum'=>'#7B2D8B','taupe'=>'#483C32',
                ];
                $k = strtolower( trim( (string) $name ) );
                if ( isset( $map[ $k ] ) ) {
                    return $map[ $k ];
                }
                if ( preg_match( '/^#[0-9a-f]{3,6}$/i', $k ) ) {
                    return $k;
                }
                $hash = 0;
                $len  = strlen( $k );
                for ( $i = 0; $i < $len; $i++ ) {
                    $hash = ( ord( $k[ $i ] ) + ( ( $hash << 5 ) - $hash ) ) & 0xFFFFFFFF;
                }
                return 'hsl(' . ( abs( $hash ) % 360 ) . ',55%,50%)';
            }
        }

        // Split into colour-swatch groups (filter_type='color') vs text chips.
        $color_groups = [];
        $color_order  = [];
        $text_chips   = [];
        foreach ( array_slice( (array) $features, 0, 6 ) as $feat ) {
            $feat_name  = $feat['name'] ?? $feat['feature_name'] ?? '';
            $feat_value = $feat['variant_name'] ?? $feat['value_str'] ?? $feat['value_text'] ?? '';
            $feat_type  = $feat['filter_type'] ?? 'checkbox';
            if ( ! $feat_name || $feat_value === '' || $feat_type === 'none' ) {
                continue;
            }
            if ( $feat_type === 'color' ) {
                if ( ! isset( $color_groups[ $feat_name ] ) ) {
                    $color_groups[ $feat_name ] = [];
                    $color_order[]              = $feat_name;
                }
                $color_groups[ $feat_name ][] = [
                    'label' => $feat_value,
                    'hex'   => titancart_card_swatch_hex( $feat_value, $feat['color_hex'] ?? '' ),
                ];
            } else {
                $text_chips[] = [ 'name' => $feat_name, 'value' => $feat_value ];
            }
        }
        ?>
        <?php foreach ( $color_order as $cg_name ) : ?>
        <div class="product-card__swatches">
            <em class="product-card__swatches-label"><?php echo esc_html( $cg_name ); ?></em>
            <span class="product-card__swatch-dots">
                <?php foreach ( $color_groups[ $cg_name ] as $c ) : ?>
                <span class="product-card__swatch" title="<?php echo esc_attr( $c['label'] ); ?>" style="background:<?php echo esc_attr( $c['hex'] ); ?>"></span>
                <?php endforeach; ?>
            </span>
        </div>
        <?php endforeach; ?>
        <?php if ( ! empty( $text_chips ) ) : ?>
        <div class="product-card__features">
            <?php foreach ( $text_chips as $feat ) : ?>
                <span class="product-card__feature">
                    <em class="product-card__feature-label"><?php echo esc_html( $feat['name'] ); ?></em>
                    <em><?php echo esc_html( $feat['value'] ); ?></em>
                </span>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Grid view: price shown here (list view hides this, shows in control column) -->
        <div class="product-card__price-grid">
            <?php if ( $hide_price ) : ?>
                <div class="product-card__price-row">
                    <a href="<?php echo esc_url( home_url( '/my-account/' ) ); ?>" class="product-price" style="font-size:12px;color:#2563EB"><?php esc_html_e( 'Login to see price', 'titancart-lite' ); ?></a>
                </div>
            <?php else : ?>
                <div class="product-card__price-row">
                    <span class="product-price"><?php echo esc_html( $currency . number_format( $price, 2 ) ); ?></span>
                    <?php if ( $on_sale ) : ?>
                        <span class="product-original-price"><?php echo esc_html( $currency . number_format( $list_price, 2 ) ); ?></span>
                    <?php endif; ?>
                    <?php if ( $show_tax_on_catalog ) : ?>
                        <span class="product-card__tax-note">incl. tax</span>
                    <?php endif; ?>
                    <?php echo wp_kses_post( $ppu_html ); // WP.org R2 item 6: kses_post at echo. ?>
                </div>
            <?php endif; ?>
            <?php if ( ! $in_stock ) : ?>
                <span class="product-card__stock-badge product-card__stock-badge--out">Out of Stock</span>
            <?php elseif ( $show_stock && $stock_qty > 0 ) : ?>
                <span class="product-card__stock-badge product-card__stock-badge--count"><?php echo esc_html( $stock_qty ); ?> in stock</span>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══ Control column (list view only — price, stock, cart) ═══ -->
    <div class="product-card__control">
        <?php if ( $hide_price ) : ?>
            <a href="<?php echo esc_url( home_url( '/my-account/' ) ); ?>" class="product-price" style="font-size:13px;color:#2563EB"><?php esc_html_e( 'Login to see price', 'titancart-lite' ); ?></a>
        <?php else : ?>
            <div class="product-card__control-price">
                <span class="product-price"><?php echo esc_html( $currency . number_format( $price, 2 ) ); ?></span>
                <?php if ( $on_sale ) : ?>
                    <span class="product-original-price"><?php echo esc_html( $currency . number_format( $list_price, 2 ) ); ?></span>
                <?php endif; ?>
                <?php if ( $show_tax_on_catalog ) : ?>
                    <span class="product-card__tax-note">incl. tax</span>
                <?php endif; ?>
                <?php echo wp_kses_post( $ppu_html ); // WP.org R2 item 6: kses_post at echo. ?>
            </div>
        <?php endif; ?>

        <?php if ( ! $in_stock ) : ?>
            <span class="product-card__stock-badge product-card__stock-badge--out" style="margin:8px 0">Out of Stock</span>
        <?php else : ?>
            <span class="product-card__stock-badge product-card__stock-badge--in" style="margin:8px 0">In Stock</span>
        <?php endif; ?>

        <?php if ( $catalog_mode_on && $cm_type === 'inquiry' && $in_stock ) : ?>
        <a href="<?php echo esc_url( $cm_inquiry_url ); ?>" class="product-card__list-cart-btn product-card__list-inquiry-btn">
            <i class="bi bi-envelope"></i> <?php echo esc_html( $cm_inquiry_text ); ?>
        </a>
        <?php elseif ( $in_stock && ! $deny_cart ) : ?>
        <?php if ( $is_variation ) : ?>
        <a href="<?php echo esc_url( $product_url ); ?>" class="product-card__list-cart-btn product-card__list-choose-btn">
            <i class="bi bi-sliders"></i> <?php esc_html_e( 'Choose Options', 'titancart-lite' ); ?>
        </a>
        <?php else : ?>
        <button type="button" class="product-card__list-cart-btn tc-add-to-cart-btn" data-product-id="<?php echo esc_attr( $product_id ); ?>">
            <i class="bi bi-cart-plus"></i> Add to Cart
        </button>
        <?php endif; ?>
        <?php elseif ( ! $in_stock ) : ?>
        <a href="<?php echo esc_url( $product_url ); ?>#tc-notify-wrap" class="product-card__list-cart-btn product-card__list-notify-btn">
            <i class="bi bi-bell"></i> Notify Me
        </a>
        <?php endif; ?>

        <div class="product-card__control-actions">
            <?php if ( $wishlist_enabled ) : ?>
            <button type="button" class="product-card__control-icon tc-wishlist-toggle" data-product-id="<?php echo esc_attr( $product_id ); ?>" title="Wishlist"><i class="bi bi-heart"></i></button>
            <?php endif; ?>
            <?php if ( $compare_enabled ) : ?>
            <button type="button" class="product-card__control-icon tc-compare-toggle" data-product-id="<?php echo esc_attr( $product_id ); ?>" title="Compare"><i class="bi bi-arrow-left-right"></i></button>
            <?php endif; ?>
        </div>
    </div>
</div>
