/**
 * Oxygen Payment Js code for handling modal windows of payment
 *
 * @package Oxygen Payments
 * @version 2.0.38
 * @author Oxygen
 * @since 1.0.0
 *
 * This file handle oxygen payment window
 */


jQuery( document ).ready(

    function ( $ ) {

        $('#billing_vat_field span.woocommerce-input-wrapper').append('<div id="vat-check-button" ><div class="loader_vat"></div><img class="div_vat" src="' + window.location.origin + '/wp-content/plugins/oxygen-mydata/assets/images/icon-search.png" alt="Check VAT"/></div>');

        function check_if_is_europe_country(selected_country){

            var validEUCountries = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK', 'XI'];
            console.log("vies check not ajax , only country check " + selected_country);
            if (validEUCountries.includes(selected_country) || selected_country === 'GR') {
                $('#vat-check-button').show();
            }else{
                $('#vat-check-button').hide();
            }
        }

        /* check vies */
        var selected_country = '';

        if ($('#billing_country').val() !== '') {
            selected_country = $('#billing_country').val();
        } else{
            selected_country = $('#billing_country option:selected').val();
        }

        check_if_is_europe_country(selected_country);

        $( 'input#billing_invoice' ).on('change', function () {
            /* vies check vat */
            if ($('#billing_country').val() !== '') {
                selected_country = $('#billing_country').val();
            } else{
                selected_country = $('#billing_country option:selected').val();
            }
            check_if_is_europe_country(selected_country);
        });

        $( '#billing_country' ).on('change', function () {
            /* vies check vat */
            if ($('#billing_country').val() !== '') {
                selected_country = $('#billing_country').val();
            } else{
                selected_country = $('#billing_country option:selected').val();
            }
            check_if_is_europe_country(selected_country);
        });


        var vat_number = '';

        var height_billing_vat = $('#billing_vat').outerHeight();
        let btn_h = height_billing_vat - 10;
        $('#vat-check-button').css('height',btn_h);
        $('#vat-check-button').css('width',btn_h);

        $('input#billing_vat').on('keyup', function() {
            vat_number = $(this).val();  // Get the current value of the input field
            if(vat_number === ''){
                $('#billing_job').val( '');
                $('#billing_tax_office').val( '');
                $('#billing_company').val( '');
            }
            $('#billing_vat').val(vat_number);
        });

        $(document).on('keyup', '#billing_job, #billing_tax_office, #billing_company', function() {
            if ($(this).val().trim() !== '') {
                $(this).removeClass('error_border');
            }

        });

        function check_vat_ajax(requestData){

            let vat_number = requestData['vat_number'];

            console.log("here you are " + vat_number);
            if (vat_number !== '') {

                $('#billing_vat').removeClass('error_border');
                $('.woocommerce-notices-wrapper.vat_field').remove();


                $.ajax({
                    type: 'POST',
                    url: wc_checkout_params.ajax_url, // WooCommerce's default AJAX URL
                    data: requestData,
                    beforeSend: function() {
                        // setting a timeout
                        $('.loader_vat').addClass('loading_vat');
                        $('.div_vat').hide();
                    },
                    success: function (response) {

                        $('.loader_vat').removeClass('loading_vat');
                        $('.div_vat').show();

                        var data = response['data'];
                        let afm = '';
                        let company_name = '';
                        let doy = '';
                        let job = '';

                        var kad_data = data['firms'];

                        if(data !== undefined && data['code'] === undefined){

                            afm = data['vatNumber'];
                            if(afm !== '') {
                                company_name = data['legalName'];
                                doy = data['taxAuthorityName'];

                                if (kad_data !== undefined && kad_data.length > 0) {
                                    job = kad_data[0]['description'];
                                }

                                $('#billing_job').val(job);
                                $('#billing_tax_office').val(doy);
                                $('#billing_company').val(company_name);

                                const requiredFields = ['#billing_job', '#billing_tax_office', '#billing_company'];
                                const emptyFields = requiredFields.filter(field => $(field).val().trim() === '');

                                // If there are empty fields, show error for each
                                if (emptyFields.length > 0) {
                                    emptyFields.forEach(field => {
                                        showVatError(field, handle_check_vat_action.mandatory_field);
                                    });
                                    reverse_prices();
                                }else {
                                    requiredFields.forEach(field => $(field.id).removeClass('error_border'));
                                }

                                change_price_per_vat();

                            }

                        }else{

                            $('#billing_job').val( '');
                            $('#billing_tax_office').val( '');
                            $('#billing_company').val( '');

                            if(data[0]['message'] === '' && data['code'] !== ''){
                                showVatError('#billing_vat',"Κάτι πήγε στραβά.");
                            }else if(data['code'] !== '' && data[0]['message'] !== ''){
                                showVatError('#billing_vat',data[0]['message']);

                            }

                        }
                    },
                    error: function (error) {
                        console.log(error);
                        $('.loader_vat').removeClass('loading_vat');
                        $('.div_vat').show();
                    }
                });
            }else{
                $('#billing_vat').addClass('error_border');

            }
        }




        $('#vat-check-button').on('click', function () {

            let vat_number = $('#billing_vat').val();

            var requestData = {
                action: 'check_vat_action',
                vat_number: vat_number
            };

            if(selected_country === 'GR'){

                check_vat_ajax(requestData);
                console.log('simple vat');

            }else {

                requestData = {
                    action: 'check_vat_action',
                    vat_number: vat_number,
                    country_code: selected_country
                };
                check_vat_ajax(requestData);
                console.log('not GR country - search in vies');
            }

        });

        function  change_price_per_vat(){

            if($('#billing_country').val() !== 'GR'){

                $.ajax({
                    type: 'POST',
                    url: change_price_per_vat_action.ajax_url,
                    data: {
                        action: 'change_price_per_vat_action',
                        security: change_price_per_vat_action.nonce
                    },
                    success: function (response) {

                        console.log(response);
                        // Update UI: e.g., refresh total field
                        $('.woocommerce-Price-amount').each(function() {
                            $(this).html(response.data.totals.total);
                        });

                        $('.includes_tax .woocommerce-Price-amount').each(function() {
                            $(this).html(response.data.totals.total_tax);
                        });
                        // Or trigger a WooCommerce checkout update:
                        $('body').trigger('update_checkout');
                    },
                    error: function() {
                        console.error('Failed to update cart prices.');
                    }
                });

            }else{
                reverse_prices();
            }

        }

        function reverse_prices(){


            $.ajax({
                type: 'POST',
                url: restore_price_with_tax_action.ajax_url,
                data: {
                    action: 'restore_price_with_tax_action',
                    security: restore_price_with_tax_action.nonce
                },
                success: function (response) {
                    console.log("reverse_prices " + response);
                    if (response.success) {
                        $('body').trigger('update_checkout');
                    }
                },
                error: function () {
                    console.error('Failed to update cart prices.');
                }
            });
        }

        function showVatError(fieldID, message) {
            if(fieldID === '#billing_vat') {

                const errorHtml = `
                <div class="woocommerce-notices-wrapper vat_field" style="margin-top:2px;">
                    <ul class="woocommerce-error" style="margin: 6px 0 0!important;">
                        <div class="woocommerce-invalid woocommerce-invalid-required-field" style="font-size:14px;">
                            ${message}
                        </div>
                    </ul>
                </div>
            `;
                // Show the error message after the specified field
                $(fieldID).after(errorHtml);
            }
            // Add error border to the field
            $(fieldID).addClass('error_border');
        }
    }
);