$(document).ready(function () {
    'use strict';

    /**
     * Generate cart table load/refresh POS page
     */
    let generateCartItems = () => {
        let cart = JSON.parse(localStorage.getItem('cart-data')) || [];
        let totalQty = 0,
            totalPrice = 0,
            grandTotal = 0;
        $('#cart-table > tbody').empty();

        if (cart.length !== 0) {
            $('#pay-now').prop('disabled', false);
            cart.map((x) => {
                let { id, name, price, qty } = x;
                let tr = `
                    <tr data-id="${id}">
                        <td class="align-middle">${name}</td>
                        <td class="text-right align-middle">$ ${price}</td>
                        <td class="text-center">
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <span class="input-group-text decrease">-</span>
                                </div>
                                <input type="text" class="form-control" value="${qty}">
                                <div class="input-group-append">
                                    <span class="input-group-text increase">+</span>
                                </div>
                            </div>
                        </td>
                        <td class="text-right align-middle">$ ${price * qty}</td>
                        <td class="text-center align-middle"><i class="fa fa-trash text-danger delete"></i></td>
                    </tr>
                    `;

                $('#cart-table > tbody:last').append(tr);

                totalQty += qty;
                totalPrice += price * qty;
            });
        } else {
            $('#pay-now').prop('disabled', true);
            let tr = `
                <tr>
                    <td colspan="5" class="text-center align-middle">No Item Added Yet</td>
                </tr>
                `;
            $('#cart-table > tbody:last').append(tr);
        }

        $('#total-qty').val(totalQty);
        let discount = $('#discount').val();
        if (!discount) {
            discount = 0;
        }
        $('#total-amount').val(totalPrice);
        let taxRate = $('#taxRate').val();
        let taxAmount = (totalPrice * taxRate) / 100;
        $('#tax-amount').val(taxAmount);
        grandTotal = totalPrice + taxAmount - discount;
        $('#grand-total').html('$ ' + grandTotal);

        $('#barcode-search').focus();
    };
    generateCartItems();

    /**
     * Calculate discount
     */
    $(document).on('keyup', '#discount', () => {
        generateCartItems();
    });

    /**
     * Add item on cart
     */
    $(document).on('click', '#product-list', (e) => {
        e.preventDefault();

        let cart = JSON.parse(localStorage.getItem('cart-data')) || [];

        if (e.target.matches('.stretched-link')) {
            let id = e.target.closest('li').getAttribute('data-id');
            let name = e.target.closest('li').getAttribute('data-name');
            let price = e.target.closest('li').getAttribute('data-price');

            let search = cart.find((x) => x.id === id);
            if (search === undefined) {
                cart.push({
                    id: id,
                    name: name,
                    qty: 1,
                    price: price,
                });
            } else {
                search.qty += 1;
            }

            localStorage.setItem('cart-data', JSON.stringify(cart));

            generateCartItems();
        }
    });

    /**
     * Increase, Decrease, and Delete item from cart table
     */
    $(document).on('click', '#cart-table', (e) => {
        let cart = JSON.parse(localStorage.getItem('cart-data')) || [];
        let id = e.target.closest('tr').getAttribute('data-id');

        // Increase item qty
        if (e.target.matches('.increase')) {
            let search = cart.find((x) => x.id === id);
            search.qty += 1;
        }

        // Decrease item qty
        if (e.target.matches('.decrease')) {
            let search = cart.find((x) => x.id === id);
            if (search.qty === 1) {
                return;
            } else {
                search.qty -= 1;
            }
        }

        // Delete item
        if (e.target.matches('.delete')) {
            cart = cart.filter((x) => x.id !== id);
        }

        localStorage.setItem('cart-data', JSON.stringify(cart));
        generateCartItems();
    });

    /**
     * Reset whole cart
     */
    $(document).on('click', '#reset', () => {
        localStorage.removeItem('cart-data');
        $('#discount').val('');
        generateCartItems();
    });

    /**
     * Pay Now button
     */
    $(document).on('click', '#pay-now', () => {
        let cart = JSON.parse(localStorage.getItem('cart-data')) || [];
        let totalPrice = 0,
            totalQty = 0,
            grandTotal = 0;
        cart.map((x) => {
            let { id, name, price, qty } = x;
            totalQty += qty;
            totalPrice += qty * price;
        });
        let discount = $('#discount').val();
        if (!discount) {
            discount = 0;
        }
        let taxRate = $('#taxRate').val();
        let taxAmount = (totalPrice * taxRate) / 100;

        grandTotal = totalPrice + taxAmount - discount;

        $('#paying_amount').val(grandTotal);

        $('#tableTotalQty').html('' + totalQty);
        $('#tableTotalAmount').html('' + '$ ' + totalPrice);
        $('#tableTaxAmount').html('' + '$ ' + taxAmount + ' ( ' + taxRate + ' % )');
        $('#tableDiscount').html('' + '$ ' + discount);
        $('#tableGrandTotal').html('' + '$ ' + grandTotal);
    });

    /**
     * Calculate change return amount
     */
    $(document).on('keyup', '#received_amount', () => {
        $('#change_return').val($('#received_amount').val() - $('#paying_amount').val());
    });

    /**
     * Prepare object for sweetalert2
     */
    var Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
    });

    /**
     * Add sales entry
     */
    $(document).on('click', '#submit-pay-now', (e) => {
        let received_amount = $('#received_amount').val();
        let paying_amount = $('#paying_amount').val();
        let customer_id = $('#customer_id').val();
        let tax_percent = $('#taxRate').val();
        let tax_amount = $('#tax-amount').val();
        let discount = $('#discount').val();
        let payment_type = $('#payment_type').val();
        let payment_notes = $('#payment_notes').val();
        let payment_status = $('#payment_status').val();
        let cart = localStorage.getItem('cart-data');

        // if (!sales_no) {
        //     alert('Please give a sales no.');
        //     return false;
        // }
        // if (!item_id) {
        //     alert('Please select an Item.');
        //     return false;
        // }
        // if (!customer_id) {
        //     alert('Please select a Customer.');
        //     return false;
        // }
        // if (!quantity) {
        //     alert('Quantity must be greated than zero.');
        //     return false;
        // }

        $.ajax({
            type: 'POST',
            url: 'pos/sales_complete',
            data: {
                received_amount: received_amount,
                paying_amount: paying_amount,
                customer_id: customer_id,
                tax_percent: tax_percent,
                tax_amount: tax_amount,
                discount: discount,
                payment_type: payment_type,
                payment_notes: payment_notes,
                payment_status: payment_status,
                cart: cart,
            },
            success: function (response) {
                response = JSON.parse(response);

                if (response.type !== 'success') {
                    Toast.fire({
                        icon: 'error',
                        title: 'There is some issues. Please try again later!',
                    });
                } else {
                    Toast.fire({
                        icon: 'success',
                        title: 'Invoice Saved Successfully!',
                    });
                    let url = 'pos/print_invoice/' + response.sales_no;
                    window.open(url, '_blank', 'width=450, height=600');
                    $('#modal-pay-now').modal('hide');
                    localStorage.removeItem('cart-data');
                    $('#discount').val('');
                    generateCartItems();
                }
            },
        });
    });

    /**
     * Show barcode scan product
     */
    $(document).on('keyup', '#barcode-search', (e) => {
        let barcode_search = $('#barcode-search').val();
        let search_result = $('#barcode-search-result');

        if (e.key === 'Enter') {
            $.ajax({
                type: 'POST',
                url: 'pos/search_product/code',
                data: { barcode_search: barcode_search },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.type !== 'success') {
                        search_result.hide();
                    } else {
                        let cart = JSON.parse(localStorage.getItem('cart-data')) || [];

                        let search = cart.find((x) => x.id === response.items.id);
                        if (search === undefined) {
                            cart.push({
                                id: response.items.id,
                                name: response.items.name,
                                qty: 1,
                                price: response.items.min_sale_price,
                            });
                        } else {
                            search.qty += 1;
                        }

                        localStorage.setItem('cart-data', JSON.stringify(cart));

                        generateCartItems();

                        $('#barcode-search').val('');
                    }
                },
            });
        }

        if (barcode_search === '') {
            search_result.hide();
        } else {
            $.ajax({
                type: 'POST',
                url: 'pos/search_product/name',
                data: { barcode_search: barcode_search },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.type !== 'success') {
                        search_result.hide();
                    } else {
                        let li = response.items.map((item) => {
                            return (
                                '<li data-id="' +
                                item.id +
                                '" data-name="' +
                                item.name +
                                '" data-price="' +
                                item.min_sale_price +
                                '">' +
                                item.name +
                                '</li>'
                            );
                        });

                        let result = '<ul>' + li.join('') + '</ul>';
                        search_result.empty();
                        search_result.html(result);
                        search_result.show();
                    }
                },
            });
        }
    });

    /**
     * Select item in barcode-search dropdown
     */
    $(document).on('click', '#barcode-search-result > ul > li', (e) => {
        e.preventDefault();

        let search_result = $('#barcode-search-result');
        let barcode_search = $('#barcode-search');
        let id = e.target.getAttribute('data-id');
        let name = e.target.getAttribute('data-name');
        let price = e.target.getAttribute('data-price');

        let cart = JSON.parse(localStorage.getItem('cart-data')) || [];

        let search = cart.find((x) => x.id === id);
        if (search === undefined) {
            cart.push({
                id: id,
                name: name,
                qty: 1,
                price: price,
            });
        } else {
            search.qty += 1;
        }

        localStorage.setItem('cart-data', JSON.stringify(cart));

        generateCartItems();

        search_result.empty();
        search_result.hide();
        barcode_search.val('');
    });
});
