(function($) {
	"use strict";

    KirilKirkovWpCreateInvoiceInit();

    function KirilKirkovWpCreateInvoiceInit() {
        const TIMEOUT_ON_SEARCH_INPUTS = 200; // global for all input search by ajax. Wait before stop typing
        
        let main_table_items_wrapper = '#kirilkirkov .create-invoice-page .table-invoice-items .body-items';
        let invoice_wrapper = '#kirilkirkov .create-invoice-page .invoice';
        let opened_item_modal_obj = null;

        // individual client or company
        jQuery('#kirilkirkov .create-invoice-page .is-individual').on('click', function() {
            if(jQuery(this).is(':checked')) {
                jQuery('#kirilkirkov .create-invoice-page .not-individual').addClass('hidden');
                jQuery('#kirilkirkov .create-invoice-page .only-individual').removeClass('hidden');
            } else {
                jQuery('#kirilkirkov .create-invoice-page .not-individual').removeClass('hidden');
                jQuery('#kirilkirkov .create-invoice-page .only-individual').addClass('hidden');
            }
        });

        // Has or Not Maturity Date
        jQuery('#kirilkirkov .create-invoice-page .maturity-date').on('click', function() {
            if(jQuery(this).is(':checked')) {
                jQuery('#kirilkirkov .create-invoice-page .has-maturity-date').removeClass('hidden');
            } else {
                jQuery('#kirilkirkov .create-invoice-page .has-maturity-date').addClass('hidden');
            }
        });

        // Vat registration
        jQuery('#kirilkirkov .create-invoice-page .vat-registration').on('click', function() {
            if(jQuery(this).is(':checked')) {
                jQuery('#kirilkirkov .create-invoice-page .has-vat-number').removeClass('hidden');
            } else {
                jQuery('#kirilkirkov .create-invoice-page .has-vat-number').addClass('hidden');
            }
        });

        // No Vat in total
        jQuery('#kirilkirkov .create-invoice-page .no-vat').on('click', function() {
            if(jQuery(this).is(':checked')) {
                jQuery('#kirilkirkov .create-invoice-page .no-vat-selected').addClass('hidden');
                jQuery('#kirilkirkov .create-invoice-page .no-vat-reason').removeClass('hidden');
            } else {
                jQuery('#kirilkirkov .create-invoice-page .no-vat-selected').removeClass('hidden');
                jQuery('#kirilkirkov .create-invoice-page .no-vat-reason').addClass('hidden');
            }
        });

        // on load if has more than one items
        if(jQuery(main_table_items_wrapper + ' tr').length > 1) {
            jQuery(main_table_items_wrapper + ' .actions').removeClass('hidden');
        }
        // on load - calculate (if is edit)
        doInvoiceCalculation();

        jQuery('#kirilkirkov .create-invoice-page .add-new-item').click(function () {
            let obj_new_item = jQuery(main_table_items_wrapper + ' tr:first').clone(true).insertAfter(main_table_items_wrapper + ' tr:last');
            
            obj_new_item.find('.item_from_list-input').val('0'); // relation to the item if is selected from list
            obj_new_item.find('.items_quantities').val('0'); // quantity
            obj_new_item.find('.item-name').val(''); // clear item name
            jQuery(main_table_items_wrapper + ' .actions').removeClass('hidden'); // show actions for remove and sort
            obj_new_item.find('.quantity-input-field').val('1.00'); // add default quantity
            obj_new_item.find('.price-input-field').val('0.00'); // add default price
            obj_new_item.find('.item-txt-total').text('0.00'); // clear total price for the item
            obj_new_item.find('.item-input-total').val('0.00'); // clear total price for the item input
        });

        /**
         * Attach invoice to user from invoice create page
         */
        jQuery('#kirilkirkov .create-invoice-page .attach-inv-to-user-from-list input').click(function () {
            jQuery('.kkwi-select-customer-modal').removeClass('none');
        });
        jQuery(document).on('click', '#kirilkirkov .kkwi-select-customer-modal .do-close', function() {
			jQuery('.kkwi-select-customer-modal').addClass('none');
		});
        // prevent form submit
        jQuery('#kirilkirkov .kkwi-select-customer-modal form').submit(function(e) {
            e.preventDefault();
        });
        let customers_list;
        let customers_ul = jQuery('#kirilkirkov .kkwi-select-customer-modal .customers-list'); // ul
        let customer_list_search_input = jQuery("#kirilkirkov .kkwi-select-customer-modal form input");
        let delay_timer_customer_search_input;
        customer_list_search_input.on("keyup", function(e) {
        
            clearTimeout(delay_timer_customer_search_input);
            delay_timer_customer_search_input = setTimeout(function() {
                jQuery('#kirilkirkov .kkwi-select-customer-modal .text-error').addClass('hidden');

                let customer_search_value = e.target.value;
                if(customer_search_value === '') {
                    customers_list = [];
                    customers_ul.empty();
                    return;
                }

                customers_list = [];
                customers_ul.empty();
                jQuery.ajax({
                    url: kkpdfim_inv_data.select_customer.ajax_url,
                    type: 'GET',
                    data: {
                        action: kkpdfim_inv_data.select_customer.action_select_customer,
                        search: customer_search_value,
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.data.length < 1) {
                            jQuery('#kirilkirkov .kkwi-select-customer-modal .text-error').removeClass('hidden');
                            return;
                        }
                        customers_list = response.data;
                        jQuery.each(customers_list, function (index, value) {
                            let li = jQuery('<li>').html(kkpdfim_inv_data.select_customer.customer_icon + ' ' + value.user_login + '(' + value.user_email + ')');
                            li.attr('data-id', value.id);
                            customers_ul.append(li);
                        });

                    },
                    error: function(xhr, textStatus, errorThrown) {  
                        // nothing todo
                    }    
                });
            }, TIMEOUT_ON_SEARCH_INPUTS);
        });
        jQuery(document).on('click', '#kirilkirkov .kkwi-select-customer-modal .customers-list li', function() {
			let customer_data_id = jQuery(this).data('id');
			let customer_data_value = jQuery(this).text();

            jQuery('#kirilkirkov .create-invoice-page .hidden-customer_user_id').val(customer_data_id);
            jQuery('#kirilkirkov .create-invoice-page .visible-customer_user_id').val(customer_data_value);

            jQuery('.kkwi-select-customer-modal').addClass('none');
		});
        /**
         * !!! END - Attach invoice to user from invoice create page !!!
         */

        /*
        * Remove Item in create invoice page
        */
        jQuery(main_table_items_wrapper + ' .delete-item').on("click", function () {
            jQuery(this).closest('tr').remove();
            if (jQuery(main_table_items_wrapper + ' tr').length < 2) {
                jQuery(main_table_items_wrapper + ' .actions').addClass('hidden');
            }
            doInvoiceCalculation();
        });

        /*
        * Select main currency for the invoice
        */
        jQuery(invoice_wrapper + ' .select-main-currency').on("change", function () {
            jQuery(invoice_wrapper + ' .currency-text').text(jQuery(this).val());
            jQuery(invoice_wrapper + ' .discount-select-type option:first').val(jQuery(this).val());
            jQuery(invoice_wrapper + ' .discount-select-type option:first').text(jQuery(this).val());
            // Change for Stripe
            setCurrencyForStripe(jQuery(this).val());
        });

        /*
        * On change item quantity, check is not lower than available and do alert (notification) if is..
        */
        jQuery(invoice_wrapper + ' .quantity-input-field').on("change", function () {
            let change_item_value_available_quantity = jQuery(this).parents('tr').find('.item-available-quantity').val();
            if(parseFloat(jQuery(this).val()) !== 'NaN' && parseFloat(change_item_value_available_quantity) !== 'NaN') {
                if(parseFloat(change_item_value_available_quantity) < parseFloat(jQuery(this).val())) {
                    jQuery(this).parents('td').find('.td-col-warning-msg').text(kkpdfim_inv_data.select_item.low_quantity_warning).show().delay(5000).fadeOut();
                }
            }
        });

        /*
        * Sortable items in Create Invoice page
        */
        $('#kirilkirkov .create-invoice-page .table-invoice-items .body-items').sortable({
            handle: '.sort-item'
        });

        /*
        * On change some form this html-s :)
        * Call the calculator
        */
        jQuery(document).on('change', invoice_wrapper + ' .calc-field', function() {
            doInvoiceCalculation();
        });

        // simple nan validation
        jQuery(document).on('change', invoice_wrapper + ' .is-nan-validation', function() {
            if(isNaN(jQuery(this).val())) {
                jQuery(this).css("border-color", kkpdfim_inv_data.create_document.border_color_wrong);
            } else {
                jQuery(this).css("border-color", kkpdfim_inv_data.create_document.border_color_fields);
            }
        });

        // Select Client Modal
		jQuery(document).on('click', '#kirilkirkov .kkwi-show-select-client-modal', function() {
			jQuery('.kkwi-select-client-modal').removeClass('none');
		});
		jQuery(document).on('click', '#kirilkirkov .kkwi-select-client-modal .do-close', function() {
			jQuery('.kkwi-select-client-modal').addClass('none');
		});

        // prevent form submit
        jQuery('#kirilkirkov .kkwi-select-client-modal form').submit(function(e) {
            e.preventDefault();
        });

        let clients_list;
        let clients_ul = jQuery('#kirilkirkov .kkwi-select-client-modal .clients-list'); // ul
        let client_list_search_input = jQuery("#kirilkirkov .kkwi-select-client-modal form input");
        let delay_timer_client_search_input;
        client_list_search_input.on("keyup", function(e) {
        
            clearTimeout(delay_timer_client_search_input);
            delay_timer_client_search_input = setTimeout(function() {
                jQuery('#kirilkirkov .kkwi-select-client-modal .text-error').addClass('hidden');

                let client_search_value = e.target.value;
                if(client_search_value === '') {
                    clients_list = [];
                    clients_ul.empty();
                    return;
                }

                clients_list = [];
                clients_ul.empty();
                jQuery.ajax({
                    url: kkpdfim_inv_data.select_client.ajax_url,
                    type: 'GET',
                    data: {
                        action: kkpdfim_inv_data.select_client.action_select_client,
                        search: client_search_value,
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.data.length < 1) {
                            jQuery('#kirilkirkov .kkwi-select-client-modal .text-error').removeClass('hidden');
                            return;
                        }
                        clients_list = response.data;
                        jQuery.each(clients_list, function (index, value) {
                            let client_type_v = '';
                            if(value.is_individual === 1) {
                                client_type_v = ' - ' + value[client_type_v]
                            }
                            let li = jQuery('<li>').html(kkpdfim_inv_data.select_client.client_icon + ' ' + value.client + client_type_v);
                            li.attr('data-id', value.id);
                            clients_ul.append(li);
                        });

                    },
                    error: function(xhr, textStatus, errorThrown) {  
                        // nothing todo
                    }    
                });
            }, TIMEOUT_ON_SEARCH_INPUTS);
        });

        // Append client to invoice
        jQuery(document).on('click', '#kirilkirkov .kkwi-select-client-modal .clients-list li', function() {
			let client_data_id = jQuery(this).data('id');
            jQuery.each(clients_list, function (index, value) {

                // find client and do append
                if(parseInt(value.id) === parseInt(client_data_id)) {
                    addClientToInvoice(value);
                }
            });
            // close modal
            jQuery('.kkwi-select-client-modal').addClass('none');
            clients_list = []; // clear array
            clients_ul.empty();
            client_list_search_input.val('');
		});
        // End select client

        // Start select client by query param (from clients list "Create Invoice" button)
        let urlParams = new URLSearchParams(window.location.search);
        let kkwp_create_inv_for_client = urlParams.get('kkwp_create_inv_for_client');
        if(kkwp_create_inv_for_client !== null && kkwp_create_inv_for_client !== '') {
            jQuery.ajax({
                url: kkpdfim_inv_data.select_client_by_query_param.ajax_url,
                type: 'GET',
                data: {
                    action: kkpdfim_inv_data.select_client_by_query_param.action_select_client,
                    client_id: kkwp_create_inv_for_client,
                },
                dataType: 'json',
                success: function(response) {
                    if(response.status === 'success') {
                        addClientToInvoice(response.data);
                    }
                },
                error: function(xhr, textStatus, errorThrown) {  
                    // nothing todo
                }    
            });
        }
        // End select client by query param

        function addClientToInvoice(value) {
            jQuery(invoice_wrapper + ' .client-name-input').val(value.client);

            if(parseInt(value.is_individual) === 1) {
                jQuery(invoice_wrapper + ' .is-individual').trigger('click');
            }
            jQuery(invoice_wrapper + ' .client-indentification-number-input').val(value.identification_number);
            if(parseInt(value.has_vat_registration) === 1) {
                jQuery(invoice_wrapper + ' .vat-registration').trigger('click');
            }
            jQuery(invoice_wrapper + ' .client-vat-number-input').val(value.vat_number);
            jQuery(invoice_wrapper + ' .client-accountable-person-input').val(value.accountable_person);
            jQuery(invoice_wrapper + ' .client-city-input').val(value.city);
            jQuery(invoice_wrapper + ' .client-address-input').val(value.address);
            jQuery(invoice_wrapper + ' .client-country-input').val(value.country);
            jQuery(invoice_wrapper + ' .client-beneficiary-input').val(value.beneficiary);
            jQuery(invoice_wrapper + ' .client-zip-code-input').val(value.zip_code);
            jQuery(invoice_wrapper + ' .client-selected-from-list').val(value.id);
        }

        // Select Item Modal
        jQuery(document).on('click', '#kirilkirkov .kkwi-show-select-item-modal', function() {
			jQuery('.kkwi-select-item-modal').removeClass('none');
            opened_item_modal_obj = jQuery(this);
		});
		jQuery(document).on('click', '#kirilkirkov .kkwi-select-item-modal .do-close', function() {
			jQuery('.kkwi-select-item-modal').addClass('none');
            opened_item_modal_obj = null;
		});

        // prevent form submit
         jQuery('#kirilkirkov .kkwi-select-item-modal form').submit(function(e) {
            e.preventDefault();
        });

        let items_list;
        let items_ul = jQuery('#kirilkirkov .kkwi-select-item-modal .items-list'); // ul
        let item_list_search_input = jQuery("#kirilkirkov .kkwi-select-item-modal form input");
        let delay_timer_item_search_input;
        item_list_search_input.on("keyup", function(e) {
            
            clearTimeout(delay_timer_item_search_input);
            delay_timer_item_search_input = setTimeout(function() {
                jQuery('#kirilkirkov .kkwi-select-item-modal .text-error').addClass('hidden');

                let item_search_value = e.target.value;
                if(item_search_value === '') {
                    items_list = [];
                    items_ul.empty();
                    return;
                }

                items_list = [];
                items_ul.empty();
                jQuery.ajax({
                    url: kkpdfim_inv_data.select_item.ajax_url,
                    type: 'GET',
                    data: {
                        action: kkpdfim_inv_data.select_item.action_select_item,
                        search: item_search_value,
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.data.length < 1) {
                            jQuery('#kirilkirkov .kkwi-select-item-modal .text-error').removeClass('hidden');
                            return;
                        }
                        items_list = response.data;
                        jQuery.each(items_list, function (index, value) {
                            let li = jQuery('<li>').html(kkpdfim_inv_data.select_item.item_icon + ' ' + value.name + ' - ' + value.price);
                            li.attr('data-id', value.id);
                            items_ul.append(li);
                        });

                    },
                    error: function(xhr, textStatus, errorThrown) {  
                        // kkpdfim_inv_data.select_client.undefined_error
                    }    
                });
            }, TIMEOUT_ON_SEARCH_INPUTS);
        });
        // append item to invoice
        jQuery(document).on('click', '#kirilkirkov .kkwi-select-item-modal .items-list li', function() {
			let item_data_id = jQuery(this).data('id');
            jQuery.each(items_list, function (index, value) {
                // find item and do append
                if(parseInt(value.id) === parseInt(item_data_id)) {
                    opened_item_modal_obj.parents('tr').find('.item-available-quantity').val(value.available_quantity);
                    opened_item_modal_obj.parents('tr').find('.item-name').val(value.name);
                    opened_item_modal_obj.parents('tr').find('.price-input-field').val(value.price);
                    opened_item_modal_obj.parents('tr').find('.item_from_list-input').val(value.id);
                }
            });
            // close modal
            jQuery('.kkwi-select-item-modal').addClass('none');
            items_list = []; // clear array
            items_ul.empty();
            opened_item_modal_obj = null;
            item_list_search_input.val('');
            doInvoiceCalculation();
		});
        // End select item

        /*
        * Create Invoice Calculator
        * Sum Items prices
        * Sum Vat %/Currency
        * Sum Discount
        * We will use math.js library
        */
        function doInvoiceCalculation() {
            // if is enabled calculator, calculate with math.js, 
            // else do it yourself in input fields
            if (kkpdfim_inv_data.create_document.enabled_calculator !== true) {
                return;
            }

            // Sum item by item
            let items_total = 0.00;
            jQuery(main_table_items_wrapper + ' tr').each(function () {
                let item_quantity = jQuery('.quantity-input-field', this).val();
                let item_price = jQuery('.price-input-field', this).val();

                if(!isNaN(item_quantity) && !isNaN(item_price)) {
                    let item_total = math.multiply(item_quantity, item_price).toFixed(kkpdfim_inv_data.create_document.round_to);
                    jQuery('.item-txt-total', this).text(item_total);
                    jQuery('.item-input-total', this).val(item_total);
                    items_total = math.add(items_total, item_total).toFixed(kkpdfim_inv_data.create_document.round_to);
                }
            });

            // set Invoice amount
            jQuery(invoice_wrapper + ' .items-txt-total').text(items_total);
            jQuery(invoice_wrapper + ' .items-input-total').val(items_total);

            // set Tax base after discount
            let discount_type = jQuery(invoice_wrapper + ' .discount-select-type option:selected').val();
            let discount_value = jQuery(invoice_wrapper + ' .discount-input-field').val();
            let tax_base = 0;
            if(!isNaN(discount_value)) {
                if (discount_type === 'percent') {
                    tax_base = math.subtract(items_total, math.multiply(items_total, math.divide(discount_value, 100))).toFixed(kkpdfim_inv_data.create_document.round_to);
                } else {
                    tax_base = math.subtract(items_total, discount_value).toFixed(kkpdfim_inv_data.create_document.round_to);
                }
            }
            jQuery(invoice_wrapper + ' .tax-txt-base').text(tax_base);
            jQuery(invoice_wrapper + ' .tax-input-base').val(tax_base);

            // Get vat 
            let final_sum = tax_base;
            if (!jQuery(invoice_wrapper + ' .no-vat').is(":checked")) {
                let vat_percent = jQuery(invoice_wrapper + ' .vat-percent-input').val();
                if(!isNaN(vat_percent)) {
                    let vat_sum = math.multiply(math.divide(tax_base, 100), vat_percent).toFixed(kkpdfim_inv_data.create_document.round_to);
                    jQuery(invoice_wrapper + ' .vat-txt-field').text(vat_sum);
                    jQuery(invoice_wrapper + ' .vat-input-field').val(vat_sum);
                    final_sum = math.add(tax_base, vat_sum).toFixed(kkpdfim_inv_data.create_document.round_to);
                }
            }
            
            // Set final sum
            jQuery(invoice_wrapper + ' .total-txt-field').text(final_sum);
            jQuery(invoice_wrapper + ' .total-input-field').val(final_sum);

            // Set Stripe amount if is enabled
            if(jQuery(invoice_wrapper + ' .amount-for-stripe').length > 0) {
                jQuery(invoice_wrapper + ' .amount-for-stripe').val(final_sum);
            }
        }

        function setCurrencyForStripe(currency = null) {
            // Set Stripe currency if selected from settings is in list
            if(jQuery(invoice_wrapper + ' .currency-for-stripe').length > 0) {
                
                let selectedCurrency = kkpdfim_inv_data.create_document.selected_currency.toUpperCase();
                if(currency !== null) {
                    selectedCurrency = currency;
                }

                jQuery(invoice_wrapper + ' .currency-for-stripe option').each(function() {
                    let optionValueSelectedCurrency = jQuery(this).val().toUpperCase();
                    if (optionValueSelectedCurrency === selectedCurrency) {
                        jQuery(this).prop('selected', true);
                    } else {
                        jQuery(this).prop('selected', false);
                    }
                });
            }
        }
        if(!kkpdfim_inv_data.create_document.is_edit_mode) {
            setCurrencyForStripe(); // set on load default currency
        }

        // Toggle show options into create invoice page for WooCommerce
        jQuery(document).on('click', '#kirilkirkov .kkwi-create-inv-toggle-woo-options', function() {
            jQuery('#kirilkirkov .kkwi-create-inv-woo-options').toggleClass('none');
		});

        // When click "GET DATA" from WooCommerce section in create invoice page, get text from input field and add it to the get parameter
        jQuery(document).on('click', '#kirilkirkov .kkwi-create-inv-woo-options-get-data-button', function() {
            let get_data_wc_order_id = jQuery('#kirilkirkov .kkwi-create-inv-woo-options-get-data-input').val();
            let get_data_wc_order_id__attr_name = jQuery('#kirilkirkov .kkwi-create-inv-woo-options-get-data-input').attr('name');
            let get_data_wc_order_nonce = jQuery('#kirilkirkov .kkwi-create-inv-woo-options-nonce-wc-order').val();
            if(get_data_wc_order_id !== '') {
                let current_url = window.location.href;
                let new_url = current_url + '&' + get_data_wc_order_id__attr_name + '=' + get_data_wc_order_id;
                window.location.href = new_url;
            }
        });
    }

})(jQuery);