/**
 * Admin JS.
 *
 * @package YITH\CostOfGoods
 */

jQuery(
	function($) {

		// Code Generator Modal Handling
		$(document).on( 'click', '#yith_cog_apply_cost_settings_button', function(ev){
			ev.preventDefault();

			yith.ui.modal( {
				title  : cog_data.apply_cost_modal.title,
				content: cog_data.apply_cost_modal.content,
				width: 600,
				allowWpMenu: false,
				closeWhenClickingOnOverlay: true,
				allowClosingWithEsc: true,
				classes: {
					title: 'yith-cog-apply-cost-to-orders-modal-title',
					content: 'yith-cog-apply-cost-settings-modal'
				}
			});
		});

		// Product Bulk Action.
		$(
			function() {
				// Watch the bulk actions dropdown, looking for custom bulk actions.
				$( "#bulk-action-selector-top, #bulk-action-selector-bottom" ).on(
					'change',
					function(e){
						var $this = $( this );

						if ( $this.val() == 'set_cost_of_goods' ) {
							$this.after( $( "<input>", { type: 'text', placeholder: "Enter the Cost value", name: "yith_cog_cost" } ).addClass( "custom-bulk-actions-elements" ) );
						} else {
							$( ".custom-bulk-actions-elements" ).remove();
						}
					}
				);
			}
		);

		// Variations Bulk Actions.
		$( 'select#field_to_edit' ).on(
			'variable_cost_of_goods_ajax_data',
			function() {
				return {value: window.prompt( woocommerce_admin_meta_boxes_variations.i18n_enter_a_value )};
			}
		);

		$( document ).on( 'change', '#yith_cog_apply_cost_radio', function(e){
			if ( 'yith_cog_order_id_cost' === $(this).val() ) {
				$('#apply_cost_selected_order_input').fadeIn();
			} else {
				$('#apply_cost_selected_order_input').fadeOut();
			}
		});
	
		//Trigger the cross icon to close the modal when pressing the "close" button.
		$( document ).on( 'click', '#yith-cog-close-modal', function(e){
			closeModal();
		});

		//Trigger the cross icon to close the modal
		const closeModal = function(){
			$( '.yith-plugin-fw__modal__close' ).trigger( 'click' );
		}

		// ajax para el boton apply cost.
		$( document ).on( 'click', '#yith_cog_apply_cost_button', function(e){
			yith_apply_cost_process();
		});
	
			function yith_apply_cost_process( limit,offset ) {
				$ajax_zone    = $( '#yith_cog_apply_cost_button' );
				$done         = $( '.apply-cost-done' );
				$content      = $( '#yith-cog-apply-cost-settings-modal-content' );
				$radio_button = $( '#yith_cog_apply_cost_radio' ).val();


				if (typeof(offset) === 'undefined') {
					offset = 0;
				}
				if (typeof(limit) === 'undefined') {
					limit = 0;
				}

				if (offset == 0) {
					$ajax_zone.block( {message: null, overlayCSS: {background: "#f1f1f1", opacity: .7}} );
				}

				var post_data = {
					'limit': limit,
					'offset': offset,
					action: 'yith_apply_cost_button'
				};
				if ( 'yith_cog_override_cost' === $radio_button ) {

					var post_data = {
						'limit': limit,
						'offset': offset,
						action: 'yith_apply_cost_overriding_button'
					};
				}
				if ( 'yith_cog_order_id_cost' === $radio_button ) {

					var order_id_value = $( '#apply_cost_selected_order_input' ).val();
					var post_data = {
						action: 'yith_apply_cost_selected_order_button',
						order_id: order_id_value
					};
				}


				$.ajax(
					{
						type: "POST",
						data: post_data,
						url: cog_data.ajaxurl,
						success: function (response) {
							console.log( 'Processing, do not cancel' );
							if (response.loop == 1) {
								yith_apply_cost_process( response.limit, response.offset );
							}
							if (response.loop == 0) {
								$ajax_zone.unblock();
								$content.hide();
								$done.show();
								setTimeout( closeModal, 4000);
							}
						},
						error: function (response) {
							console.log( "ERROR" );
							console.log( response );
							$ajax_zone.unblock();
							return false;
						}
					}
				);
			}

		var a = document.createElement( 'a' );
		if (typeof a.download === 'undefined') {
			$( '.export_csv' ).hide();
		}
		// Export.
		$( '.yith_export_csv' ).click(
			function () {

				var export_format = $( this ).data( 'export' );
				var csv_data      = 'data:application/csv;charset=utf-8,';

				if ('table' === export_format) {

					$( this ).offsetParent().find( 'thead tr,tbody tr ' ).each(
						function () {
							$( this ).find( 'th, td' ).each(
								function () {
									var value = $( this ).contents().text();
									value     = value.replace( '[?]', '' ).replace( '#', '' ).replace( 'Show more details', '' ).replace( 'Actions', '' ).replace( 'EditView', '' ).replace(/\"/g,'""');
									csv_data += '"' + value + '"' + ',';
								}
							);
							csv_data  = csv_data.substring( 0, csv_data.length - 1 );
							csv_data += '\n';
						}
					);
				}

				// Set data as href and return.
				$( this ).attr( 'href', encodeURI( csv_data ) );
				return true;
			}
		);
		// Quick edit data cost.
		$( '#the-list' ).on(
			'click',
			'.editinline',
			function(e) {
				var cost, inline_data, post_id;
				post_id     = $( this ).closest( 'tr' ).attr( 'id' );
				post_id     = post_id.replace( 'post-', '' );
				inline_data = $( '#yith_cog_inline_' + post_id );
				cost        = inline_data.find( '.yith_cog_cost' ).text();
				return $( 'input[name="yith_cog_cost"]' ).val( cost );
			}
		);
		// ajax para el boton import cost.
		$( '.import_cost' ).on(
			'click',
			function () {
				yith_import_cost_process();
			}
		);
		function yith_import_cost_process( limit,offset ) {
			$ajax_zone = $( '#ajax_zone_import_cost' );

			if (typeof(offset) === 'undefined') {
				offset = 0;
			}
			if (typeof(limit) === 'undefined') {
				limit = 0;
			}

			var post_data = {
				'limit': limit,
				'offset': offset,
				action: 'yith_import_cost_button'
			};
			if (offset == 0) {
				$ajax_zone.block( {message: null, overlayCSS: {background: "#f1f1f1", opacity: .7}} );
			}
			$.ajax(
				{
					type: "POST",
					data: post_data,
					url: cog_data.ajaxurl,
					success: function (response) {
						console.log( 'Processing, do not cancel' );
						if (response.loop == 1) {
							yith_import_cost_process( response.limit, response.offset );
						}
						if (response.loop == 0) {
							$ajax_zone.unblock();
						}
					},
					error: function (response) {
						console.log( "ERROR" );
						console.log( response );
						$ajax_zone.unblock();
						return false;
					}
				}
			);
		}

		// AJAX call to manage wether to show currency in the table or not.
		$( '#screen-options-apply' ).on(
			'click',
			function () {
				window.onbeforeunload = null;
				yith_cog_show_currency();
			}
		);
		function yith_cog_show_currency() {
			$input = $( '#yith_cog_currency_report' ).is(':checked');

			var post_data = {
				'input_value': $input,
				action:        'yith_cog_show_currency'
			};
			$.ajax(
				{
					type: "POST",
					data: post_data,
					url: cog_data.ajaxurl,
					success: function (response) {
						location.reload();
					},
					error: function (response) {
						console.log( "ERROR" );
					}
				}
			);
		}

		// Reset table button logic (reload just the table content).
		$( '.action.reset-button' ).on(
			'click',
			function () {
				window.onbeforeunload = null;
				location.reload();
			}
		);

		// Avoid the borwser notice when filtering.
		$( '.yith-cog-reports-tablenav #post-query-submit' ).on(
			'click',
			function () {
				window.onbeforeunload = null;
			}
		);

		$(function() {

			var from = $( '#yith-cog-from-datepicker' ).val(),
				to = $( '#yith-cog-to-datepicker' ).val();

			$( 'body.yith-plugins_page_yith_cog_setting .pagination-links a' ).attr('href', function(i, h) {
				return h + "&yith-cog-from-datepicker=" + from + "&yith-cog-to-datepicker=" + to ;
			});
		});

	}
);
