<?php
    $hasDiscount = !is_null($product->discount_price) && $product->discount_price > 0;
    $basePrice   = $product->price ?: 0;
    $finalPrice  = $hasDiscount ? $product->discount_price : $basePrice;

    $brandName   = 'SEF Card';
    $category    = optional($product->category)->name ?? '';
    $affiliation = config('app.name', 'SEF Card');
?>

<script>
    // GA4 dataLayer ensure
    window.dataLayer = window.dataLayer || [];

    (function () {
        // PHP থেকে আসা প্রোডাক্ট ডাটা JS object এ আনছি
        const product = {
            item_id: <?php echo json_encode($product->id, 15, 512) ?>,
            item_name: <?php echo json_encode($product->name, 15, 512) ?>,
            affiliation: <?php echo json_encode($affiliation, 15, 512) ?>,
            item_brand: <?php echo json_encode($brandName, 15, 512) ?>,
            item_category: <?php echo json_encode($category, 15, 512) ?>,
            price: <?php echo e(number_format($finalPrice, 2, '.', '')); ?>,
            google_business_vertical: "retail"
        };

        // ========== view_item ==========
        document.addEventListener('DOMContentLoaded', function () {
            window.dataLayer.push({ecommerce: null});
            window.dataLayer.push({
                event: "view_item",
                ecommerce: {
                    currency: "BDT",
                    value: product.price,
                    items: [product]
                }
            });
        });

        // ========== add_to_cart ==========
        document.addEventListener('click', function (e) {
            const btn = e.target.closest('.getcartitem');
            if (!btn) return;

            // quantity আপাতত ১ ধরলাম (তোমার details পেজে qty ফিল্ড নেই)
            let qty = 1;

            // size থাকলে সেটাও পাঠাই
            let sizeText = '';
            const sizeEl = document.querySelector('.selected-size');
            if (sizeEl && sizeEl.textContent) {
                sizeText = sizeEl.textContent.replace('Selected size:', '').trim();
            }

            const item = Object.assign({}, product, {
                item_variant: sizeText || undefined,
                quantity: qty
            });

            window.dataLayer.push({ecommerce: null});
            window.dataLayer.push({
                event: "add_to_cart",
                ecommerce: {
                    currency: "BDT",
                    value: item.price * qty,
                    items: [item]
                }
            });
        });
    })();
</script>
<?php /**PATH /home/emdadtwa/sefcard.com/resources/views/frontend/partials/ga4-product.blade.php ENDPATH**/ ?>