<?php
/**
 * Reports — customer journey tab.
 *
 * @package CartCue
 */
defined( 'ABSPATH' ) || exit;
?>
<div class="ap-card">
	<div class="ap-card__header"><?php esc_html_e( 'Customer journey', 'cartcue-sales-automation' ); ?></div>
	<div class="ap-card__body">
		<p class="description"><?php esc_html_e( 'Look up a customer email to see automations, emails, branches, and unsubscribe events.', 'cartcue-sales-automation' ); ?></p>
		<div class="ap-field-row" style="display:flex;gap:8px;align-items:center;max-width:520px">
			<input type="email" id="ap-journey-email" class="ap-input" placeholder="<?php esc_attr_e( 'customer@example.com', 'cartcue-sales-automation' ); ?>">
			<button type="button" class="ap-btn ap-btn-primary" id="ap-journey-search"><?php esc_html_e( 'Search', 'cartcue-sales-automation' ); ?></button>
		</div>
		<div id="ap-journey-results" style="margin-top:20px"></div>
	</div>
</div>
<script>
jQuery(function($){
	var nonce = (window.cartcueAdmin && cartcueAdmin.nonces && cartcueAdmin.nonces.customer_journey) || '';
	$('#ap-journey-search').on('click', function(){
		var email = $('#ap-journey-email').val();
		$('#ap-journey-results').html('<p><?php echo esc_js( __( 'Loading…', 'cartcue-sales-automation' ) ); ?></p>');
		$.post(ajaxurl, { action: 'cartcue_customer_journey', email: email, nonce: nonce }, function(r){
			if(!r.success || !r.data || !r.data.length){
				$('#ap-journey-results').html('<p><?php echo esc_js( __( 'No journey events found for this email.', 'cartcue-sales-automation' ) ); ?></p>');
				return;
			}
			var html = '<table class="wp-list-table widefat fixed striped"><thead><tr><th><?php echo esc_js( __( 'When', 'cartcue-sales-automation' ) ); ?></th><th><?php echo esc_js( __( 'Event', 'cartcue-sales-automation' ) ); ?></th></tr></thead><tbody>';
			r.data.forEach(function(row){
				html += '<tr><td>' + $('<span>').text(row.at).html() + '</td><td>' + $('<span>').text(row.label).html() + '</td></tr>';
			});
			html += '</tbody></table>';
			$('#ap-journey-results').html(html);
		});
	});
});
</script>
