<?php $__env->startSection('content'); ?>
    <!-- Premium Checkout Stylesheet -->
    <link rel="stylesheet" href="<?php echo e(asset('assets/css/checkout.css')); ?>">

    <div class="checkout-page-wrapper">
        <div class="container-fluid" style="padding-left:7.5%;padding-right:7.5%;">
            
            <!-- Breadcrumb Navigation -->
            <div class="checkout-breadcrumb">
                <a href="<?php echo e(route('american.plastic.web')); ?>">Home</a>
                <i class="fas fa-chevron-right"></i>
                <span class="active">Checkout</span>
            </div>
            
            <!-- Page Title Section -->
            <div class="checkout-title-section">
                <h1 class="checkout-main-title">Complete Your Order</h1>
                <p class="checkout-subtitle">Please enter your shipping details and select a payment method below.</p>
            </div>

            
            <?php if($errors->any() || session('error')): ?>
                <div class="checkout-card border-danger bg-light mb-4 position-relative">
                    <button type="button" class="btn-close position-absolute top-0 end-0 m-3" onclick="this.parentElement.style.display='none';" style="border: none; background: transparent; font-size: 1.2rem; cursor: pointer;">&times;</button>
                    <div class="d-flex align-items-center gap-3 mb-3 text-danger">
                        <i class="fas fa-exclamation-circle fa-2x"></i>
                        <h4 class="m-0 fw-bold">Information Required to Proceed</h4>
                    </div>
                    <ul class="text-danger fw-semibold list-unstyled ps-3 mb-0">
                        <?php if(session('error')): ?>
                            <li class="position-relative mb-2"><i class="fas fa-chevron-right me-2 text-danger"></i><?php echo e(session('error')); ?></li>
                        <?php endif; ?>
                        <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <li class="position-relative mb-2"><i class="fas fa-chevron-right me-2 text-danger"></i><?php echo e($error); ?></li>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </ul>
                </div>
            <?php endif; ?>

            <?php if(session('success')): ?>
                <div class="alert alert-success alert-dismissible fade show mb-4 border-start border-4 border-success shadow-sm" role="alert">
                    <strong><i class="fas fa-check-circle me-2"></i> Success:</strong> <?php echo e(session('success')); ?>

                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            <?php endif; ?>

            <?php
                $user = Auth::user();
                $taxBaseSetting = \App\Models\SystemSetting::get('tax_calculation_base', 'selling_price');
                $taxRateSetting = (float) \App\Models\SystemSetting::get('corporate_tax_percentage', 18.00);
                $productdata = App\Models\Product::where('id', $productid)->first();
                $total = $productprice * $quantity;
                
                try {
                    $totalWeightInGrams = ($productdata->weight ?? 0) * ($quantity ?? 1);
                    $totalWeightInKg = $totalWeightInGrams / 1000;
                    $shippingPrice = $totalWeightInKg > 1 ? ceil($totalWeightInKg - 1) * 100 : 0;
                } catch (\Throwable $th) {
                    $shippingPrice = 0;
                }
                
                // Get user details if logged in
                $userdata = null;
                if (Auth::check()) {
                    $userdata = App\Models\Userdata::where('userid', $user->id)->first();
                }
            ?>

            <?php if(Auth::guest()): ?>
                <!-- Guest login helper card -->
                <div class="returning-customer-card shadow-sm">
                    <div class="returning-customer-info">
                        <i class="fas fa-info-circle"></i>
                        <span>Returning customer? Sign in to checkout faster.</span>
                    </div>
                    <a href="#" id="customer" class="returning-customer-btn">Please Login</a>
                </div>
            <?php endif; ?>

            <div class="row">
                <!-- Left Column: Shipping Form -->
                <div class="col-lg-7 col-md-12">
                    <form id="billing-form" class="checkout-form">
                        <?php echo csrf_field(); ?>
                        <?php echo $__env->make('web.home.checkout.partials.shipping_fields', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </form>
                </div>

                <!-- Right Column: Order Summary & Payment Method -->
                <div class="col-lg-5 col-md-12">
                    <div class="sticky-sidebar-summary">
                        <!-- Order Summary Card -->
                        <div class="checkout-card shadow-sm">
                            <div class="card-header-custom">
                                <i class="fas fa-shopping-bag"></i>
                                <h3>Order Summary</h3>
                            </div>

                            <!-- Single Product Summary Row -->
                            <div class="summary-items-list">
                                <div class="summary-item">
                                    <?php
                                        $firstImage = 'default.jpg';
                                        if ($productdata && !empty($productdata->product_image)) {
                                            $imageArray = explode(',', $productdata->product_image);
                                            $firstImage = trim($imageArray[0]) ?: 'default.jpg';
                                        }
                                    ?>
                                    <img src="<?php echo e(asset('admin/assets/img/product/' . $firstImage)); ?>" class="summary-item-img" alt="<?php echo e($productdata->product_name ?? 'Product Image'); ?>">
                                    <div class="summary-item-details">
                                        <h4 class="summary-item-name"><?php echo e($productdata->product_name); ?></h4>
                                        <div class="summary-item-meta">
                                            <div class="color-badge-container">
                                                <span class="color-dot" style="background-color: <?php echo e($setcolor); ?>"></span>
                                                <span><?php echo e($setcolor); ?></span>
                                            </div>
                                            <span>&bull;</span>
                                            <span>Qty: <?php echo e($quantity); ?></span>
                                        </div>
                                    </div>
                                    <div class="summary-item-price-qty">
                                        <span class="summary-item-total">LKR <?php echo e(number_format($productprice, 2)); ?></span>
                                        <span class="summary-item-subtext">each</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Totals List -->
                            <div class="totals-list">
                                <div class="totals-row">
                                    <span class="label">Subtotal</span>
                                    <span class="value base-subtotal">LKR <?php echo e(number_format($total, 2)); ?></span>
                                </div>
                                <div class="totals-row">
                                    <span class="label">Shipping Fee</span>
                                    <span class="value shipping-price">LKR 0.00</span>
                                </div>
                                <?php if(Auth::check() && Auth::user()->is_corporate): ?>
                                    <div class="totals-row tax-row">
                                        <span class="label">Tax (<?php echo e(number_format($taxRateSetting, 1)); ?>%)</span>
                                        <span class="value tax-value">LKR 0.00</span>
                                    </div>
                                <?php endif; ?>
                                <div class="totals-row discount-row" style="display: none;">
                                    <span class="label">Discount</span>
                                    <span class="value discount-value" id="discount_display">- LKR 0.00</span>
                                </div>
                                <div class="totals-row points-row" style="display: none;">
                                    <span class="label">Points Applied</span>
                                    <span class="value points-value" id="points_display">- LKR 0.00</span>
                                </div>
                                <div class="totals-row grand-total">
                                    <span class="label">Total</span>
                                    <span class="value total-price">LKR 0.00</span>
                                </div>
                            </div>

                            <?php if(Auth::check()): ?>
                                <!-- Pay by Recycling Points Summary Widget -->
                                <div class="points-payment-summary-box mt-3">
                                    <div class="points-header">
                                        <div class="points-info">
                                            <div class="points-icon-wrapper">
                                                <i class="fas fa-coins"></i>
                                            </div>
                                            <div class="points-title-desc">
                                                <span class="points-title">Pay with Recycling Points</span>
                                                <span class="points-balance" id="available-points-display" data-points="<?php echo e(Auth::user()->recycling_points ?? 0); ?>">Available: <?php echo e(number_format(Auth::user()->recycling_points ?? 0, 2)); ?> PTS</span>
                                            </div>
                                        </div>
                                        <div class="form-check form-switch m-0">
                                            <input class="form-check-input" type="checkbox" id="use-points-checkbox" role="switch">
                                        </div>
                                        </div>
                                    </div>
                                    <div class="error-message" id="points-error" style="display: none; margin-top: 8px;">
                                        Insufficient points for this order.
                                    </div>
                                </div>
                            <?php endif; ?>

                            <!-- Voucher Container -->
                            <div class="voucher-box mt-4">
                                <h4>Have an E-Voucher?</h4>
                                <div class="voucher-input-wrapper">
                                    <input type="text" id="voucher_input" placeholder="Enter Code" class="modern-field voucher-input">
                                    <button type="button" id="apply_voucher_btn" class="voucher-btn">Apply</button>
                                </div>
                                <div id="voucher_msg" class="voucher-msg" style="display: none;"></div>
                                <input type="hidden" id="applied_voucher_code" name="applied_voucher_code" value="">
                                <input type="hidden" id="discount_amount" name="discount_amount" value="0">
                            </div>
                        </div>

                        <!-- Payment Selection Card -->
                        <?php echo $__env->make('web.home.checkout.partials.payment_methods', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            cal();

            // Trigger login modal for guests
            $('#customer').on('click', function(e) {
                e.preventDefault();
                $('#loginmodal').modal('show');
            });

            // Handle points checkbox toggle
            $('body').on('change', '#use-points-checkbox', function () {
                cal();
            });
        });

        // Deterrence for Page Inspection
        // document.addEventListener('contextmenu', event => event.preventDefault());
        // document.onkeydown = function (e) {
        //     if (e.keyCode == 123 ||
        //         (e.ctrlKey && e.shiftKey && (e.keyCode == 'I'.charCodeAt(0) || e.keyCode == 'C'.charCodeAt(0) || e.keyCode == 'J'.charCodeAt(0))) ||
        //         (e.ctrlKey && e.keyCode == 'U'.charCodeAt(0))) {
        //         return false;
        //     }
        // };

        document.addEventListener("DOMContentLoaded", function () {
            var checkbox = document.getElementById("cartTearm");
            var checkoutButton = document.getElementById("checkout-button");

            // Ensure the button is disabled on page load
            checkoutButton.disabled = true;

            checkbox.addEventListener("change", function () {
                if (checkbox.checked) {
                    checkoutButton.disabled = false;
                } else {
                    checkoutButton.disabled = true;
                }
            });
        });

        function cal() {
            var city = $('#inputCity').val() || 'Pagoda';
            var district = $('#inputdistrict').val() || '';
            let csrfToken = $('meta[name="csrf-token"]').attr('content');

            updateDisplayOnly();

            $.ajax({
                type: "GET",
                url: "<?php echo e(route('zone.check', ':selectedvalue')); ?>".replace(':selectedvalue', city) + "?district=" + encodeURIComponent(district),
                headers: {
                    'X-CSRF-TOKEN': csrfToken
                },
                success: function (response) {
                    let additionalShippingPrice = parseFloat(response) || 0;
                    let initialShippingPrice = parseFloat("<?php echo e($shippingPrice); ?>".replace(/,/g, '')) || 0;
                    let totalShippingPrice = additionalShippingPrice + initialShippingPrice;

                    var productPrice = parseFloat("<?php echo e($productprice); ?>".replace(/,/g, '')) || 0;
                    var qty = parseInt("<?php echo e($quantity); ?>") || 1;
                    var productTotal = productPrice * qty;

                    var taxAmount = 0;
                    <?php if(Auth::check() && Auth::user()->is_corporate): ?>
                        var taxBaseSetting = "<?php echo e($taxBaseSetting); ?>";
                        var cuttedPrice = parseFloat("<?php echo e($productdata->cutted_price ?? $productprice); ?>".replace(/,/g, '')) || 0;
                        var taxBasePrice = (taxBaseSetting === 'cutted_price' && cuttedPrice > 0) ? cuttedPrice : productPrice;

                        taxAmount = Math.round((taxBasePrice * qty * <?php echo e($taxRateSetting); ?>) / 100 * 100) / 100;
                        $('.tax-value').text('LKR ' + taxAmount.toFixed(2));
                    <?php endif; ?>

                    var discount = parseFloat($('#discount_amount').val()) || 0;
                    var grandTotal = Math.max(0, productTotal + parseFloat(totalShippingPrice) + taxAmount - discount);

                    $('.base-subtotal').text('LKR ' + productTotal.toFixed(2));
                    $('.shipping-price').text('LKR ' + totalShippingPrice.toFixed(2));
                    $('.total-price').text('LKR ' + grandTotal.toFixed(2));
                    $('#totalamount').val(grandTotal.toFixed(2));
                    $('#shipping_amount_hidden').val(totalShippingPrice.toFixed(2));
                    $('#tax_amount_hidden').val(taxAmount.toFixed(2));
                    validatePoints(grandTotal);
                },
                error: function (error) {
                    updateDisplayOnly();
                }
            });
        }

        function updateDisplayOnly() {
            var productPrice = parseFloat("<?php echo e($productprice); ?>".replace(/,/g, '')) || 0;
            var qty = parseInt("<?php echo e($quantity); ?>") || 1;
            var productTotal = productPrice * qty;

            var initialShippingPrice = parseFloat("<?php echo e($shippingPrice); ?>".replace(/,/g, '')) || 0;
            var discount = parseFloat($('#discount_amount').val()) || 0;

            var taxAmount = 0;
            <?php if(Auth::check() && Auth::user()->is_corporate): ?>
                var taxBaseSetting = "<?php echo e($taxBaseSetting); ?>";
                var cuttedPrice = parseFloat("<?php echo e($productdata->cutted_price ?? $productprice); ?>".replace(/,/g, '')) || 0;
                var taxBasePrice = (taxBaseSetting === 'cutted_price' && cuttedPrice > 0) ? cuttedPrice : productPrice;

                taxAmount = Math.round((taxBasePrice * qty * <?php echo e($taxRateSetting); ?>) / 100 * 100) / 100;
                $('.tax-value').text('LKR ' + taxAmount.toFixed(2));
            <?php endif; ?>

            var grandTotal = Math.max(0, productTotal + initialShippingPrice + taxAmount - discount);

            $('.base-subtotal').text('LKR ' + productTotal.toFixed(2));
            $('.shipping-price').text('LKR ' + initialShippingPrice.toFixed(2));
            $('.total-price').text('LKR ' + grandTotal.toFixed(2));
            $('#totalamount').val(grandTotal.toFixed(2));
            $('#shipping_amount_hidden').val(initialShippingPrice.toFixed(2));
            $('#tax_amount_hidden').val(taxAmount.toFixed(2));
            validatePoints(grandTotal);
        }

        function validatePoints(grandTotal) {
            var displaySpan = document.getElementById('available-points-display');
            if (displaySpan) {
                var availablePoints = parseFloat(displaySpan.getAttribute('data-points')) || 0;
                var pointsCheckbox = document.getElementById('use-points-checkbox');
                var pointsError = document.getElementById('points-error');

                if (availablePoints <= 0) {
                    if (pointsCheckbox) {
                        pointsCheckbox.disabled = true;
                        pointsCheckbox.checked = false;
                    }
                    if (pointsError) {
                        pointsError.style.display = 'block';
                        pointsError.innerText = 'You do not have any recycling points.';
                    }
                } else {
                    if (pointsCheckbox) pointsCheckbox.disabled = false;
                    if (pointsError) pointsError.style.display = 'none';
                }
                
                updateTotalsWithPoints(grandTotal);
            }
        }

        function updateTotalsWithPoints(grandTotal) {
            var displaySpan = document.getElementById('available-points-display');
            var pointsCheckbox = document.getElementById('use-points-checkbox');
            var pointsRadio = document.getElementById('points');
            
            if (!displaySpan || !pointsCheckbox) return;

            var availablePoints = parseFloat(displaySpan.getAttribute('data-points')) || 0;
            
            if (pointsCheckbox.checked && availablePoints > 0) {
                var pointsApplied = Math.min(availablePoints, grandTotal);
                var remainingTotal = grandTotal - pointsApplied;

                // Update Points Applied Row
                $('.points-row').show();
                $('#points_display').text('- LKR ' + pointsApplied.toFixed(2));

                // Update Displayed Grand Total and hidden input
                $('.total-price').text('LKR ' + remainingTotal.toFixed(2));
                $('#totalamount').val(remainingTotal.toFixed(2));

                if (remainingTotal <= 0) {
                    // Fully covered by points
                    if (pointsRadio) pointsRadio.checked = true;
                    $('.payment-card-input:not(#points)').prop('checked', false);
                    $('.payment-card-grid').css('opacity', '0.5').css('pointer-events', 'none');
                } else {
                    // Partially covered by points
                    if (pointsRadio) pointsRadio.checked = false;
                    $('.payment-card-grid').css('opacity', '1').css('pointer-events', 'auto');
                }
            } else {
                // Points not checked or none available
                $('.points-row').hide();
                $('.total-price').text('LKR ' + grandTotal.toFixed(2));
                $('#totalamount').val(grandTotal.toFixed(2));
                if (pointsRadio) pointsRadio.checked = false;
                $('.payment-card-grid').css('opacity', '1').css('pointer-events', 'auto');
            }
        }

        $(document).ready(function () {
            $('#apply_voucher_btn').on('click', function () {
                var code = $('#voucher_input').val().trim();
                var productPrice = parseFloat("<?php echo e($productprice); ?>".replace(/,/g, ''));
                var qty = parseInt("<?php echo e($quantity); ?>") || 1;
                var subtotal = productPrice * qty;
                var msgDiv = $('#voucher_msg');
                var email = $('#input-email').val() || '';

                if (code === '') {
                    msgDiv.text('Please enter a voucher code.').css('color', 'red').show();
                    return;
                }

                var shipping = parseFloat($('#shipping_amount_hidden').val()) || parseFloat("<?php echo e($shippingPrice); ?>".replace(/,/g, '')) || 0;
                var tax = parseFloat($('#tax_amount_hidden').val()) || 0;
                var orderTotal = subtotal + shipping + tax;

                $.ajax({
                    type: "POST",
                    url: "<?php echo e(route('vouchers.apply')); ?>",
                    data: {
                        code: code,
                        subtotal: subtotal,
                        order_total: orderTotal,
                        email: email,
                        _token: "<?php echo e(csrf_token()); ?>"
                    },
                    success: function (response) {
                        if (response.success) {
                            msgDiv.text(response.message).css('color', 'green').show();

                            $('#applied_voucher_code').val(response.code);
                            $('#discount_amount').val(response.discount);

                            $('#discount_display').text('- LKR ' + response.discount);
                            $('.discount-row').show();

                            cal(); // Re-calculate grand total
                        } else {
                            msgDiv.text(response.message).css('color', 'red').show();
                            $('#applied_voucher_code').val('');
                            $('#discount_amount').val(0);
                            $('.discount-row').hide();
                            cal();
                        }
                    },
                    error: function () {
                        msgDiv.text('An error occurred. Please try again.').css('color', 'red').show();
                    }
                });
            });
        });

        $('body').on('click', '#checkout-button', function () {
            const fullNumber = iti.getNumber();
            document.querySelector("#input-telephone").value = fullNumber;

            var email = document.getElementById('input-email');
            var telephone = document.getElementById('input-telephone');
            var addressone = document.getElementById('input-address-1');
            var fullname = document.getElementById('input-fullname');
            var district = document.getElementById('inputdistrict');
            var city = document.getElementById('inputCity');

            var selectedPaymentMethod = document.querySelector('input[name="payment_method"]:checked');

            if (!selectedPaymentMethod) {
                showNotification('Please select a payment method');
                return false;
            }

            if (fullname.value === "") {
                document.getElementById('input-fullname').focus();
                showNotification('Please fill in your full name');
                return false;
            } else if (!/^\S+@\S+\.\S+$/.test(email.value)) {
                document.getElementById('input-email').focus();
                showNotification('Please fill in your email address');
                return false;
            } else if (telephone.value === "" || !/^\+?\d+$/.test(telephone.value)) {
                document.getElementById('input-telephone').focus();
                showNotification('Please fill in your telephone number');
                return false;
            } else if (district.value === "") {
                document.getElementById('inputdistrict').focus();
                showNotification('Please select district');
                return false;
            } else if (addressone.value === "") {
                document.getElementById('input-address-1').focus();
                showNotification('Please fill in your address');
                return false;
            } else if (city.value === "") {
                document.getElementById('inputCity').focus();
                showNotification('Please fill your city');
                return false;
            }

            var grandTotal = document.getElementById('totalamount').value;
            var companyname = document.getElementById('input-company').value;
            var address_one = document.getElementById('input-address-1').value;
            var address_two = document.getElementById('input-address-2').value;
            var cityVal = document.getElementById('inputCity').value;
            var districtVal = document.getElementById('inputdistrict').value;
            var postal_code = document.getElementById('input-postcode').value;
            var order_note = document.getElementById('ordernte').value;
            var paymentMethod = selectedPaymentMethod.value;

            var description = "<?php echo e($productdata->product_name); ?>";
            var product_id = "<?php echo e($productdata->id); ?>";
            var color = "<?php echo e($setcolor); ?>";
            var qty = "<?php echo e($quantity); ?>";
            var phone = telephone.value;
            var emailVal = email.value;
            var company = companyname;
            var addressoneVal = address_one;
            var addresstwoVal = address_two;
            var postcode = postal_code;
            var ordernote = order_note;
            var shippingprice = $('#shipping_amount_hidden').val() || "<?php echo e($shippingPrice); ?>";
            var weight = "<?php echo e($totalWeightInKg); ?>";

            var paymentData = {
                payment_method: paymentMethod
            };

            fetch('/create-session', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                },
                body: JSON.stringify({
                    amount: grandTotal,
                    desc: description,
                    productid: product_id,
                    cus_firstname: fullname.value,
                    cus_lastname: 'null',
                    order_color: color,
                    order_qty: qty,
                    cus_phone: phone,
                    cus_email: emailVal,
                    cus_company: company,
                    cus_address_one: addressoneVal,
                    cus_address_two: addresstwoVal,
                    cus_city: cityVal,
                    cus_district: districtVal,
                    cus_postcode: postcode,
                    order_note: ordernote,
                    shipping_price: shippingprice,
                    totalweight: weight,
                    voucher_code: $('#applied_voucher_code').val(),
                    discount_amount: $('#discount_amount').val(),
                    payment_data: paymentData,
                    use_points: $('#use-points-checkbox').is(':checked') ? 1 : 0
                }),
            })
            .then(response => response.json())
            .then(session => {
                var sessionid = session.session['session.id'];

                if (paymentMethod === 'cod') {
                    var formData = {
                        amount: grandTotal,
                        description: "<?php echo e($productdata->product_name); ?>",
                        order_id: "<?php echo e(uniqid()); ?>",
                        cus_firstname: fullname.value,
                        cus_email: emailVal,
                        cus_lastname: 'null',
                        order_color: color,
                        order_qty: qty,
                        cus_phone: phone,
                        productid: product_id,
                        cus_company: company,
                        cus_address_one: addressoneVal,
                        cus_address_two: addresstwoVal,
                        cus_city: cityVal,
                        cus_district: districtVal,
                        cus_postcode: postcode,
                        order_note: ordernote,
                        shipping_price: shippingprice,
                        totalweight: weight,
                        voucher_code: $('#applied_voucher_code').val(),
                        discount_amount: $('#discount_amount').val(),
                        payment_data: paymentData,
                        payment_method: paymentMethod,
                        use_points: $('#use-points-checkbox').is(':checked') ? 1 : 0
                    };

                    var queryString = Object.keys(formData).map(key =>
                        key + '=' + encodeURIComponent(formData[key])
                    ).join('&');

                    window.location.href = '<?php echo e(route('american.plastic.web.order.cod.confirmed')); ?>?' +
                        queryString + '&session_id=' + encodeURIComponent(sessionid);
                } else if (paymentMethod === 'points') {
                    var formData = {
                        amount: grandTotal,
                        description: "<?php echo e($productdata->product_name); ?>",
                        order_id: "<?php echo e(uniqid()); ?>",
                        cus_firstname: fullname.value,
                        cus_email: emailVal,
                        cus_lastname: 'null',
                        order_color: color,
                        order_qty: qty,
                        cus_phone: phone,
                        productid: product_id,
                        cus_company: company,
                        cus_address_one: addressoneVal,
                        cus_address_two: addresstwoVal,
                        cus_city: cityVal,
                        cus_district: districtVal,
                        cus_postcode: postcode,
                        order_note: ordernote,
                        shipping_price: shippingprice,
                        totalweight: weight,
                        voucher_code: $('#applied_voucher_code').val(),
                        discount_amount: $('#discount_amount').val(),
                        payment_data: paymentData,
                        payment_method: paymentMethod,
                        use_points: 1
                    };

                    var queryString = Object.keys(formData).map(key =>
                        key + '=' + encodeURIComponent(formData[key])
                    ).join('&');

                    window.location.href = '<?php echo e(route('american.plastic.web.order.points.confirmed')); ?>?' +
                        queryString + '&session_id=' + encodeURIComponent(sessionid);
                } else if (paymentMethod === 'koko') {
                    var formData = {
                        amount: grandTotal,
                        description: "<?php echo e($productdata->product_name); ?>",
                        order_id: "<?php echo e(uniqid()); ?>",
                        cus_firstname: fullname.value,
                        cus_email: emailVal,
                        cus_lastname: 'null',
                        order_color: color,
                        order_qty: qty,
                        cus_phone: phone,
                        productid: product_id,
                        cus_company: company,
                        cus_address_one: addressoneVal,
                        cus_address_two: addresstwoVal,
                        cus_city: cityVal,
                        cus_district: districtVal,
                        cus_postcode: postcode,
                        order_note: ordernote,
                        shipping_price: shippingprice,
                        totalweight: weight,
                        voucher_code: $('#applied_voucher_code').val(),
                        discount_amount: $('#discount_amount').val(),
                        payment_data: paymentData,
                        use_points: $('#use-points-checkbox').is(':checked') ? 1 : 0
                    };

                    var form = document.createElement('form');
                    form.method = 'POST';
                    form.action = '<?php echo e(route('koko.payment.initiate')); ?>';

                    var csrfInput = document.createElement('input');
                    csrfInput.type = 'hidden';
                    csrfInput.name = '_token';
                    csrfInput.value = '<?php echo e(csrf_token()); ?>';
                    form.appendChild(csrfInput);

                    Object.keys(formData).forEach(key => {
                        var input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = key;
                        input.value = formData[key];
                        form.appendChild(input);
                    });

                    document.body.appendChild(form);
                    form.submit();
                } else if (paymentMethod === 'mintpay') {
                    var formData = {
                        amount: grandTotal,
                        description: "<?php echo e($productdata->product_name); ?>",
                        order_id: "<?php echo e(uniqid()); ?>",
                        cus_firstname: fullname.value,
                        cus_email: emailVal,
                        cus_lastname: 'null',
                        order_color: color,
                        order_qty: qty,
                        cus_phone: phone,
                        productid: product_id,
                        cus_company: company,
                        cus_address_one: addressoneVal,
                        cus_address_two: addresstwoVal,
                        cus_city: cityVal,
                        cus_district: districtVal,
                        cus_postcode: postcode,
                        order_note: ordernote,
                        shipping_price: shippingprice,
                        totalweight: weight,
                        voucher_code: $('#applied_voucher_code').val(),
                        discount_amount: $('#discount_amount').val(),
                        payment_data: paymentData,
                        use_points: $('#use-points-checkbox').is(':checked') ? 1 : 0
                    };

                    var form = document.createElement('form');
                    form.method = 'POST';
                    form.action = '<?php echo e(route('mintpay.checkout')); ?>';

                    var csrfInput = document.createElement('input');
                    csrfInput.type = 'hidden';
                    csrfInput.name = '_token';
                    csrfInput.value = '<?php echo e(csrf_token()); ?>';
                    form.appendChild(csrfInput);

                    Object.keys(formData).forEach(key => {
                        var input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = key;
                        input.value = formData[key];
                        form.appendChild(input);
                    });

                    document.body.appendChild(form);
                    form.submit();
                } else if (paymentMethod === 'card') {
                    window.location.href = '<?php echo e(route('next.page')); ?>?session_id=' + encodeURIComponent(sessionid);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('An error occurred. Please try again.');
            });
        });

        function showNotification(message) {
            const notification = document.createElement('div');
            notification.textContent = message;
            notification.style.position = 'fixed';
            notification.style.top = '20px';
            notification.style.right = '20px';
            notification.style.padding = '15px 20px';
            notification.style.backgroundColor = '#fff5f5';
            notification.style.color = '#dc3545';
            notification.style.border = '1px solid #fca5a5';
            notification.style.borderRadius = '5px';
            notification.style.boxShadow = '0 4px 8px rgba(0,0,0,0.1)';
            notification.style.zIndex = '1000';
            notification.style.fontFamily = 'Arial, sans-serif';
            notification.style.fontSize = '14px';
            notification.style.transition = 'all 0.3s ease';

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    if (document.body.contains(notification)) {
                        document.body.removeChild(notification);
                    }
                }, 300);
            }, 5000);
        }

        function orderconfirmed() {
            window.location.href = "<?php echo e(route('american.plastic.web.order.confirmed')); ?>";
        }
    </script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('web.home.layout.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/amerbofz/test.americanplastics.lk/resources/views/web/home/checkout/checkout.blade.php ENDPATH**/ ?>