(function ($) {
	'use strict';

	$('a#eurostocks-verify-euro-keys').on("click", function (e) {
		e.preventDefault();
		var EuroStocksFormData = $('#eurostocks-settings').serializeArray();
		EuroStocksFormData.push({ name: "security", value: validajax.security });
		EuroStocksFormData.push({ name: "action", value: "validate_eurostocks_key" });
		$("#eurostocks-feedback").removeClass('red');
		$("#eurostocks-feedback").removeClass('green');
		$.ajax({
			type: "POST",
			url: validajax.admin_url,
			data: EuroStocksFormData,
			success: function (response) {
				if (response && response.success) {
					$("#eurostocks-feedback").text(EUROSTOCKS_TRANSLATIONS.API_CORRECT);
					$("#eurostocks-feedback").addClass('green');
					$("#eurostocks-feedback").removeClass('red');
					return;
				}

				var message = (response && response.data && response.data.message) ? response.data.message : EUROSTOCKS_TRANSLATIONS.API_INCORRECT;
				$("#eurostocks-feedback").text(message);
				$("#eurostocks-feedback").addClass('red');
				$("#eurostocks-feedback").removeClass('green');

			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("#eurostocks-feedback").text(EUROSTOCKS_TRANSLATIONS.API_INCORRECT);
				$("#eurostocks-feedback").addClass('red');
				$("#eurostocks-feedback").removeClass('green');

				console.log("Status: " + textStatus);
				console.log("Error: " + errorThrown);
			}
		});

		return false;

	});

	$('#eurostocks-select-available-model').change(function () {
		var selectedValue = $(this).find(":selected").val();
		var selectedData = $(this).find(":selected").data('type');
		var selectedMake = $('#eurostocks-select-available-make').find(":selected").val();

		$('.shortcode-result').removeClass('eurostocks-none');
		$('.eurostocks-shortcode-code').empty();
		$('.eurostocks-shortcode-code').append('[eurostocks make="' + selectedMake + '" model="' + selectedValue + '" type="' + selectedData + '"]');
	});

	var $iplist = $("#eurostocks-iplist");
	if ($iplist.length) {
		var curValue = $iplist.val();
		var newValue = curValue + '\n';
		$iplist.val(newValue);
	}

	$('.block_ip').on("click", function (e) {
		e.preventDefault();
		var $link = $(this);
		var ip = $link.data("id");
		if (!ip) {
			// Validation happens before disabling the element; no need to restore pointer-events here.
			return;
		}

		$link.css('pointer-events', 'none');

		$.post(validajax.admin_url, {
			action: 'eurostocks_block_ip',
			security: validajax.security,
			ip: ip
		}).done(function (response) {
			if (response && response.success) {
				var $row = $link.closest('tr');
				if ($row.length) {
					$row.fadeOut(200, function () {
						$(this).remove();
					});
				}
			} else {
				var message = (response && response.data && response.data.message) ? response.data.message : 'Unable to block IP.';
				alert(message);
			}
		}).fail(function () {
			alert('Unable to block IP.');
		}).always(function () {
			$link.css('pointer-events', '');
		});
	});

	function updateBulkControls() {
		var $checkboxes = $('.eurostocks-blocked-ip-checkbox');
		var $bulkButton = $('#eurostocks-unblock-selected');

		if ($bulkButton.length) {
			$bulkButton.prop('disabled', $checkboxes.filter(':checked').length === 0);
		}

		var $selectAll = $('#eurostocks-blocked-ip-select-all');
		if ($selectAll.length) {
			if (!$checkboxes.length) {
				$selectAll.prop('checked', false).prop('indeterminate', false);
				return;
			}

			var checkedCount = $checkboxes.filter(':checked').length;
			if (checkedCount === 0) {
				$selectAll.prop('checked', false).prop('indeterminate', false);
			} else if (checkedCount === $checkboxes.length) {
				$selectAll.prop('checked', true).prop('indeterminate', false);
			} else {
				$selectAll.prop('checked', false).prop('indeterminate', true);
			}
		}
	}

	function removeBlockedIpRow(ip) {
		if (!ip) {
			return;
		}

		var found = false;
		$('.eurostocks-blocked-ip-checkbox').filter(function () {
			return $(this).val() === ip;
		}).each(function () {
			found = true;
			var $row = $(this).closest('tr');
			$row.fadeOut(200, function () {
				$(this).remove();
				updateBulkControls();
			});
		});

		if (!found) {
			updateBulkControls();
		}
	}

	$(document).on('change', '.eurostocks-blocked-ip-checkbox', function () {
		updateBulkControls();
	});

	$(document).on('change', '#eurostocks-blocked-ip-select-all', function () {
		var isChecked = $(this).is(':checked');
		$('.eurostocks-blocked-ip-checkbox').prop('checked', isChecked);
		updateBulkControls();
	});

	$(document).on('click', '#eurostocks-unblock-selected', function (e) {
		e.preventDefault();
		var $button = $(this);
		if ($button.prop('disabled')) {
			return;
		}

		var selectedIps = $('.eurostocks-blocked-ip-checkbox:checked').map(function () {
			return $(this).val();
		}).get();

		if (!selectedIps.length) {
			return;
		}

		$button.prop('disabled', true);

		$.post(validajax.admin_url, {
			action: 'eurostocks_remove_ip_block',
			security: validajax.security,
			ips: selectedIps
		}).done(function (response) {
			if (response && response.success) {
				var removedIps = [];
				if (response.data && Array.isArray(response.data.removed)) {
					removedIps = response.data.removed;
				} else if (response.data && response.data.ip) {
					removedIps = [response.data.ip];
				}
				if (!removedIps.length) {
					removedIps = selectedIps;
				}
				removedIps.forEach(removeBlockedIpRow);
			} else {
				var message = (response && response.data && response.data.message) ? response.data.message : 'Unable to remove IP.';
				alert(message);
			}
		}).fail(function () {
			alert('Unable to remove IP.');
		}).always(function () {
			$('#eurostocks-blocked-ip-select-all').prop('checked', false).prop('indeterminate', false);
			updateBulkControls();
			$button.prop('disabled', false);
		});
	});

	$(document).on('click', '.eurostocks-remove-blocked-ip', function (e) {
		e.preventDefault();
		var $button = $(this);
		var ip = $button.data('ip');
		if (!ip) {
			return;
		}

		$button.prop('disabled', true);

		$.post(validajax.admin_url, {
			action: 'eurostocks_remove_ip_block',
			security: validajax.security,
			ip: ip
		}).done(function (response) {
			if (response && response.success) {
				var removedIps = [];
				if (response.data && Array.isArray(response.data.removed)) {
					removedIps = response.data.removed;
				} else if (response.data && response.data.ip) {
					removedIps = [response.data.ip];
				}
				if (!removedIps.length) {
					removedIps = [ip];
				}

				removedIps.forEach(removeBlockedIpRow);
			} else {
				var message = (response && response.data && response.data.message) ? response.data.message : 'Unable to remove IP.';
				alert(message);
			}
		}).fail(function () {
			alert('Unable to remove IP.');
		}).always(function () {
			$button.prop('disabled', false);
			updateBulkControls();
		});
	});

	$(document).on('click', '.eurostocks-remove-verification', function (e) {
		e.preventDefault();
		var $button = $(this);
		var hash = $button.data('hash');
		if (!hash) {
			return;
		}

		$button.prop('disabled', true);

		$.post(validajax.admin_url, {
			action: 'eurostocks_remove_verification_entry',
			security: validajax.security,
			hash: hash,
			ip: $button.data('ip') || '',
			unblock: $button.data('unblock') || 0
		}).done(function (response) {
			if (response && response.success) {
				$button.closest('tr').fadeOut(200, function () {
					$(this).remove();
				});
			} else {
				var message = (response && response.data && response.data.message) ? response.data.message : 'Unable to remove entry.';
				alert(message);
			}
		}).fail(function () {
			alert('Unable to remove entry.');
		}).always(function () {
			$button.prop('disabled', false);
		});
	});

	$(document).ready(function () {
		$('.select_model option').prop('selected', true);
		$('.euroselect').select2();
		updateBulkControls();
	});

	$('.select_makes').change(function () {
		var value = $('.select_makes:checked').val();
		if (value == 1) {
			$('.select_models_rn').removeClass('eurostocks-none');
		} else {
			$('.select_models_rn').addClass('eurostocks-none');
			$('.euroselect option').prop('selected', true);
			$('.euroselect').select2({
				placeholder: "Selectect a make",
			});
		}
	});

	$('a#check-robots').on('click', function (e) {
		e.preventDefault();

		var EuroStocksFormData = $('#eurostocks-settings').serializeArray();
		EuroStocksFormData.push({ name: "security", value: validajax.security });
		EuroStocksFormData.push({ name: "action", value: "check_robots_txt" });
		$("#eurostocks-feedback-robots").removeClass('red');
		$("#eurostocks-feedback-robots").removeClass('green');
		$.ajax({
			type: "POST",
			url: validajax.admin_url,
			data: EuroStocksFormData,
			success: function (data) {

				data = JSON.parse(data);
				console.log(data);
				if (data.disallowed === true) {
					$("#eurostocks-feedback-robots").html(EUROSTOCKS_TRANSLATIONS.ROBOTS_CORRECT + " " + EXTENDED_TRANSLATIONS.ROBOTS_DISCLAIMER);
					$("#eurostocks-feedback-robots").addClass('green');
					$("#eurostocks-feedback-robots").removeClass('red');
				} else {
					$("#eurostocks-feedback-robots").html(EUROSTOCKS_TRANSLATIONS.ROBOTS_INCORRECT + " " + EXTENDED_TRANSLATIONS.ROBOTS_DISCLAIMER);
					$("#eurostocks-feedback-robots").addClass('red');
					$("#eurostocks-feedback-robots").removeClass('green');
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("#eurostocks-feedback-robots").html(EUROSTOCKS_TRANSLATIONS.ROBOTS_ERROR);
				$("#eurostocks-feedback-robots").addClass('red');
				$("#eurostocks-feedback-robots").removeClass('green');
				console.log("Status: " + textStatus);
				console.log("Error: " + errorThrown);
			}
		});
		return false;

	});

	$('.update_modals').on('click', function (e) {

		e.preventDefault();
		var EuroStocksFormData = $('#eurostocks-settings').serializeArray();
		EuroStocksFormData.push({ name: "security", value: validajax.security });
		EuroStocksFormData.push({ name: "action", value: "get_eurostocks_models_ajax" });

		var makes = EuroStocksFormData.filter(function (item) {
			return item.name === 'eurostocks_cars[select_available_make][]';
		});
		EuroStocksFormData = EuroStocksFormData.filter(function (item) {
			return item.name !== 'eurostocks_cars[select_available_make][]';
		});

		makes.forEach(function (item) {
			EuroStocksFormData.push({ name: item.name, value: item.value });
		});
		// remove eurostocks none class for spinner
		$('.eurostocks-spinner').removeClass('eurostocks-none');
		$("#eurostocks-feedback-get-models-ajax").removeClass('green');

		$.ajax({
			type: "POST",
			url: validajax.admin_url,
			data: EuroStocksFormData,
			success: function (data) {
				$("#eurostocks-feedback-get-models-ajax").html(EUROSTOCKS_TRANSLATIONS.GET_MODELS_SUCCESS);
				$("#eurostocks-feedback-get-models-ajax").addClass('green');
				$('#submit').removeAttr('disabled');
				$('.eurostocks-spinner').addClass('eurostocks-none');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("#eurostocks-feedback-get-models-ajax").html(EUROSTOCKS_TRANSLATIONS.GET_MODELS_ERROR);
				$("#eurostocks-feedback-get-models-ajax").removeClass('green');
				console.log("Status: " + textStatus);
				console.log("Error: " + errorThrown);
				$('.eurostocks-spinner').addClass('eurostocks-none');
			}
		});

	})

	$('.modelschange').on('change', function () {
		// disable submit button
		$('#submit').attr('disabled', 'disabled');

	})
	$('.deselect-all').on('click', function (e) {
		e.preventDefault();

		$('.euroselect option').prop('selected', false);
		$('.euroselect').select2();
	});


	$('body').on('click', '.eurostocks-media-upload', function (event) {
		event.preventDefault();

		const button = $(this)
		const imageId = button.next().next().val();
		const customUploader = wp.media({
			title: 'Insert image',
			library: {
				type: 'image'
			},
			button: {
				text: 'Use this image'
			},
			multiple: false
		}).on('select', function () {
			const attachment = customUploader.state().get('selection').first().toJSON();
			button.removeClass('button').html('<img src="' + attachment.url + '">');
			button.next().show();
			button.next().next().val(attachment.id);
		})
		customUploader.on('open', function () {
			if (imageId) {
				const selection = customUploader.state().get('selection')
				attachment = wp.media.attachment(imageId);
				attachment.fetch();
				selection.add(attachment ? [attachment] : []);
			}
		})
		customUploader.open()
	});
	$('body').on('click', '.experts_one_img-media-upload', function (event) {
		event.preventDefault();

		const button = $(this)
		const imageId = button.next().next().val();
		const customUploader = wp.media({
			title: 'Insert image',
			library: {
				type: 'image'
			},
			button: {
				text: 'Use this image'
			},
			multiple: false
		}).on('select', function () {
			const attachment = customUploader.state().get('selection').first().toJSON();
			button.removeClass('button').html('<img src="' + attachment.url + '">');
			button.next().show();
			button.next().next().val(attachment.id);
		})
		customUploader.on('open', function () {
			if (imageId) {
				const selection = customUploader.state().get('selection')
				attachment = wp.media.attachment(imageId);
				attachment.fetch();
				selection.add(attachment ? [attachment] : []);
			}
		})
		customUploader.open()
	});
	$('body').on('click', '.experts_two_img-media-upload', function (event) {
		event.preventDefault();

		const button = $(this)
		const imageId = button.next().next().val();
		const customUploader = wp.media({
			title: 'Insert image',
			library: {
				type: 'image'
			},
			button: {
				text: 'Use this image'
			},
			multiple: false
		}).on('select', function () {
			const attachment = customUploader.state().get('selection').first().toJSON();
			button.removeClass('button').html('<img src="' + attachment.url + '">');
			button.next().show();
			button.next().next().val(attachment.id);
		})
		customUploader.on('open', function () {
			if (imageId) {
				const selection = customUploader.state().get('selection')
				attachment = wp.media.attachment(imageId);
				attachment.fetch();
				selection.add(attachment ? [attachment] : []);
			}
		})
		customUploader.open()
	});


	$('body').on('click', '.top_footer_img-media-upload', function (event) {
		event.preventDefault();

		const button = $(this)
		const imageId = button.next().next().val();
		const customUploader = wp.media({
			title: 'Insert image',
			library: {
				type: 'image'
			},
			button: {
				text: 'Use this image'
			},
			multiple: false
		}).on('select', function () {
			const attachment = customUploader.state().get('selection').first().toJSON();
			button.removeClass('button').html('<img src="' + attachment.url + '">');
			button.next().show();
			button.next().next().val(attachment.id);
		})
		customUploader.on('open', function () {
			if (imageId) {
				const selection = customUploader.state().get('selection')
				attachment = wp.media.attachment(imageId);
				attachment.fetch();
				selection.add(attachment ? [attachment] : []);
			}
		})
		customUploader.open()
	});


	$('body').on('click', '.review_img-media-upload', function (event) {
		event.preventDefault();

		const button = $(this)
		const imageId = button.next().next().val();
		const customUploader = wp.media({
			title: 'Insert image',
			library: {
				type: 'image'
			},
			button: {
				text: 'Use this image'
			},
			multiple: false
		}).on('select', function () {
			const attachment = customUploader.state().get('selection').first().toJSON();
			button.removeClass('button').html('<img src="' + attachment.url + '">');
			button.next().show();
			button.next().next().val(attachment.id);
		})
		customUploader.on('open', function () {
			if (imageId) {
				const selection = customUploader.state().get('selection')
				attachment = wp.media.attachment(imageId);
				attachment.fetch();
				selection.add(attachment ? [attachment] : []);
			}
		})
		customUploader.open()
	});

	$('body').on('click', '.eurostocks-media-remove', function (event) {
		event.preventDefault();
		const button = $(this);
		button.next().val('');
		button.hide().prev().addClass('button').html('Upload image');
	});

	// on select form analytics_period on change go to current page with the selected value
	$('#analytics_period').on('change', function () {
		var selected = $(this).val();
		var currentUrl = window.location.href;
		var url = new URL(currentUrl);
		url.searchParams.set('analytics_period', selected);
		window.location.href = url;
	});

	function applyRulesToRow(row) {
        var hideCheckbox = row.querySelector('.euro-hide');
        var selCheckbox = row.querySelector('.euro-sel');
        var favCheckbox = row.querySelector('.euro-fav');

        // Rule: Uncheck euro-sel and euro-fav when euro-hide is checked
        hideCheckbox.addEventListener('change', function() {
            if (hideCheckbox.checked) {
                selCheckbox.checked = false;
                favCheckbox.checked = false;
            }
        });

		selCheckbox.addEventListener('change', function() {
            if (selCheckbox.checked) {
                hideCheckbox.checked = false;
            }
        });

        favCheckbox.addEventListener('change', function() {
            if (favCheckbox.checked) {
                hideCheckbox.checked = false;
				countChecked();
            }
        });
    }

	function countChecked() {
		var favCheckboxes = document.querySelectorAll('.euro-fav');
		var checkedCount = 0;
		favCheckboxes.forEach(function(checkbox) {
			if (checkbox.checked) {
				checkedCount++;
			}
		}
		);
		if (checkedCount >= 10) {
			favCheckboxes.forEach(function(checkbox) {
				if (!checkbox.checked) {
					checkbox.disabled = true;
				}
			}
			);
		}
		else {
			favCheckboxes.forEach(function(checkbox) {
				checkbox.disabled = false;
			}
			);
		}
	}

    var rows = document.querySelectorAll('#eurostocks-options-table tbody tr');

    rows.forEach(function(row) {
        applyRulesToRow(row);
    });

	countChecked();


	$('#eurostocks-export-options-button').on('click', function (e) {
		e.preventDefault();
		var EuroStocksFormData = $('#eurostocks-settings').serializeArray();
		EuroStocksFormData.push({ name: "security", value: validajax.security });
		EuroStocksFormData.push({ name: "action", value: "eurostocks_export_options_data" });
		
		$.ajax({
			type: "POST",
			url: validajax.admin_url,
			data: EuroStocksFormData,
			success: function (data) {
				var blob = new Blob([data], { type: 'application/json' });
                var url = window.URL.createObjectURL(blob);
                var a = document.createElement('a');
                a.href = url;
                a.download = 'eurostocks_options.json';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log("Status: " + textStatus);
				console.log("Error: " + errorThrown);
			}
		});
	});

	$('#eurostocks-import-options-button').on('click', function (e) {
		e.preventDefault();
		
		//var EuroStocksFormData = $('#eurostocks-settings').serializeArray();
		var form = $('#eurostocks-settings')[0];
    	var formData = new FormData(form);

		formData.append('action', 'eurostocks_import_options_data');
    	formData.append('security', validajax.security);
		for (var pair of formData.entries()) {
			console.log(pair[0]+ ': ' + pair[1]);
		}
		$.ajax({
			type: "POST",
			url: validajax.admin_url,
			data: formData,
			processData: false,
			contentType: false,
			success: function (data) {
				$('#eurostocks-import-export-notice')
                    .removeClass('notice-error')
                    .addClass('notice-success')
                    .html('Settings imported successfully!')
                    .show();
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log("Status: " + textStatus);
				console.log("Error: " + errorThrown);
				$('#eurostocks-import-export-notice')
                    .removeClass('notice-success')
                    .addClass('notice-error')
                    .html('Error importing settings')
                    .show();
			}
		});
	});

	$('#sortable-ctas').sortable({
		
		update: function(event, ui) {
			console.log('Sortable updated');
			let order = $(this).children().map(function() {
				return $(this).data('key');
			}).get();
			console.log('New order:', order);
			$('#cta_order_input').val(order.join(','));
		}
	});

	var $apiStatsContainer = $('.eurostocks-api-statistics');
	if ($apiStatsContainer.length) {
		var defaultPeriod = $apiStatsContainer.data('default-period') || 'current_month';
		var hasCredentials = String($apiStatsContainer.data('has-credentials')) === '1';
		var l10n = window.eurostocksAdminL10n || {};
		var apiL10n = l10n.apiStats || {};
		var locale = l10n.locale || 'en-US';

		var $form = $('#eurostocks-api-stats-form');
		var $periodRadios = $form.find('input[name="eurostocks_api_period"]');
		var $customRange = $('.eurostocks-custom-range');
		var $fromInput = $('#eurostocks-from-date');
		var $toInput = $('#eurostocks-to-date');
		var $noticeArea = $('.eurostocks-stats-notices');
		var $loadingNotice = $('.eurostocks-stats-loading');
		var $fetchButton = $('#eurostocks-fetch-stats');
		var $resetButton = $('#eurostocks-reset-stats');
		var $cardValues = $('.eurostocks-stat-card-value');
		var $rangeLabel = $('#eurostocks-active-range');

		function renderNotice(type, message) {
			$noticeArea.empty();
			if (!message) {
				return;
			}

			var cssClass = 'notice';
			if (type === 'success') {
				cssClass += ' notice-success';
			} else if (type === 'info') {
				cssClass += ' notice-info';
			} else {
				cssClass += ' notice-error';
			}

			var $notice = $('<div>').addClass(cssClass).append($('<p>').text(message));
			$noticeArea.append($notice);
		}

		function toggleCustomRange() {
			var period = $periodRadios.filter(':checked').val();
			var isCustom = period === 'custom';
			$customRange.toggleClass('eurostocks-hidden', !isCustom);
			$fromInput.prop('disabled', !isCustom);
			$toInput.prop('disabled', !isCustom);
		}

		function setLoading(isLoading) {
			if (isLoading) {
				$loadingNotice.removeClass('eurostocks-hidden');
				$fetchButton.prop('disabled', true);
				$resetButton.prop('disabled', true);
				$cardValues.addClass('is-loading').text('—');
			} else {
				$loadingNotice.addClass('eurostocks-hidden');
				$fetchButton.prop('disabled', false);
				$resetButton.prop('disabled', false);
				$cardValues.removeClass('is-loading');
			}
		}

		function formatNumber(value) {
			var numberValue = parseInt(value, 10);
			if (isNaN(numberValue)) {
				return '0';
			}
			try {
				return numberValue.toLocaleString(locale || undefined);
			} catch (e) {
				return numberValue.toLocaleString();
			}
		}

		function renderTotals(totals) {
			$cardValues.each(function () {
				var $field = $(this);
				var key = $field.data('field');
				var value = (totals && typeof totals[key] !== 'undefined') ? totals[key] : null;
				$field.text(value === null ? '—' : formatNumber(value));
			});
		}

		function updateRangeLabel(from, to) {
			if (!$rangeLabel.length) {
				return;
			}

			if (from && to) {
				var prefix = apiL10n.rangeLabelPrefix || 'Current period:';
				$rangeLabel.text(prefix + ' ' + from + ' to ' + to);
			} else {
				$rangeLabel.text('');
			}
		}

		function validateCustomRange(period) {
			if (period !== 'custom') {
				return { valid: true, from: '', to: '' };
			}

			var fromVal = $fromInput.val();
			var toVal = $toInput.val();
			var datePattern = /^\d{4}-\d{2}-\d{2}$/;

			if (!fromVal || !toVal) {
				renderNotice('error', apiL10n.fillBothDates || 'Please fill in both From and To.');
				return { valid: false };
			}

			if (!datePattern.test(fromVal) || !datePattern.test(toVal)) {
				renderNotice('error', apiL10n.invalidDateFormat || 'Use format yyyy-mm-dd.');
				return { valid: false };
			}

			return { valid: true, from: fromVal, to: toVal };
		}

		function fetchStatistics(event) {
			if (event) {
				event.preventDefault();
			}

			if (!hasCredentials) {
				renderNotice('error', apiL10n.missingCredentials || 'Please enter valid API credentials first.');
				return;
			}

			var period = $periodRadios.filter(':checked').val() || defaultPeriod;
			var customRange = validateCustomRange(period);
			if (!customRange.valid) {
				return;
			}

			setLoading(true);
			renderNotice('', '');

			var payload = {
				action: 'eurostocks_fetch_api_statistics',
				security: validajax.security,
				period: period,
				fromDate: customRange.from || '',
				toDate: customRange.to || ''
			};

			$.post(validajax.admin_url, payload)
				.done(function (response) {
					if (response && response.success && response.data) {
						renderTotals(response.data.totals);
						updateRangeLabel(response.data.fromDate, response.data.toDate);
						if (response.data.fromDate) {
							$fromInput.val(response.data.fromDate);
						}
						if (response.data.toDate) {
							$toInput.val(response.data.toDate);
						}
					} else {
						var message = (response && response.data && response.data.message) ? response.data.message : (apiL10n.fetchError || 'Could not fetch statistics.');
						renderNotice('error', message);
						renderTotals({});
					}
				})
				.fail(function () {
					renderNotice('error', apiL10n.fetchError || 'Could not fetch statistics.');
					renderTotals({});
				})
				.always(function () {
					setLoading(false);
				});
		}

		function resetStatistics(event) {
			if (event) {
				event.preventDefault();
			}

			$periodRadios.filter('[value="' + defaultPeriod + '"]').prop('checked', true);
			$fromInput.val('');
			$toInput.val('');
			toggleCustomRange();
			fetchStatistics();
		}

		$periodRadios.on('change', function () {
			toggleCustomRange();
		});

		$fetchButton.on('click', fetchStatistics);
		$resetButton.on('click', resetStatistics);

		toggleCustomRange();

		if (hasCredentials) {
			fetchStatistics();
		}
	}

})(jQuery);
