
<?php $__env->startSection('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">Checkout</li>
            </ol>
        </nav>
    </div>
    <section>
        <div class="container mt-4">
            <div class="row">
                <div class="col-12 col-sm-12 col-md-12 col-lg-7">
                    <div class="checkout-header">
                        <h1 class="title text-start fw-semibold">Checkout</h1>
                        <h6 class="subtitle">Enter your details and place your order to finish your purchase!</h6>
                    </div>
                    <div class="shipping">

                        <div class="form">
                            <div class="heading d-flex justify-content-start align-items-center gap-2">
                                <p class="address-one d-flex justify-content-center align-items-center m-0">
                                    <i class="fa-solid fa-truck"></i>
                                </p>

                                <p class="text-start m-0 text-light shipping-head">Shipping Address</p>
                            </div>
                            <form class="shipping-form p-3">
                                <div class="phone mb-3">
                                    <label for="phone" class="form-label">Phone</label>
                                    <input type="text" class="form-control" id="phone" name="phone"
                                           aria-describedby="phoneHelp">
                                    <p class="user-phone text-danger"></p>
                                </div>
                                <div class="mb-3">
                                    <label for="name" class="form-label">Name</label>
                                    <input type="text" class="form-control user-name" id="name" name="name"
                                           aria-describedby="emailHelp">
                                    <p class="user_name text-danger"></p>
                                </div>
                                <div class="address mb-3">
                                    <label for="address" class="form-label">Address</label>
                                    <input type="text" class="form-control" id="address" name="address"
                                           aria-describedby="emailHelp">
                                    <p class="user-address text-danger"></p>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="pay-method mt-3">
                        <div class="heading d-flex justify-content-start align-items-center gap-2">

                            <p class="address-one d-flex justify-content-center align-items-center m-0">
                                <i class="fa-solid fa-file-invoice-dollar"></i>
                            </p>

                            <p class="text-start m-0 text-light">Payment Method</p>
                        </div>
                        <form class="method-form p-3" action="">
                            <div class="form-check py-2 m-0">
                                <input class="form-check-input" type="radio" name="flexRadioDefault"
                                       id="flexRadioDefault2" checked>
                                <label class="form-check-label" for="flexRadioDefault2">
                                    <img class="cash" src="/assets/img/shpping.png" alt="">
                                    <span class="cash-text">Cash on delivery</span>
                                </label>
                            </div>
                        </form>

                    </div>

                </div>

                <div class="col-12 col-sm-12 col-md-12 col-lg-5">
                    <div class="order-review">
                        <div class="heading d-flex justify-content-start align-items-center gap-2">
                            <p class="address-one d-flex justify-content-center align-items-center m-0">
                                <i class="fa-solid fa-check"></i>
                            </p>
                            <p class="text-start m-0 text-light">Order Preview</p>
                        </div>
                        <div class="product p-3">

                        </div>
                        <div class="border-top">
                            <div class="d-flex justify-content-between align-items-center p-3">
                                <p class="p-0 m-0">Subtotal</p>
                                <p class="p-0 m-0 subt">Tk 0</p>
                            </div>
                        </div>
                        <div class="border-top">
                            <div class="p-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <p class="p-0 m-0">Shipping</p>
                                    
                                    <p class="p-0 m-0 ship-amount">Tk 0</p>
                                </div>
                                <p class="p-0 mt-1 pqu">
                                    within 3-4 days inside Dhaka, within 4-7 days outside Dhaka
                                </p>
                            </div>
                        </div>
                        <div class="ptotal">
                            <div class="prototal d-flex justify-content-between align-items-center p-3">
                                <p class="p-0 m-0 tov">TOTAL</p>
                                <p class="p-0 m-0 total-price">Tk 0</p>
                            </div>
                        </div>
                        <div class="mt-4 p-3">
                            <p class="p-0 note-title">Important note:</p>
                            <p class="p-0 m-0 note">
                                By clicking Confirme Order, you agree to Brains's
                                <span class="terms">Terms and Conditions.</span>
                            </p>
                        </div>
                        <div class="mt-1 p-3">
                            <p class="p-0 instruntion-title">General Instructions for Cash on Delivery Orders:</p>
                            <p class="p-0 m-0 note">
                                1. Double-check your contact info, like your phone number and
                                address, when you order.
                            </p>
                            <p class="p-0 m-0 note">
                                2. Answer calls from the delivery person to get your order on time.
                            </p>
                            <p class="p-0 m-0 note">
                                3. Pay only when you receive your order. Don't pay in advance.
                            </p>

                        </div>
                        <div class="checkout">
                            <div class="d-flex justify-content-center align-items-center">
                                <button class="chekbtn confirm-order">
                                    <a href="javascript:void(0)">Confirm Order</a>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </section>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('script'); ?>
    <script>
        // GA4 helper for dataLayer
        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());

            var userId = <?php echo json_encode($userId, 15, 512) ?>;
            var userName = <?php echo json_encode($userName, 15, 512) ?>;

            // base subtotal (only products) – already discounted from Cart page
            let productSubtotal = sessionStorage.getItem("productSubtotal");
            productSubtotal = parseFloat(productSubtotal) || 0;

            $('.subt').text('Tk ' + productSubtotal.toFixed(2));

            // shipping & total
            let shippingAmount = 0;
            let total_price = 0;

            if (userId !== null) {
                $('.user-name').val(userName);
            }

            // ---------- helper: final unit price (discount-aware) ----------
            function getFinalUnitPrice(item) {
                let basePrice = parseFloat(item.price || 0);
                let disc = parseFloat(item.discount || 0);

                if (isNaN(basePrice)) basePrice = 0;
                if (isNaN(disc)) disc = 0;

                // discount > 0 & কম হলে discountটাই unit price
                if (disc > 0 && (disc < basePrice || basePrice === 0)) {
                    return disc;
                }
                return basePrice;
            }

            // ---------- CART ITEMS PREVIEW + GA ----------
            let pItems = cart.getItems();
            let allItem = "";

            let gaItems = [];
            let gaTotalValue = 0;
            const gaBrand = <?php echo json_encode(config('app.name', 'MyCommerce'), 512) ?>;

            pItems.forEach(e => {
                let unitPrice = getFinalUnitPrice(e);
                let qty = parseInt(e.quantity || e.qty || 1, 10);
                if (isNaN(qty) || qty < 1) qty = 1;

                let lineTotal = unitPrice * qty;

                allItem += `
                  <div class="d-flex justify-content-between align-items-start mb-3">
                      <div class="d-flex">
                          <div>
                              <img class="checkimage" src="<?php echo e(asset('storage')); ?>/${e.thumbnail}" alt="">
                          </div>
                          <div class="pname ps-2">
                              <p class="p-0 m-0">${e.name}</p>
                              <p class="p-0 m-0 pqu">Qty: ${qty}</p>
                              <p class="p-0 m-0 pqu">Size: ${e.size !== null ? e.size : ""}</p>
                              <p class="p-0 m-0 pqu">unit price: ${unitPrice.toFixed(2)}</p>
                          </div>
                      </div>
                      <div class="pname">
                          <p>Tk ${lineTotal.toFixed(2)}</p>
                      </div>
                  </div>
                `;

                // GA4 item object – discounted price ব্যবহার
                gaItems.push({
                    item_id: String(e.id),
                    item_name: String(e.name || 'Product'),
                    affiliation: gaBrand,
                    item_brand: gaBrand,
                    item_category: String(e.category_name || ''),
                    price: unitPrice,
                    quantity: qty
                });
                gaTotalValue += unitPrice * qty;

                return allItem;
            });

            $(".product").html(allItem);

            if (gaItems.length) {
                pushEcomEvent('begin_checkout', {
                    currency: "BDT",
                    value: gaTotalValue,
                    items: gaItems
                });
            }

            // ---------- SHIPPING LOGIC (Dhaka / outside) ----------
            function calcShippingByAddress(address) {
                if (!address) {
                    // default: treat as outside Dhaka
                    return 120;
                }
                let lower = address.toLowerCase();
                if (lower.includes('dhaka') || lower.includes('ঢাকা')) {
                    return 70;
                }
                return 120;
            }

            function updateShippingAndTotal() {
                let addr = $('#address').val().trim();
                shippingAmount = calcShippingByAddress(addr);

                total_price = productSubtotal + shippingAmount;

                $('.ship-amount').text('Tk ' + shippingAmount.toFixed(2));
                $('.total-price').text('Tk ' + total_price.toFixed(2));
            }

            // initial calc
            updateShippingAndTotal();

            // address change করলে শিপিং আপডেট
            $('#address').on('input blur', function () {
                updateShippingAndTotal();
            });

            // ---------- CONFIRM ORDER ----------
            function resetConfirmButton() {
                var $btn = $('.confirm-order');
                $btn.data('loading', false);
                $btn.prop('disabled', false).removeClass('disabled');
                $btn.find('a').text('Confirm Order');
            }

            $(document).on('click', '.confirm-order', function (event) {
                event.preventDefault();

                var $btn = $('.confirm-order');

                if ($btn.data('loading')) {
                    return;
                }

                // real cart check
                if (cart.totalItems() <= 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Your cart is empty',
                        text: 'Please add items to your cart before placing an order.'
                    });
                    return;
                }

                // latest items
                let pItems = cart.getItems();

                var phone = $('#phone').val().trim();
                var name = $('#name').val().trim();
                var address = $('#address').val().trim();

                $('.user-phone, .user_name, .user-address').text("").hide();

                var isValid = true;

                if (phone === "") {
                    $('.user-phone').text('Phone number is required').show();
                    isValid = false;
                }
                if (name === "") {
                    $('.user_name').text('Name is required').show();
                    isValid = false;
                }
                if (address === "") {
                    $('.user-address').text('Address is required').show();
                    isValid = false;
                }

                if (!isValid) {
                    return;
                }

                let totalVal = parseFloat(total_price || 0);
                if (isNaN(totalVal)) totalVal = 0;

                // GA4: add_payment_info event (COD)
                let payMethod = 'Cash on delivery';
                if (gaItems.length) {
                    pushEcomEvent('add_payment_info', {
                        currency: "BDT",
                        value: totalVal,
                        payment_type: payMethod,
                        items: gaItems
                    });
                }

                let order = [];

                pItems.forEach(product => {
                    let unitPrice = getFinalUnitPrice(product);
                    let qty = parseInt(product.quantity || product.qty || 1, 10);
                    if (isNaN(qty) || qty < 1) qty = 1;

                    let lineTotal = unitPrice * qty;

                    // id ফ্যালব্যাকসহ
                    let id = product.id || product.product_id || product.productId;
                    let size = product.size;
                    let pcode = product.productCode;

                    if (!id) {
                        return; // নিরাপত্তার জন্য invalid item skip
                    }

                    order.push({
                        id: id,
                        quantity: qty,
                        product_size: size,
                        product_code: pcode,
                        totalPrice: lineTotal,   // ✅ discounted line total
                    });

                });

                // button loading state
                $btn.data('loading', true);
                $btn.prop('disabled', true).addClass('disabled');
                $btn.find('a').text('Processing...');

                $.ajax({
                    url: "<?php echo e(url('/order')); ?>",
                    type: 'post',
                    dataType: 'json',
                    data: {
                        _token: "<?php echo e(csrf_token()); ?>",    // ✅ CSRF token directly body te pathাচ্ছি
                        orders: order,
                        userId: userId,
                        phone: phone,
                        name: name,
                        address: address,
                        totalAmount: totalVal   // product + shipping (discounted)
                    },
                    success: function (response) {
                        if (response.status === 'success') {
                            Swal.fire({
                                position: 'center',
                                icon: 'success',
                                title: response.message,
                                showConfirmButton: false,
                                timer: 1500,
                                customClass: {
                                    container: 'custom-swal-container',
                                },
                            }).then(() => {
                                sessionStorage.clear();
                                cart.emptyCart();
                                $(".total-price").text("");
                                $(".subt").text("");
                                window.location.href = "<?php echo e(url('/confirm-order')); ?>/" + response.order_id;
                            });
                        } else {
                            resetConfirmButton();
                            Swal.fire({
                                icon: 'error',
                                title: 'Order failed',
                                text: response.message || 'Something went wrong. Please try again.'
                            });
                        }
                    },
                    error: function (xhr, status, error) {
                        console.log(xhr.responseText);

                        resetConfirmButton();

                        let message = 'Something went wrong. Please try again.';

                        if (xhr.responseJSON && xhr.responseJSON.errors) {
                            let errors = xhr.responseJSON.errors;
                            if (errors.phone && errors.phone[0]) {
                                $('.user-phone').text(errors.phone[0]).show();
                            }
                            if (errors.name && errors.name[0]) {
                                $('.user_name').text(errors.name[0]).show();
                            }
                            if (errors.address && errors.address[0]) {
                                $('.user-address').text(errors.address[0]).show();
                            }

                            message = 'Please check the highlighted fields and try again.';
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            // যদি backend থেকে custom message আসে
                            message = xhr.responseJSON.message;
                        }

                        Swal.fire({
                            icon: 'error',
                            title: 'Order failed',
                            text: message
                        });
                    }
                });
            });
        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('frontend.layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/emdadtwa/sefcard.com/resources/views/frontend/checkout.blade.php ENDPATH**/ ?>