/**
 * ArkHost Security Pack - Admin Scripts
 *
 * All admin page AJAX handlers. Dynamic values are passed via arkspAdmin object
 * (wp_localize_script).
 */

/* global jQuery, ajaxurl, arkspAdmin */

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

	// -------------------------------------------------------------------------
	// Status tab: Delete WP info files (readme.html, license.txt).
	// -------------------------------------------------------------------------
	$('.arksp-delete-file').on('click', function() {
		var $btn = $(this);
		var file = $btn.data('file');

		if (!confirm(arkspAdmin.strings.confirmDeleteFile)) {
			return;
		}

		$btn.prop('disabled', true).text(arkspAdmin.strings.deleting);

		$.post(ajaxurl, {
			action: 'arksp_delete_wp_file',
			file: file,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				$btn.closest('tr').fadeOut();
			} else {
				alert(response.data.message || arkspAdmin.strings.failedDeleteFile);
				$btn.prop('disabled', false).text(arkspAdmin.strings.deleteBtn);
			}
		});
	});

	// -------------------------------------------------------------------------
	// Login tab: Test email.
	// -------------------------------------------------------------------------
	$('#arksp-test-email').on('click', function() {
		var $btn = $(this);
		var $result = $('#arksp-test-email-result');
		var email = $('#arksp-alert-email').val() || arkspAdmin.adminEmail;

		$btn.prop('disabled', true);
		$result.html('<span style="color: #666;">' + arkspAdmin.strings.sending + '</span>');

		$.post(ajaxurl, {
			action: 'arksp_test_email',
			email: email,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			$btn.prop('disabled', false);
			if (response.success) {
				$result.html('<span style="color: #46b450;">' + arkspAdmin.strings.testEmailSent + '</span>');
			} else {
				$result.html('<span style="color: #dc3232;">' + response.data.message + '</span>');
			}
		}).fail(function() {
			$btn.prop('disabled', false);
			$result.html('<span style="color: #dc3232;">' + arkspAdmin.strings.requestFailed + '</span>');
		});
	});

	// -------------------------------------------------------------------------
	// IP Control tab: Unblock IP and download geo DB.
	// -------------------------------------------------------------------------
	$('.arksp-unblock-ip').on('click', function() {
		var ip = $(this).data('ip');
		var $row = $(this).closest('tr');

		$.post(ajaxurl, {
			action: 'arksp_unblock_ip',
			ip: ip,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				$row.fadeOut();
			}
		});
	});

	$('#arksp-download-geo-db').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true).text(arkspAdmin.strings.downloading);

		$.post(ajaxurl, {
			action: 'arksp_download_geo_db',
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				location.reload();
			} else {
				alert(response.data.message);
				$btn.prop('disabled', false).text(arkspAdmin.strings.downloadGeoDb);
			}
		});
	});

	// -------------------------------------------------------------------------
	// Headers tab: Reset headers and load example CSP.
	// -------------------------------------------------------------------------
	$('#arksp-reset-headers').on('click', function() {
		if (confirm(arkspAdmin.strings.confirmResetHeaders)) {
			$('[id^="header-"]').each(function() {
				var defaultVal = $(this).data('default');
				$(this).val(defaultVal);
			});
		}
	});

	$('#arksp-load-example-csp').on('click', function() {
		var exampleCSP = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self';";
		$('#header-content_security_policy').val(exampleCSP);
	});

	// -------------------------------------------------------------------------
	// Scanner tab: File integrity scan, malware scan, quarantine.
	// -------------------------------------------------------------------------
	$('#arksp-run-file-scan').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true).text(arkspAdmin.strings.scanning);

		$.post(ajaxurl, {
			action: 'arksp_run_file_scan',
			_ajax_nonce: arkspAdmin.nonce
		}, function() {
			location.reload();
		});
	});

	$('#arksp-reset-baseline, #arksp-dismiss-file-changes').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true);

		$.post(ajaxurl, {
			action: 'arksp_reset_file_baseline',
			_ajax_nonce: arkspAdmin.nonce
		}, function() {
			location.reload();
		});
	});

	$('#arksp-run-malware-scan').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true);
		$('#arksp-scan-status').text(arkspAdmin.strings.scanningMalware);

		$.post(ajaxurl, {
			action: 'arksp_run_malware_scan',
			_ajax_nonce: arkspAdmin.nonce
		}, function() {
			location.reload();
		});
	});

	$('#arksp-clear-malware-results').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true);

		$.post(ajaxurl, {
			action: 'arksp_clear_malware_results',
			_ajax_nonce: arkspAdmin.nonce
		}, function() {
			location.reload();
		});
	});

	// Quarantine file.
	$('.arksp-quarantine-file').on('click', function() {
		var $btn = $(this);
		var filePath = $btn.data('file');

		if (!confirm(arkspAdmin.strings.confirmQuarantine)) {
			return;
		}

		$btn.prop('disabled', true).text(arkspAdmin.strings.moving);

		$.post(ajaxurl, {
			action: 'arksp_quarantine_file',
			file_path: filePath,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				$btn.closest('tr').fadeOut(function() {
					$(this).remove();
					location.reload();
				});
			} else {
				alert(response.data.message || arkspAdmin.strings.failedQuarantine);
				$btn.prop('disabled', false).text(arkspAdmin.strings.quarantineBtn);
			}
		});
	});

	// Restore file from quarantine.
	$('.arksp-restore-file').on('click', function() {
		var $btn = $(this);
		var name = $btn.data('name');

		if (!confirm(arkspAdmin.strings.confirmRestore)) {
			return;
		}

		$btn.prop('disabled', true).text(arkspAdmin.strings.restoring);

		$.post(ajaxurl, {
			action: 'arksp_restore_file',
			quarantine_name: name,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				location.reload();
			} else {
				alert(response.data.message || arkspAdmin.strings.failedRestore);
				$btn.prop('disabled', false).text(arkspAdmin.strings.restoreBtn);
			}
		});
	});

	// Delete quarantined file permanently.
	$('.arksp-delete-quarantined').on('click', function() {
		var $btn = $(this);
		var name = $btn.data('name');

		if (!confirm(arkspAdmin.strings.confirmDeletePermanent)) {
			return;
		}

		$btn.prop('disabled', true).text(arkspAdmin.strings.deleting);

		$.post(ajaxurl, {
			action: 'arksp_delete_quarantined',
			quarantine_name: name,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				$btn.closest('tr').fadeOut(function() {
					$(this).remove();
				});
			} else {
				alert(response.data.message || arkspAdmin.strings.failedDeleteFile);
				$btn.prop('disabled', false).text(arkspAdmin.strings.deleteBtn);
			}
		});
	});

	// -------------------------------------------------------------------------
	// Logs tab: Filter, export, clear.
	// -------------------------------------------------------------------------
	$('#arksp-filter-logs').on('click', function() {
		var type = $('#arksp-filter-type').val();
		var url = new URL(window.location.href);
		if (type) {
			url.searchParams.set('event_type', type);
		} else {
			url.searchParams.delete('event_type');
		}
		url.searchParams.delete('paged');
		window.location.href = url.toString();
	});

	$('#arksp-export-logs').on('click', function() {
		$.post(ajaxurl, {
			action: 'arksp_export_logs',
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				var blob = new Blob([response.data.csv], {type: 'text/csv'});
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = 'arkhost-security-pack-logs-' + new Date().toISOString().split('T')[0] + '.csv';
				a.click();
				URL.revokeObjectURL(url);
			}
		});
	});

	$('#arksp-clear-logs').on('click', function() {
		if (confirm(arkspAdmin.strings.confirmClearLogs)) {
			$.post(ajaxurl, {
				action: 'arksp_clear_logs',
				_ajax_nonce: arkspAdmin.nonce
			}, function(response) {
				if (response.success) {
					location.reload();
				}
			});
		}
	});

	// -------------------------------------------------------------------------
	// Tools tab: Whitelist IP, clear lockouts, force logout, export/import/reset.
	// -------------------------------------------------------------------------
	$('#arksp-whitelist-my-ip').on('click', function() {
		var $btn = $(this);
		$btn.prop('disabled', true);
		$.post(ajaxurl, {
			action: 'arksp_whitelist_ip',
			ip: arkspAdmin.currentIp,
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				$('#arksp-whitelist-status').text(arkspAdmin.strings.ipWhitelisted).css('color', 'green');
				setTimeout(function() { location.reload(); }, 1000);
			} else {
				$('#arksp-whitelist-status').text(response.data.message || arkspAdmin.strings.error).css('color', 'red');
				$btn.prop('disabled', false);
			}
		});
	});

	$('#arksp-clear-lockouts').on('click', function() {
		if (confirm(arkspAdmin.strings.confirmClearLockouts)) {
			$.post(ajaxurl, {
				action: 'arksp_clear_lockouts',
				_ajax_nonce: arkspAdmin.nonce
			}, function(response) {
				if (response.success) {
					$('#arksp-lockout-status').text(arkspAdmin.strings.lockoutsCleared).css('color', 'green');
				}
			});
		}
	});

	$('#arksp-force-logout-all').on('click', function() {
		if (confirm(arkspAdmin.strings.confirmForceLogout)) {
			$.post(ajaxurl, {
				action: 'arksp_force_logout_all',
				_ajax_nonce: arkspAdmin.nonce
			}, function(response) {
				if (response.success) {
					$('#arksp-logout-status').text(arkspAdmin.strings.sessionsTerminated).css('color', 'green');
					setTimeout(function() {
						window.location.href = arkspAdmin.loginUrl;
					}, 1500);
				}
			});
		}
	});

	$('#arksp-export-settings').on('click', function() {
		$.post(ajaxurl, {
			action: 'arksp_export_settings',
			_ajax_nonce: arkspAdmin.nonce
		}, function(response) {
			if (response.success) {
				var blob = new Blob([JSON.stringify(response.data, null, 2)], {type: 'application/json'});
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = 'arkhost-security-pack-settings.json';
				a.click();
				URL.revokeObjectURL(url);
			}
		});
	});

	$('#arksp-import-settings').on('click', function() {
		var file = $('#arksp-import-file')[0].files[0];
		if (!file) {
			alert(arkspAdmin.strings.selectFileToImport);
			return;
		}

		var reader = new FileReader();
		reader.onload = function(e) {
			$.post(ajaxurl, {
				action: 'arksp_import_settings',
				settings: e.target.result,
				_ajax_nonce: arkspAdmin.nonce
			}, function(response) {
				if (response.success) {
					$('#arksp-import-status').text(arkspAdmin.strings.settingsImported).css('color', 'green');
					setTimeout(function() { location.reload(); }, 1000);
				} else {
					$('#arksp-import-status').text(response.data.message).css('color', 'red');
				}
			});
		};
		reader.readAsText(file);
	});

	$('#arksp-reset-settings').on('click', function() {
		if (confirm(arkspAdmin.strings.confirmResetSettings)) {
			$.post(ajaxurl, {
				action: 'arksp_reset_settings',
				_ajax_nonce: arkspAdmin.nonce
			}, function(response) {
				if (response.success) {
					location.reload();
				}
			});
		}
	});
});
