@extends('frontend.layouts.app')
@section('content')
    <div class="container mt-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="#">Home</a></li>
                <li class="breadcrumb-item active" aria-current="page">Shopping Cart</li>
            </ol>
        </nav>
    </div>

    <section>
        <div class="container">
            <div class="row mb-5 mt-5">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                        <tr>
                            <th class="table-heading product-thumbnail">Image</th>
                            <th class="table-heading product-name">Product</th>
                            <th class="table-heading product-size">Size</th>
                            <th class="table-heading product-price">Price</th>
                            <th class="table-heading product-price">Discount</th>
                            <th class="table-heading product-quantity">Quantity</th>
                            <th class="table-heading product-total">Total</th>
                            <th class="table-heading product-remove">Remove</th>
                        </tr>
                        </thead>
                        <tbody id="additem">

                        </tbody>
                    </table>
                </div>

            </div>
        </div>

        <div class="container">
            <div class="row">
                <div class="d-flex justify-content-end align-items-center">
                    <div class="summary">
                        <div class="mb-4">
                            <h4 class="summary-text">Order Summary</h4>
                        </div>
                        <div class="row mb-3">
                            <div class="col">
                                <span class="text-black">Subtotal</span>
                            </div>
                            <div class="col text-end">
                                <strong class="text-black subTotal"></strong>
                            </div>
                        </div>
                        <!--<div class="row mb-3">-->
                        <!--    <div class="col">-->
                        <!--        <span class="text-black ship-price">-->
                        <!--            Shipping (within 3-4 days inside Dhaka, within 4-7 days outside Dhaka)-->
                        <!--        </span>-->
                        <!--    </div>-->
                        <!--    <div class="col text-end">-->
                        <!--        <strong class="text-black shipp">100</strong>-->
                        <!--    </div>-->
                        <!--</div>-->
                        <div class="row mb-3">
                            <div class="col">
                                <span class="text-black ship-price">Discount</span>
                            </div>
                            <div class="col text-end">
                                <strong class="text-black discount">0.00</strong>
                            </div>
                        </div>
                        <div class="row mb-5">
                            <div class="col">
                                <span class="text-black">Total</span>
                            </div>
                            <div class="col text-end">
                                <strong class="text-black total"></strong>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <a href="javascript:void(0)">
                                    <button class="btn btn-dark py-2 myorder">Proceed To Checkout</button>
                                </a>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
        </div>

    </section>
@endsection

@push('style')
    <style>
        .quantity-container {
            max-width: 250px;
            min-width: 150px;
        }

        .quantity-amount {
            min-width: 100px;
            flex-grow: 1;
            font-size: 16px;
        }
    </style>
@endpush

@push('script')
    <script>
        // GA4 helper
        window.dataLayer = window.dataLayer || [];

        function pushEcomEvent(eventName, ecommerceData) {
            window.dataLayer.push({ecommerce: null});
            window.dataLayer.push({
                event: eventName,
                ecommerce: ecommerceData
            });
        }

        var cart = new Cart();

        $(document).ready(function () {
            $(".cartTotal").html(cart.totalItems());

            let totalItem = cart.getItems();
            let html = "";

            // GA4 view_cart data build
            let gaItems = [];
            let gaTotalValue = 0;
            const gaBrand = @json(config('app.name', 'MyCommerce'));

            totalItem.forEach(element => {
                let qty = parseInt(element.quantity || element.qty || 1, 10);
                if (isNaN(qty) || qty < 1) qty = 1;

                html += ` <tr class="trElement" data-product-id="${element.id}">
                            <td class="product-thumbnail">
                                <img src="{{ asset('storage') }}/${element.thumbnail}" alt="Image" class="" width="100"
                                     height="100">
                            </td>
                            <td class="product-name">
                                <p class="text-black">${element.name}</p>
                            </td>
                            <td class="product-size">
                                <p class="text-black">${element.size !== null ? element.size : ""}</p>
                            </td>
                            <td class="price">${element.price}</td>
                            <td class="p-iscount">${element.discount !== null && element.discount !== undefined ? element.discount : ''}</td>
                            <td>
                                <div class="input-group mb-3 d-flex justify-content-center align-items-center flex-nowrap quantity-container"
                                     style="max-width: 120px;">
                                    <div class="input-group-prepend">
                                        <button class="btn btn-outline-black decrease" type="button">&minus;</button>
                                    </div>

                                    <input type="text"
                                           class="form-control text-center quantity-amount totalQamount"
                                           value="${qty}"
                                           aria-label="Quantity">

                                    <div class="input-group-append">
                                        <button class="btn btn-outline-black increase" type="button">&plus;</button>
                                    </div>
                                </div>
                            </td>

                            <td class="totalPrice"></td>
                            <td>
                                <a href="#" class="btn btn-black btn-sm removeElement cart-trash"
                                   data-ga-remove="1"
                                   data-product-id="${element.id}">
                                    <i class="fa-solid fa-trash"></i>
                                </a>
                            </td>
                        </tr> `;

                // ---- GA4 item object (discount-aware price) ----
                let basePrice = parseFloat(element.price || 0);
                let disc      = parseFloat(element.discount || 0);
                if (isNaN(basePrice)) basePrice = 0;
                if (isNaN(disc))      disc = 0;

                // final unit price = discount > 0 ? discount : base price
                let finalPrice = (disc > 0 && (disc < basePrice || basePrice === 0)) ? disc : basePrice;

                let gaQty = qty;

                gaItems.push({
                    item_id: String(element.id),
                    item_name: String(element.name || 'Product'),
                    affiliation: gaBrand,
                    item_brand: gaBrand,
                    item_category: String(element.category_name || ''),
                    price: finalPrice,
                    quantity: gaQty
                });
                gaTotalValue += finalPrice * gaQty;

                return html;
            });

            $("#additem").html(html);

            // ---- helper: per-row effective unit price (discount-aware) ----
            function getUnitPrice(row) {
                let basePrice = parseFloat(row.find('.price').text()) || 0;
                let disc      = parseFloat(row.find('.p-iscount').text()) || 0;

                if (disc > 0 && (disc < basePrice || basePrice === 0)) {
                    return disc;
                }
                return basePrice;
            }

            // ---- GA4: view_cart event on page load ----
            if (gaItems.length) {
                pushEcomEvent('view_cart', {
                    currency: "BDT",
                    value: gaTotalValue,
                    items: gaItems
                });
            }

            $("#additem").on('click', '.increase', function () {
                let row = $(this).closest("tr");
                let amount = parseInt(row.find(".totalQamount").val(), 10);
                if (isNaN(amount) || amount < 1) {
                    amount = 1;
                }
                amount++;
                row.find(".totalQamount").val(amount);

                let productId = row.data("product-id");
                cart.updateTotalQuantity(productId, amount);
                cart.updateTotalPrice();

                // recalc row + summary
                recalcRowTotal(row);
                subTotal();
            });

            $("#additem").on('click', '.decrease', function () {
                let row = $(this).closest("tr");
                let amount = parseInt(row.find(".totalQamount").val(), 10);
                if (isNaN(amount) || amount < 1) {
                    amount = 1;
                }
                if (amount > 1) {
                    amount--;
                    row.find(".totalQamount").val(amount);
                    let productId = row.data("product-id");
                    cart.updateTotalQuantity(productId, amount);
                    cart.updateTotalPrice();

                    // recalc row + summary
                    recalcRowTotal(row);
                    subTotal();
                }
            });

            function recalcRowTotal(row) {
                let unitPrice = getUnitPrice(row);
                let quantity = parseInt(row.find('.totalQamount').val(), 10);
                if (isNaN(quantity) || quantity < 1) quantity = 1;
                let total = unitPrice * quantity;
                row.find('.totalPrice').text(total.toFixed(2));
            }

            // remove_from_cart + existing remove logic
            $("#additem").on('click', '.removeElement', function (event) {
                event.preventDefault();

                let row = $(this).closest("tr");
                let productId = row.data("product-id");

                // GA4 remove_from_cart payload build from current row
                let unitPrice = getUnitPrice(row);
                let qty = parseInt(row.find('.totalQamount').val() || '1', 10);
                if (isNaN(qty) || qty < 1) qty = 1;

                let itemName = row.find('.product-name p').text().trim();

                pushEcomEvent('remove_from_cart', {
                    currency: "BDT",
                    value: unitPrice * qty,
                    items: [{
                        item_id: String(productId),
                        item_name: itemName,
                        affiliation: gaBrand,
                        item_brand: gaBrand,
                        item_category: "",
                        price: unitPrice,
                        quantity: qty
                    }]
                });

                // existing behaviour
                row.remove();
                cart.removeItem(productId);
                $(".cartTotal").html(cart.totalItems());
                subTotal();
            });

            $("#additem").on('click', '.decrease, .increase', function () {
                let row = $(this).closest('tr');
                recalcRowTotal(row);
                subTotal();
            });

            function totalprice() {
                $(".totalPrice").each(function () {
                    let row = $(this).closest("tr");
                    let unitPrice = getUnitPrice(row);
                    let quantity = parseFloat(row.find(".totalQamount").val()) || 0;
                    if (quantity < 1) quantity = 1;
                    let ptotal = unitPrice * quantity;
                    $(this).text(ptotal.toFixed(2));
                });
                cart.updateTotalPrice();
            }

            /**
             * Subtotal / Total calculation
             * unit price already discount-aware, তাই এখানে আর আলাদা করে discount নাই।
             */
            function subTotal() {
                let subtotal = 0;

                $(".totalPrice").each(function () {
                    let val = parseFloat($(this).text());
                    if (!isNaN(val)) {
                        subtotal += val;
                    }
                });

                $(".subTotal").text(subtotal.toFixed(2));

                // discount already price-e adjust করা, তাই এখানে extra discount = 0
                let pro_discount = 0;
                $(".discount").text(pro_discount.toFixed(2));

                let shipp = parseFloat($(".shipp").text()) || 0;

                let total_price = subtotal + shipp;

                $(".total").text(total_price.toFixed(2));
            }

            totalprice();
            subTotal();

            $(document).on('click', '.myorder', function () {

    // ---------- GA4 begin_checkout ----------
    let beginItems = [];
    let beginTotal = 0;

            $("#additem").find("tr.trElement").each(function (index) {
                const row = $(this);
                const productId = row.data("product-id");
                const itemName  = row.find('.product-name p').text().trim();
                const unitPrice = getUnitPrice(row);
                let qty         = parseInt(row.find('.totalQamount').val() || '1', 10);
                if (isNaN(qty) || qty < 1) qty = 1;
        
                beginItems.push({
                    item_id: String(productId),
                    item_name: itemName,
                    affiliation: gaBrand,
                    item_brand: gaBrand,
                    item_category: "",
                    price: unitPrice,
                    quantity: qty
                });
        
                beginTotal += unitPrice * qty;
            });
        
            if (beginItems.length) {
                pushEcomEvent('begin_checkout', {
                    currency: "BDT",
                    value: beginTotal,
                    items: beginItems
                });
            }
        
            // ---------- existing behaviour ----------
            let total_price = parseFloat($(".total").text()) || 0;
            let productSubtotal = parseFloat($(".subTotal").text()) || 0;
            let pdiscount = $(".discount").text();
        
            sessionStorage.setItem("total_price", total_price);
            sessionStorage.setItem("productSubtotal", productSubtotal);
            sessionStorage.setItem("discount", pdiscount);
        
            window.location.href = "{{ route('checkout') }}";
        });

        });
    </script>
@endpush
