/**
 * AIEO Remote Export — admin AJAX glue.
 *
 * Wires the settings form save, the per-row "Test" button, the
 * "Run export now" button, and the force-reexport panel. Talks to
 * AIEO_DMM_Remote_Export::ajax_* handlers via admin-ajax.php.
 */
(function ($) {
	'use strict';

	if (typeof aieoRemoteExport === 'undefined') {
		return;
	}

	var CFG = aieoRemoteExport;

	function setMsg($el, text, kind) {
		$el.removeClass('success error').text(text || '');
		if (kind) { $el.addClass(kind); }
	}

	function post(action, data, onDone, onFail) {
		var payload = $.extend({}, data || {}, {
			action: action,
			nonce: CFG.nonce
		});
		$.ajax({
			url: CFG.ajaxUrl,
			method: 'POST',
			data: payload,
			dataType: 'json',
			timeout: 60000
		}).done(function (resp) {
			if (resp && resp.success) {
				if (onDone) { onDone(resp.data || {}); }
			} else {
				var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Failed';
				if (onFail) { onFail(msg); }
			}
		}).fail(function (xhr, status, err) {
			if (onFail) { onFail(err || status || 'Network error'); }
		});
	}

	function refreshDashboard(dashboard) {
		if (!dashboard || !dashboard.length) { return; }
		var $body = $('#aieo-rex-dash-body');
		$body.find('tr').each(function () {
			var slug = $(this).data('slug');
			var match = null;
			for (var i = 0; i < dashboard.length; i++) {
				if (dashboard[i].slug === slug) { match = dashboard[i]; break; }
			}
			if (!match) { return; }
			var $tr = $(this);
			$tr.find('td').eq(1).text((match.local_rows || 0).toLocaleString());
			$tr.find('td').eq(2).text((match.last_exported_id || 0).toLocaleString());
			$tr.find('td').eq(3).text(match.last_exported_ts || '—');
			$tr.find('td').eq(4).text(match.lag_seconds === null ? '—' : (match.lag_seconds + 's'));
			var $st = $tr.find('td').eq(5);
			$st.attr('class', 'aieo-rex-status aieo-rex-status-' + (match.last_status || 'none'));
			$st.text(match.last_status || '—');
		});
	}

	$(document).on('submit', '#aieo-remote-export-form', function (e) {
		e.preventDefault();
		var $form = $(this);
		var $msg = $('#aieo-rex-settings-msg');
		setMsg($msg, CFG.i18n.testing);

		var data = {
			connection_id: parseInt($form.find('[name="connection_id"]').val(), 10) || 0,
			frequency:     $form.find('[name="frequency"]').val(),
			batch_size:    parseInt($form.find('[name="batch_size"]').val(), 10) || 1000,
			purge_only_on_success: $form.find('[name="purge_only_on_success"]').is(':checked') ? 1 : 0,
			tables:        []
		};
		$form.find('[name="tables[]"]:checked').each(function () { data.tables.push($(this).val()); });

		post(CFG.actionSave, data,
			function (resp) {
				setMsg($msg, resp.message || CFG.i18n.saved, 'success');
				refreshDashboard(resp.dashboard);
			},
			function (err) { setMsg($msg, CFG.i18n.saveFailed + ' — ' + err, 'error'); }
		);
	});

	$(document).on('click', '.aieo-rex-test', function () {
		var $btn = $(this);
		var slug = $btn.data('slug');
		var $msg = $('#aieo-rex-settings-msg');
		setMsg($msg, CFG.i18n.testing + ' ' + slug);
		$btn.prop('disabled', true);

		post(CFG.actionTest, { table: slug },
			function (resp) {
				$btn.prop('disabled', false);
				setMsg($msg, resp.message || (CFG.i18n.testPass.replace('%d', resp.rows || 0)), 'success');
			},
			function (err) {
				$btn.prop('disabled', false);
				setMsg($msg, CFG.i18n.testFail.replace('%s', err), 'error');
			}
		);
	});

	$(document).on('click', '#aieo-rex-force-run', function () {
		var $btn = $(this);
		var $msg = $('#aieo-rex-settings-msg');
		setMsg($msg, CFG.i18n.running);
		$btn.prop('disabled', true);

		post(CFG.actionForce, {},
			function (resp) {
				$btn.prop('disabled', false);
				setMsg($msg, CFG.i18n.runDone, 'success');
				refreshDashboard(resp.dashboard);
			},
			function (err) {
				$btn.prop('disabled', false);
				setMsg($msg, err, 'error');
			}
		);
	});

	$(document).on('click', '#aieo-rex-reexp-run', function () {
		var $btn = $(this);
		var slug = $('#aieo-rex-reexp-table').val();
		var ts   = $('#aieo-rex-reexp-ts').val();
		var $msg = $('#aieo-rex-reexp-msg');
		if (!slug) { setMsg($msg, CFG.i18n.pickTable, 'error'); return; }
		if (!ts)   { setMsg($msg, 'Provide a timestamp.', 'error'); return; }
		if (!window.confirm(CFG.i18n.confirmRexp)) { return; }

		$btn.prop('disabled', true);
		post(CFG.actionReExp, { table: slug, from_ts: ts },
			function (resp) {
				$btn.prop('disabled', false);
				setMsg($msg, resp.message || CFG.i18n.rexpDone, 'success');
				refreshDashboard(resp.dashboard);
			},
			function (err) {
				$btn.prop('disabled', false);
				setMsg($msg, err, 'error');
			}
		);
	});

})(jQuery);
