<!--=====================================
                      CART SIDEBAR PART START
            =======================================-->
<aside class="cart-sidebar">
    <div class="cart-header">
        <div class="cart-total">
            <i class="fas fa-shopping-basket"></i>
            <span>total item (<span class="cart-item-num">0</span>)</span>
        </div>
        <button class="cart-close"><i class="icofont-close"></i></button>
    </div>
    <ul class="cart-list">
    </ul>
    <div class="cart-footer">
        <button class="coupon-btn">Do you have a coupon code?</button>
        <form class="coupon-form">
            <input type="text" placeholder="Enter your coupon code">
            <button type="submit"><span>apply</span></button>
        </form>
        <a class="cart-checkout-btn" href="{{ route('checkout.index') }}">
            <span class="checkout-label">결제하기</span>
            <span class="checkout-price">0</span>
        </a>
    </div>
</aside>
<!--=====================================
    CART SIDEBAR PART END
=======================================-->

@push('js')
    <script>
        $(document).ready(async function() {
            const response = await call_shop_cart_api()

            if (window.Member) {
                get_cart_item(response.data)
            }
        });

        async function call_shop_cart_api() {
            return await get_api_data('list-type1-page', {
                QueryVars: {
                    QueryName: 'point2u::pro:shop/cart',
                    SubSimpleFilter: "image_type = 'thumb'",
                    IsntPagination: true
                },
                PageVars: {
                    Limit: 10000
                }
            })
        }

        function get_cart_item(d) {
            let html = ''
            let cart_total_prc = 0

            if ( d.Page ) {
                d.Page.forEach(cart => {
                    cart_total_prc += Number(cart['C8'])
                    let route_url = '{{ route('item-details', ':id') }}'
                    route_url = route_url.replace(':id', cart['C10'] ? cart['C10'] : cart['C1'])
                    html += `
                        <li class="cart-item" data-id="${cart['Id']}">
                            <div class="cart-media">
                                <a href="#"><img src="${window.env['MEDIA_URL'] + cart['C2']}" alt="product"></a>
                                <button class="cart-delete" onclick="cart_delete(${cart['Id']})"><i class="far fa-trash-alt"></i></button>
                            </div>
                            <div class="cart-info-group">
                                <div class="cart-info">
                                    <h6><a href="${route_url}">${cart['C4']}</a></h6>
                                    <p>Unit Price - ${format_decimal(cart['C6'], 0)} 원</p>
                                </div>
                                <div class="cart-action-group">
                                    <div class="product-action">
                                        <button type="button" class="action-minus" title="Quantity Minus"><i class="icofont-minus"></i></button>
                                        <input class="action-input" title="Quantity Number" onchange="cart_qty_update(this, ${cart['Id']})"
                                            type="text" name="quantity" min="1" value="${Number(cart['C7'])}">
                                        <button type="button" class="action-plus" title="Quantity Plus"><i class="icofont-plus"></i></button>
                                    </div>
                                    <h6><span class="cart-amt">${format_decimal(cart['C8'], 0)}</span> 원</h6>
                                </div>
                            </div>
                        </li>
                    `
                })
            } else {
                html = '쇼핑카트가 비어있습니다';
            }

            const cart_total_num = d.Page?.length
            $('.cart-sidebar .cart-item-num').text(cart_total_num)
            $('.cart-sidebar .checkout-price').text(format_decimal(cart_total_prc, 0))

            // if (cart_total_num > 0) {
            //     const header_cart_item_num = '.header-cart .cart-item-num'
            //     const mobile_cart_item_num = '.mobile-menu .cart-item-num'
            //
            //     const val = cart_total_num > 9 ? '9+' : cart_total_num
            //     $(header_cart_item_num).text(val)
            //     $(header_cart_item_num).show()
            //
            //     $(mobile_cart_item_num).text(val)
            //     $(mobile_cart_item_num).show()
            // }
            $('.cart-sidebar > .cart-list').html(html)
        }

        async function cart_qty_update($this, cart_id) {
            const qty = Number($($this).val())

            if (qty < 1) {
                $($this).val(1)
                iziToast.info({ title: 'Info', message: '수량 에러' })
                return
            }

            const cart_pick = await get_api_data('cart-pick', {
                Page : [ {  Id: Number(cart_id), MemberBuyerId: window.Member['MemberBuyerId'] } ]
            })
            const cart = cart_pick.data.Page[0]
            const cart_amt = String(Number(cart.CartPrc) * Number($($this).val()));
            const response = await get_api_data('cart-act', {
                Page : [
                    {
                        Id: Number(cart_id),
                        CartPrc: cart.CartPrc,
                        CartQty: $($this).val(),
                        CartAmt: cart_amt,
                    }
                ]
            })

            show_iziToast_msg(response.data.Page, function () {
                location.reload()
                // if (isEmpty(callback)) {
                //     $($this).closest('.cart-item').find('.cart-amt').text(format_decimal(cart_amt, 0))
                //     get_cart_item_prc_total()
                // } else {
                //     callback()
                // }
            })
        }

        function cart_delete(cart_id) {
            iziToast.question({
                timeout: 20000,
                close: false,
                overlay: true,
                displayMode: 'once',
                id: 'question',
                title: $('#comfirm-delete').text(),
                message: $('#can-not-recover-after-delete').text(),
                position: 'center',
                buttons: [
                    [`<button><b>${$('#delete').text()}</b></button>`, async function (instance, toast) {
                        instance.hide({ transitionOut: 'fadeOut' }, toast, 'button');

                        const response = await get_api_data('cart-act', {
                            Page : [ {  Id: Number(`-${cart_id}`) } ]
                        })

                        show_iziToast_msg(response.data.Page, function () {
                            location.reload()
                            // $('.cart-sidebar > .cart-list li').each(function () {
                            //     if (Number(cart_id) === $(this).data('id')) {
                            //         $(this).remove()
                            //     }
                            // });
                            // get_cart_item_prc_total()
                        })
                    }, true],
                    [`<button>${$('#cancel').text()}</button>`, function (instance, toast) {
                        instance.hide({ transitionOut: 'fadeOut' }, toast, 'button');

                    }],
                ],
            });
        }

        async function get_cart_item_prc_total() {
            const response = await call_shop_cart_api()

            let result = 0
            if (response['data']['Page']) {
                result = format_decimal(
                    response['data']['Page'].reduce((total, cart) => { return total += Number(cart['C8']) }, 0)
                    , 0);
            }

            $('.cart-sidebar .checkout-price').text(result)}
    </script>
@endpush
