<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; }

$kpis    = isset( $kpis ) && is_array( $kpis ) ? $kpis : array();
$top     = isset( $top_products ) && is_array( $top_products ) ? $top_products : array();
$recent  = isset( $recent ) && is_array( $recent ) ? $recent : array();
$lastcap = isset( $last_capture ) && is_array( $last_capture ) ? $last_capture : array();
$set     = isset( $settings ) && is_array( $settings ) ? $settings : array();

$money = static function ( $v ) {
	return number_format_i18n( (float) $v, 2 ) . ' €';
};
$badge = static function ( $txt, $bg, $fg ) {
	return '<span style="display:inline-block;padding:1px 8px;border-radius:10px;font-size:11px;font-weight:600;background:' . $bg . ';color:' . $fg . ';">' . esc_html( $txt ) . '</span>';
};
$outcome_badge = static function ( $kind, $outcome, $status ) use ( $badge ) {
	if ( 'saved' === $kind ) {
		return $badge( __( 'saved', 'ai-eshop-optimizer' ), '#eef2ff', '#3730a3' );
	}
	switch ( (string) $outcome ) {
		case 'converted':
			return $badge( __( 'converted', 'ai-eshop-optimizer' ), '#ecfdf5', '#047857' );
		case 'expired':
			return $badge( __( 'expired', 'ai-eshop-optimizer' ), '#fef2f2', '#b91c1c' );
		case 'open':
			return $badge( __( 'open', 'ai-eshop-optimizer' ), '#fffbeb', '#92400e' );
		default:
			return $badge( (string) ( $outcome ? $outcome : $status ), '#f3f4f6', '#6b7280' );
	}
};
?>
<style>
.aieo-c-kpis{display:flex;flex-wrap:wrap;gap:12px;margin-top:8px;}
.aieo-c-kpi{flex:1 1 180px;background:#f8fafc;border:1px solid #e6e9ee;border-radius:8px;padding:12px 14px;}
.aieo-c-kpi .n{font-size:22px;font-weight:700;color:#111827;line-height:1.1;}
.aieo-c-kpi .l{font-size:11px;color:#6b7280;margin-top:3px;}
.aieo-c-kpi.good{background:#ecfdf5;border-color:#a7f3d0;}
.aieo-c-kpi.warn{background:#fffbeb;border-color:#fde68a;}
.aieo-c-kpi.bad{background:#fef2f2;border-color:#fecaca;}
.aieo-c-kpi.info{background:#eef2ff;border-color:#c7d2fe;}
.aieo-c-table{width:100%;border-collapse:collapse;font-size:13px;margin-top:8px;}
.aieo-c-table th,.aieo-c-table td{padding:7px 8px;border-bottom:1px solid #eef0f2;text-align:left;vertical-align:top;}
.aieo-c-table th{font-size:11px;color:#6b7280;text-transform:uppercase;letter-spacing:.03em;}
.aieo-c-table td.num,.aieo-c-table th.num{text-align:right;white-space:nowrap;}
.aieo-c-table tfoot td{font-weight:700;border-top:2px solid #e5e7eb;background:#fafbfc;}
.aieo-c-rank{font-size:11px;color:#9ca3af;width:26px;}
.aieo-c-set label{font-size:12px;color:#374151;font-weight:600;margin-right:6px;}
.aieo-c-set input[type=text]{width:240px;}
.aieo-c-set input[type=number]{width:80px;}
#aieo-c-status{font-size:12px;margin-left:10px;}
.aieo-c-chip{display:inline-block;margin-left:5px;padding:0 6px;border-radius:8px;font-size:10px;background:#ede9fe;color:#5b21b6;}
</style>

<div class="aieo-dmm-section" id="aieo-card-saved-abandoned-carts">

	<h2><?php esc_html_e( 'Saved & Abandoned Carts', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description">
		<?php esc_html_e( 'A permanent record of every cart shoppers save/share, and every checkout cart they abandon — captured from WooCommerce block-checkout draft orders before WooCommerce purges them, with each one tracked through to converted or expired. The figures here accumulate over time and never disappear.', 'ai-eshop-optimizer' ); ?>
	</p>

	<?php if ( ! $have_tables ) : ?>
		<div class="aieo-dmm-card"><p class="description"><?php esc_html_e( 'The cart tables are not installed yet. Open any AIEO admin page once (or bump the plugin version) to create them, then return here.', 'ai-eshop-optimizer' ); ?></p></div>
	<?php else : ?>

	<p style="margin:0 0 6px;">
		<button type="button" class="button button-primary" id="aieo-c-capture"><?php esc_html_e( 'Capture abandoned carts now', 'ai-eshop-optimizer' ); ?></button>
		<span id="aieo-c-status">
			<?php if ( ! empty( $lastcap['time'] ) ) : ?>
				<?php
				printf(
					
					esc_html__( 'Last run %1$s — captured %2$s, resolved %3$s.', 'ai-eshop-optimizer' ),
					esc_html( $lastcap['time'] ),
					esc_html( number_format_i18n( (int) ( $lastcap['captured'] ?? 0 ) ) ),
					esc_html( number_format_i18n( (int) ( $lastcap['resolved'] ?? 0 ) ) )
				);
				?>
			<?php else : ?>
				<?php esc_html_e( 'Runs automatically every hour.', 'ai-eshop-optimizer' ); ?>
			<?php endif; ?>
		</span>
	</p>
	<p class="aieo-c-set" style="margin:0 0 10px;">
		<label><input type="checkbox" id="aieo-c-capture-enabled" <?php checked( ! empty( $set['capture_enabled'] ) ); ?>> <?php esc_html_e( 'Automatically capture abandoned carts every hour', 'ai-eshop-optimizer' ); ?></label>
		<span class="description" style="margin-left:6px;"><?php esc_html_e( '(turn off to stop the hourly job — the “Capture now” button above still works)', 'ai-eshop-optimizer' ); ?></span>
	</p>

	<?php ?>
	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Abandoned checkout carts', 'ai-eshop-optimizer' ); ?></h3>
		<div class="aieo-c-kpis">
			<div class="aieo-c-kpi">
				<div class="n"><?php echo esc_html( number_format_i18n( (int) ( $kpis['abandoned_count'] ?? 0 ) ) ); ?></div>
				<div class="l"><?php esc_html_e( 'Abandoned carts captured (all time)', 'ai-eshop-optimizer' ); ?></div>
			</div>
			<div class="aieo-c-kpi warn">
				<div class="n"><?php echo esc_html( $money( $kpis['open_value'] ?? 0 ) ); ?></div>
				<div class="l"><?php printf( esc_html__( 'Still open / in pipeline · %s carts', 'ai-eshop-optimizer' ), esc_html( number_format_i18n( (int) ( $kpis['open_count'] ?? 0 ) ) ) ); ?></div>
			</div>
			<div class="aieo-c-kpi good">
				<div class="n"><?php echo esc_html( $money( $kpis['converted_value'] ?? 0 ) ); ?></div>
				<div class="l"><?php printf( esc_html__( 'Recovered — later converted · %s carts', 'ai-eshop-optimizer' ), esc_html( number_format_i18n( (int) ( $kpis['converted_count'] ?? 0 ) ) ) ); ?></div>
			</div>
			<div class="aieo-c-kpi bad">
				<div class="n"><?php echo esc_html( $money( $kpis['expired_value'] ?? 0 ) ); ?></div>
				<div class="l"><?php printf( esc_html__( 'Lost — expired without buying · %s carts', 'ai-eshop-optimizer' ), esc_html( number_format_i18n( (int) ( $kpis['expired_count'] ?? 0 ) ) ) ); ?></div>
			</div>
			<div class="aieo-c-kpi info">
				<div class="n"><?php echo esc_html( number_format_i18n( 100 * (float) ( $kpis['conversion_rate'] ?? 0 ), 1 ) ); ?>%</div>
				<div class="l"><?php esc_html_e( 'Recovery rate (converted ÷ decided)', 'ai-eshop-optimizer' ); ?></div>
			</div>
			<?php if ( (int) ( $kpis['restocked_count'] ?? 0 ) > 0 ) : ?>
			<div class="aieo-c-kpi">
				<div class="n"><?php echo esc_html( $money( $kpis['restocked_value'] ?? 0 ) ); ?></div>
				<div class="l"><?php printf( esc_html__( 'In carts with a Stock-Recovery restocked product · %s carts', 'ai-eshop-optimizer' ), esc_html( number_format_i18n( (int) ( $kpis['restocked_count'] ?? 0 ) ) ) ); ?></div>
			</div>
			<?php endif; ?>
		</div>
		<p class="description" style="margin:10px 0 0;"><?php esc_html_e( 'Drafts still being worked on stay “open”; once the shopper places the order they flip to “converted” (recovered), and if WooCommerce purges the draft without an order they become “expired” (lost). Values are the cart totals at capture (converted carts show the final order total).', 'ai-eshop-optimizer' ); ?></p>
	</div>

	<?php ?>
	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Saved & shared carts', 'ai-eshop-optimizer' ); ?></h3>
		<div class="aieo-c-kpis">
			<div class="aieo-c-kpi">
				<div class="n"><?php echo esc_html( number_format_i18n( (int) ( $kpis['saved_count'] ?? 0 ) ) ); ?></div>
				<div class="l"><?php esc_html_e( 'Carts saved/shared by shoppers', 'ai-eshop-optimizer' ); ?></div>
			</div>
			<div class="aieo-c-kpi">
				<div class="n"><?php echo esc_html( $money( $kpis['saved_value'] ?? 0 ) ); ?></div>
				<div class="l"><?php esc_html_e( 'Total value of saved carts', 'ai-eshop-optimizer' ); ?></div>
			</div>
			<div class="aieo-c-kpi info">
				<div class="n"><?php echo esc_html( number_format_i18n( (int) ( $kpis['saved_resumes'] ?? 0 ) ) ); ?></div>
				<div class="l"><?php esc_html_e( 'Times a saved cart was reopened / resumed', 'ai-eshop-optimizer' ); ?></div>
			</div>
		</div>

		<h4 style="margin:14px 0 4px;"><?php esc_html_e( 'Storefront save / share feature', 'ai-eshop-optimizer' ); ?></h4>
		<p class="aieo-c-set" style="margin:0 0 6px;">
			<label><input type="checkbox" id="aieo-c-enabled" <?php checked( ! empty( $set['save_enabled'] ) ); ?>> <?php esc_html_e( 'Enable the “Save / share my cart” button (cart page)', 'ai-eshop-optimizer' ); ?></label>
		</p>
		<p class="aieo-c-set" style="margin:0 0 6px;">
			<label><input type="checkbox" id="aieo-c-checkout" <?php checked( ! empty( $set['show_on_checkout'] ) ); ?>> <?php esc_html_e( 'Also show on the Checkout page', 'ai-eshop-optimizer' ); ?></label>
		</p>
		<p class="description" style="margin:0 0 6px;">
			<?php
			printf(
				
				esc_html__( 'To show & fully style this button inside the side-cart, use %s (Action buttons → SAVE button).', 'ai-eshop-optimizer' ),
				'<a href="' . esc_url( admin_url( 'admin.php?page=ai-eshop-dmm&dmm_tab=side_cart' ) ) . '">' . esc_html__( 'Side-Cart settings', 'ai-eshop-optimizer' ) . '</a>'
			);
			?>
		</p>
		<p class="aieo-c-set" style="margin:0 0 6px;">
			<label><?php esc_html_e( 'Button label', 'ai-eshop-optimizer' ); ?></label>
			<input type="text" id="aieo-c-label" value="<?php echo esc_attr( $set['save_label'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'Save / share my cart', 'ai-eshop-optimizer' ); ?>">
			<label style="margin-left:14px;"><?php esc_html_e( 'Keep saved carts for (days)', 'ai-eshop-optimizer' ); ?></label>
			<input type="number" id="aieo-c-ttl" min="0" max="3650" value="<?php echo esc_attr( (int) ( $set['ttl_days'] ?? 60 ) ); ?>">
			<button type="button" class="button button-secondary" id="aieo-c-save" style="margin-left:8px;"><?php esc_html_e( 'Save settings', 'ai-eshop-optimizer' ); ?></button>
		</p>
		<p class="description" style="margin:4px 0 0;">
			<?php esc_html_e( 'Shoppers get a link they can bookmark or send to someone; opening it loads the items back into the cart. You can also place the button anywhere with the shortcode', 'ai-eshop-optimizer' ); ?>
			<code>[aieo_save_cart]</code>. <?php esc_html_e( 'Share links look like', 'ai-eshop-optimizer' ); ?> <code><?php echo esc_html( $share_base ); ?>&lt;token&gt;</code> · <?php esc_html_e( '0 days = keep forever.', 'ai-eshop-optimizer' ); ?>
		</p>
	</div>

	<?php ?>
	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Most-abandoned products (lost demand)', 'ai-eshop-optimizer' ); ?></h3>
		<?php if ( empty( $top ) ) : ?>
			<p class="description"><?php esc_html_e( 'No abandoned-cart items captured yet.', 'ai-eshop-optimizer' ); ?></p>
		<?php else : ?>
		<table class="aieo-c-table">
			<thead><tr>
				<th>#</th>
				<th><?php esc_html_e( 'Product / SKU', 'ai-eshop-optimizer' ); ?></th>
				<th class="num"><?php esc_html_e( 'In carts', 'ai-eshop-optimizer' ); ?></th>
				<th class="num"><?php esc_html_e( 'Units', 'ai-eshop-optimizer' ); ?></th>
					<th class="num" title="<?php esc_attr_e( 'Units actually sold via converted checkout carts, since the first captured record', 'ai-eshop-optimizer' ); ?>"><?php esc_html_e( 'Sold', 'ai-eshop-optimizer' ); ?></th>
				<th class="num"><?php esc_html_e( 'Lost value', 'ai-eshop-optimizer' ); ?></th>
					<th class="num" title="<?php esc_attr_e( 'Converted checkout carts ÷ all checkout carts the product appeared in', 'ai-eshop-optimizer' ); ?>"><?php esc_html_e( 'Success', 'ai-eshop-optimizer' ); ?></th>
			</tr></thead>
			<tbody>
			<?php $rank = 0; foreach ( $top as $t ) : $rank++;
				$pid  = (int) ( $t['variation_id'] ? $t['variation_id'] : $t['product_id'] );
				$edit = (int) $t['product_id'] > 0 ? admin_url( 'post.php?post=' . (int) $t['product_id'] . '&action=edit' ) : '';
			?>
				<tr>
					<td class="aieo-c-rank"><?php echo esc_html( $rank ); ?></td>
					<td>
						<?php if ( $edit ) : ?><a href="<?php echo esc_url( $edit ); ?>" target="_blank" rel="noopener"><strong><?php echo esc_html( $t['name'] !== '' ? $t['name'] : ( '#' . (int) $t['product_id'] ) ); ?></strong></a><?php else : ?><strong><?php echo esc_html( $t['name'] !== '' ? $t['name'] : ( '#' . (int) $t['product_id'] ) ); ?></strong><?php endif; ?>
						<?php if ( (int) $t['is_restocked'] === 1 ) { echo '<span class="aieo-c-chip">' . esc_html__( 'restocked', 'ai-eshop-optimizer' ) . '</span>'; } ?>
						<?php if ( ! empty( $t['sku'] ) ) : ?><br><code style="font-size:11px;color:#9ca3af;"><?php echo esc_html( $t['sku'] ); ?></code><?php endif; ?>
					</td>
					<td class="num"><?php echo esc_html( number_format_i18n( (int) $t['carts'] ) ); ?></td>
					<td class="num"><?php echo esc_html( number_format_i18n( (int) $t['units'] ) ); ?></td>
						<td class="num"><?php echo esc_html( number_format_i18n( (int) ( $t['sold_units'] ?? 0 ) ) ); ?></td>
					<td class="num"><strong><?php echo esc_html( $money( $t['lost_value'] ) ); ?></strong></td>
						<td class="num"><?php
							$sr = isset( $t['success_rate'] ) ? (float) $t['success_rate'] : 0.0;
							printf(
								'<span title="%s">%s%%</span>',
								esc_attr( sprintf(
									
									__( '%1$d converted of %2$d checkout carts', 'ai-eshop-optimizer' ),
									(int) ( $t['sold_transactions'] ?? 0 ),
									(int) ( $t['checkout_carts'] ?? 0 )
								) ),
								esc_html( number_format_i18n( $sr, ( $sr == (int) $sr ) ? 0 : 1 ) )
							);
						?></td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php endif; ?>
	</div>

	<?php ?>
	<div class="aieo-dmm-card">
		<h3 style="display:inline-block;"><?php esc_html_e( 'Recent carts', 'ai-eshop-optimizer' ); ?></h3>
		<a class="button" style="float:right;" href="<?php echo esc_url( admin_url( 'admin-ajax.php' ) . '?action=aieo_carts_export&nonce=' . rawurlencode( $nonce ) ); ?>"><?php esc_html_e( 'Export to Excel', 'ai-eshop-optimizer' ); ?></a>
		<?php if ( empty( $recent ) ) : ?>
			<p class="description"><?php esc_html_e( 'No carts recorded yet.', 'ai-eshop-optimizer' ); ?></p>
		<?php else : ?>
		<table class="aieo-c-table">
			<thead><tr>
				<th><?php esc_html_e( 'When', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Type', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Customer', 'ai-eshop-optimizer' ); ?></th>
				<th class="num"><?php esc_html_e( 'Items', 'ai-eshop-optimizer' ); ?></th>
				<th class="num"><?php esc_html_e( 'Value', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Order', 'ai-eshop-optimizer' ); ?></th>
			</tr></thead>
			<tbody>
			<?php foreach ( $recent as $r ) :
				$oid  = (int) ( $r['converted_order_id'] ? $r['converted_order_id'] : $r['wc_order_id'] );
				$olnk = $oid > 0 ? admin_url( 'admin.php?page=wc-orders&action=edit&id=' . $oid ) : '';
			?>
				<tr>
					<td style="font-size:11px;color:#6b7280;white-space:nowrap;"><?php echo esc_html( substr( (string) $r['created_at'], 0, 16 ) ); ?></td>
					<td>
						<?php echo $outcome_badge( $r['kind'], $r['outcome'], $r['status'] ); ?>
						<?php if ( (int) $r['contains_restocked'] === 1 ) { echo ' <span class="aieo-c-chip">' . esc_html__( 'restocked', 'ai-eshop-optimizer' ) . '</span>'; } ?>
						<?php if ( 'saved' === $r['kind'] && (int) $r['resume_count'] > 0 ) : ?><br><span style="font-size:10px;color:#6b7280;"><?php printf( esc_html__( 'reopened %s×', 'ai-eshop-optimizer' ), esc_html( number_format_i18n( (int) $r['resume_count'] ) ) ); ?></span><?php endif; ?>
					</td>
					<td style="font-size:12px;"><?php echo esc_html( $r['customer_email'] !== '' ? $r['customer_email'] : ( (int) $r['user_id'] > 0 ? ( '#' . (int) $r['user_id'] ) : __( 'guest', 'ai-eshop-optimizer' ) ) ); ?></td>
					<td class="num"><?php echo esc_html( number_format_i18n( (int) $r['item_count'] ) ); ?></td>
					<td class="num"><?php echo esc_html( $money( $r['total'] ) ); ?></td>
					<td><?php if ( $olnk ) : ?><a href="<?php echo esc_url( $olnk ); ?>" target="_blank" rel="noopener">#<?php echo esc_html( $oid ); ?></a><?php else : ?><span style="color:#9ca3af;">—</span><?php endif; ?></td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<p class="description" style="margin:8px 0 0;"><?php esc_html_e( 'Showing the 100 most recent. Use “Export to Excel” for the full history.', 'ai-eshop-optimizer' ); ?></p>
		<?php endif; ?>
	</div>

	<?php endif; ?>
</div>

<script>
(function(){
	var NONCE = <?php echo wp_json_encode( $nonce ); ?>;
	var statusEl = document.getElementById('aieo-c-status');
	function setStatus(msg, ok){ if(!statusEl) return; statusEl.textContent = msg; statusEl.style.color = ok===false ? '#b91c1c' : (ok ? '#15803d' : '#6b7280'); }
	function post(action, data){
		var fd = new FormData(); fd.append('action', action); fd.append('nonce', NONCE);
		Object.keys(data||{}).forEach(function(k){ fd.append(k, data[k]); });
		return fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'}).then(function(r){ return r.json(); });
	}
	var capBtn = document.getElementById('aieo-c-capture');
	capBtn && capBtn.addEventListener('click', function(){
		capBtn.disabled = true; setStatus('<?php echo esc_js( __( 'Capturing…', 'ai-eshop-optimizer' ) ); ?>');
		post('aieo_carts_capture_now', {}).then(function(j){
			capBtn.disabled = false;
			if (j && j.success) { setStatus((j.data && j.data.message) || 'OK', true); setTimeout(function(){ location.reload(); }, 900); }
			else { setStatus((j && j.data && j.data.message) || 'error', false); }
		}).catch(function(){ capBtn.disabled = false; setStatus('<?php echo esc_js( __( 'network error', 'ai-eshop-optimizer' ) ); ?>', false); });
	});
	// Collect the full settings payload from the DOM. Always send EVERY field
	// — ajax_carts_save_settings treats a missing checkbox as "off", so a
	// partial POST (e.g. the capture toggle auto-save) would wipe the others.
	function collectSettings(){
		return {
			save_enabled:     document.getElementById('aieo-c-enabled').checked ? 1 : 0,
			save_label:       document.getElementById('aieo-c-label').value,
			ttl_days:         document.getElementById('aieo-c-ttl').value,
			show_on_checkout: document.getElementById('aieo-c-checkout').checked ? 1 : 0,
			capture_enabled:  document.getElementById('aieo-c-capture-enabled').checked ? 1 : 0
		};
	}
	function saveSettings(){
		setStatus('<?php echo esc_js( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>');
		return post('aieo_carts_save_settings', collectSettings()).then(function(j){
			if (j && j.success) { setStatus((j.data && j.data.message) || '<?php echo esc_js( __( 'Saved.', 'ai-eshop-optimizer' ) ); ?>', true); }
			else { setStatus((j && j.data && j.data.message) || 'error', false); }
		}).catch(function(){ setStatus('<?php echo esc_js( __( 'network error', 'ai-eshop-optimizer' ) ); ?>', false); });
	}
	var saveBtn = document.getElementById('aieo-c-save');
	saveBtn && saveBtn.addEventListener('click', saveSettings);
	// The capture toggle sits in its own card, far from the Save button — persist
	// it immediately on change so the operator doesn't have to scroll to save.
	var capEnable = document.getElementById('aieo-c-capture-enabled');
	capEnable && capEnable.addEventListener('change', saveSettings);
})();
</script>
