/**
 * Ghost Purge — frontend AJAX batch processor.
 *
 * Wires:
 *   - Preview button : dry-run, lists candidate users
 *   - Purge button   : init job, then loop process_batch until done
 *
 * @package Tshepho\Ops
 */

( function ( $ ) {
	'use strict';

	if ( typeof window.PlatformHelmGP === 'undefined' ) {
		return;
	}

	var cfg          = window.PlatformHelmGP;
	var $roleField   = $( '#platform-helm-gp-role' );
	var $monthsField = $( '#platform-helm-gp-months' );
	var $reassignFld = $( '#platform-helm-gp-reassign' );

	function setProgress( pct, text ) {
		$( '#platform-helm-gp-progress-wrap' ).show();
		$( '#platform-helm-gp-progress-bar' ).css( 'width', Math.min( 100, Math.max( 0, pct ) ) + '%' );
		$( '#platform-helm-gp-progress-text' ).text( text || '' );
	}

	function escapeHtml( str ) {
		if ( null === str || 'undefined' === typeof str ) {
			return '';
		}
		return String( str )
			.replace( /&/g, '&amp;' )
			.replace( /</g, '&lt;' )
			.replace( />/g, '&gt;' )
			.replace( /"/g, '&quot;' )
			.replace( /'/g, '&#039;' );
	}

	function formatString( template, args ) {
		var idx = 0;
		return template.replace( /%(\d+\$)?[ds]/g, function ( match, posToken ) {
			if ( posToken ) {
				var pos = parseInt( posToken, 10 ) - 1;
				return 'undefined' !== typeof args[ pos ] ? args[ pos ] : match;
			}
			var val = args[ idx ];
			idx += 1;
			return 'undefined' !== typeof val ? val : match;
		} );
	}

	/* ----------------------------------------------------------------- */
	/* Preview                                                            */
	/* ----------------------------------------------------------------- */

	$( '#platform-helm-gp-preview-btn' ).on( 'click', function () {
		var $btn     = $( this );
		var $results = $( '#platform-helm-gp-preview-results' );
		$btn.prop( 'disabled', true );
		$results.html( '<p><em>' + escapeHtml( cfg.i18n.previewing ) + '</em></p>' );

		$.post( cfg.ajaxUrl, {
			action: 'tshephos_ops_gp_dry_run',
			nonce:  cfg.nonce,
			role:   $roleField.val(),
			months: $monthsField.val()
		} ).done( function ( response ) {
			if ( ! response || ! response.success ) {
				var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
				$results.html( '<div class="notice notice-error"><p>' + escapeHtml( msg ) + '</p></div>' );
				return;
			}
			renderPreview( $results, response.data );
		} ).fail( function () {
			$results.html( '<div class="notice notice-error"><p>' + escapeHtml( cfg.i18n.networkError ) + '</p></div>' );
		} ).always( function () {
			$btn.prop( 'disabled', false );
		} );
	} );

	function renderPreview( $target, data ) {
		var total   = data.total || 0;
		var preview = data.preview || [];

		if ( 0 === total ) {
			$target.html( '<div class="notice notice-warning"><p>' + escapeHtml( cfg.i18n.noUsersFound ) + '</p></div>' );
			return;
		}

		var html = '<h3>' + escapeHtml( formatString( cfg.i18n.previewCount, [ total ] ) ) + '</h3>';
		if ( data.capped ) {
			html += '<p class="description">' + escapeHtml( cfg.i18n.previewCapNote ) + '</p>';
		}
		html += '<table class="widefat striped">';
		html += '<thead><tr>';
		html += '<th>ID</th><th>Login</th><th>Email</th><th>Display name</th><th>Registered</th><th>Last login</th>';
		html += '</tr></thead><tbody>';

		preview.forEach( function ( u ) {
			html += '<tr>';
			html += '<td>' + escapeHtml( u.id ) + '</td>';
			html += '<td><code>' + escapeHtml( u.login ) + '</code></td>';
			html += '<td>' + escapeHtml( u.email ) + '</td>';
			html += '<td>' + escapeHtml( u.display_name ) + '</td>';
			html += '<td>' + escapeHtml( u.user_registered ) + '</td>';
			html += '<td>' + escapeHtml( u.last_login || '—' ) + '</td>';
			html += '</tr>';
		} );
		html += '</tbody></table>';

		$target.html( html );
	}

	/* ----------------------------------------------------------------- */
	/* Purge — batched delete                                             */
	/* ----------------------------------------------------------------- */

	$( '#platform-helm-gp-purge-btn' ).on( 'click', function () {
		if ( ! window.confirm( cfg.i18n.confirmPurge ) ) {
			return;
		}
		var $btn = $( this );
		$btn.prop( 'disabled', true ).text( cfg.i18n.starting );
		setProgress( 0, cfg.i18n.starting );
		$( '#platform-helm-gp-purge-results' ).empty();

		$.post( cfg.ajaxUrl, {
			action:   'tshephos_ops_gp_init',
			nonce:    cfg.nonce,
			role:     $roleField.val(),
			months:   $monthsField.val(),
			reassign: $reassignFld.val()
		} ).done( function ( response ) {
			if ( ! response || ! response.success ) {
				var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
				$( '#platform-helm-gp-purge-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( msg ) + '</p></div>' );
				$btn.prop( 'disabled', false ).text( 'Purge' );
				setProgress( 0, '' );
				$( '#platform-helm-gp-progress-wrap' ).hide();
				return;
			}
			runBatchLoop( response.data, $btn );
		} ).fail( function () {
			$( '#platform-helm-gp-purge-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( cfg.i18n.networkError ) + '</p></div>' );
			$btn.prop( 'disabled', false ).text( 'Purge' );
		} );
	} );

	function runBatchLoop( init, $btn ) {
		var jobId     = init.job_id;
		var total     = init.total_users;
		var batchSize = init.batch_size || cfg.batchSize || 25;

		if ( 0 === total ) {
			setProgress( 100, formatString( cfg.i18n.doneSummary, [ 0, 0 ] ) );
			$btn.prop( 'disabled', false ).text( 'Purge' );
			$( '#platform-helm-gp-purge-results' ).html(
				'<div class="notice notice-warning"><p>' + escapeHtml( cfg.i18n.noUsersFound ) + '</p></div>'
			);
			return;
		}

		function nextBatch() {
			$.post( cfg.ajaxUrl, {
				action: 'tshephos_ops_gp_batch',
				nonce:  cfg.nonce,
				job_id: jobId
			} ).done( function ( response ) {
				if ( ! response || ! response.success ) {
					var msg = ( response && response.data && response.data.message ) || cfg.i18n.networkError;
					$( '#platform-helm-gp-purge-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( msg ) + '</p></div>' );
					$btn.prop( 'disabled', false ).text( 'Purge' );
					return;
				}
				var d        = response.data;
				var done     = d.done;
				var cursor   = d.cursor;
				var pct      = Math.floor( ( cursor / total ) * 100 );
				var fromIdx  = Math.max( 1, cursor - batchSize + 1 );

				setProgress(
					pct,
					formatString( cfg.i18n.processing, [ fromIdx, cursor, total ] )
				);

				if ( done ) {
					setProgress( 100, '' );
					var t = d.totals || {};
					$( '#platform-helm-gp-purge-results' ).html(
						'<div class="notice notice-success"><p><strong>' + escapeHtml( cfg.i18n.doneTitle ) + ':</strong> ' +
						escapeHtml( formatString( cfg.i18n.doneSummary, [
							t.deleted || 0,
							t.failed  || 0
						] ) ) +
						'</p></div>'
					);
					$btn.prop( 'disabled', false ).text( 'Purge' );
					return;
				}
				nextBatch();
			} ).fail( function () {
				$( '#platform-helm-gp-purge-results' ).html( '<div class="notice notice-error"><p>' + escapeHtml( cfg.i18n.networkError ) + '</p></div>' );
				$btn.prop( 'disabled', false ).text( 'Purge' );
			} );
		}
		nextBatch();
	}

} )( jQuery );
