/**
 * Plugin Name: Oxygen MyData
 * Plugin URI: https://wordpress.org/plugins/oxygen-mydata/
 * Description: A WordPress plugin to connect WooCommerce with Oxygen Pelatologio and MyData
 * Author: Oxygen
 * Author URI: https://pelatologio.gr/
 * Text Domain: oxygen
 * Domain Path: /languages/
 * Version: 2.0.38
 * Requires at least: 5.5
 * Tested up to: 6.8.2
 * WC requires at least: 4.7
 * WC tested up to: 10.0.4
 * License: GPL2
 *
 * Oxygen MyData for WooCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Oxygen myData for WooCommerce. If not, see  https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package Oxygen
 * @version 2.0.38
 * @since  1.0.0
 */

jQuery( document ).ready(
	function ( $ ) {

		$( 'form.checkout' ).on(
			'change',
			'#billing_country',
			function () {
				var selected_country = '';

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

				if ($( 'input#billing_invoice' ).is( ':checked' ) && selected_country !== 'GR') {
					change_price_per_vat();
				} else {
					reverse_prices();
				}
			}
		);

		setTimeout(
			function () {
				$( '#oxygen_payment_enabled' ).fadeOut( 'slow' );
			},
			5000
		);

		if ($( 'input#billing_invoice' ).length > 0 ) {

			var required_html = $( 'abbr.required' ).first();
			var optional_html = $( 'span.optional' ).first();

			// console.log( required_html );

			if ( $( '#billing_vat_field' ).length > 0 ) {
				$( '#billing_vat_field label span' ).remove();
				$( '#billing_vat_field label' ).append( required_html.clone() );
			}
			if ( $( '#billing_job_field' ).length > 0 ) {
				$( '#billing_job_field label span' ).remove();
				$( '#billing_job_field label' ).append( required_html.clone() );
			}
			if ( $( '#billing_tax_office_field' ).length > 0 ) {
				$( '#billing_tax_office_field label span' ).remove();
				$( '#billing_tax_office_field label' ).append( required_html.clone() );
			}

			check_invoice_checkbox();

			$( 'input#billing_invoice' ).on(
				'click',
				function () {
					check_invoice_checkbox();
				}
			);
		}

		function check_invoice_checkbox()
		{

			if ($( 'input#billing_invoice' ).is( ':checked' ) ) {

				$( 'input#billing_invoice' ).attr( "value" , '1' );

				if ($( '#billing_vat_field' ).length > 0) {

					$( '#billing_vat_field' ).show();
				}
				if ($( '#billing_job_field' ).length > 0) {

					$( '#billing_job_field' ).show();
				}
				if ($( '#billing_tax_office_field' ).length > 0) {

					$( '#billing_tax_office_field' ).show();
				}
				if ($( '#billing_company_field' ).length > 0) {
					$( '#billing_company_field label span' ).remove();
					$( '#billing_company_field label' ).append( required_html.clone() );
				}

				setTimeout(
					function () {
						$( '#billing_company_field' ).show();
					},
					100
				);

				change_price_per_vat();

			} else {

				clear_input_fields();
				reverse_prices();

				$( 'input#billing_invoice' ).attr( "value" , '0' );

				if ($( '#billing_vat_field' ).length > 0) {
					$( '#billing_vat_field' ).hide();
				}

				if ($( '#billing_job_field' ).length > 0) {
					$( '#billing_job_field' ).hide();
				}

				if ($( '#billing_tax_office_field' ).length > 0) {
					$( '#billing_tax_office_field' ).hide();
				}

				if ($( '#billing_company_field' ).length > 0) {

					$( '#billing_company_field label abbr' ).remove();
					$( '#billing_company_field label' ).append( optional_html.clone() );
				}
				setTimeout(
					function () {
						$( '#billing_company_field' ).hide();
					},
					100
				);
			}

		}

		function clear_input_fields(){

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

		}

		function change_price_per_vat(){

			console.log( "--------------- in change_price_per_vat " );

			check_vat_ajax().then(
				function (result) {

					console.log( result );

					if (result) {
						console.log( "in 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 {
						console.log( 'Invalid VAT' );
						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  - " );
						console.log( response );
						if (response.success) {
							$( 'body' ).trigger( 'update_checkout' );
						}
					},
					error: function () {
						console.error( 'Failed to update cart prices.' );
					}
				}
			);
		}

		function check_vat_ajax(){

			console.log( 'check_vat_ajax called' );

			return new Promise(
				function (resolve, reject) {

					var vat_number = $( 'input#billing_vat' ).val();

					var selected_country = '';

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

					selected_country = (selected_country === 'GR') ? 'EL' : selected_country;

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

					console.log( requestData );

					if (vat_number === '') {

						$( '#billing_vat' ).addClass( 'error_border' );
						resolve( false );
						return;

					} else {
						$( '#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 );

									}
									resolve( true );

									console.log( "success search in vies " );

								} else {

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

									if (data[0]['message'] === '' && data['code'] !== '') {
										$( '#billing_vat_field' ).after(
											'<div class="woocommerce-notices-wrapper vat_field">\n' +
											'    <ul class="woocommerce-error"><div class="woocommerce-invalid woocommerce-invalid-required-field">Κάτι πήγε στραβά.</div></ul></div>'
										);
									} else if (data['code'] !== '' && data[0]['message'] !== '') {
										$( '#billing_vat_field' ).after(
											'<div class="woocommerce-notices-wrapper vat_field">\n' +
											'    <ul class="woocommerce-error"><div class="woocommerce-invalid woocommerce-invalid-required-field" style="font-size:14px;">' + data[0]['message'] + '</div></ul></div>'
										);
									}

									resolve( false );

								}
							},
							error: function (error) {
								console.log( error );
								$( '.loader_vat' ).removeClass( 'loading_vat' );
								$( '.div_vat' ).show();
								reject( false );

							}
						}
					);
				}
			);

		}

	}
);