<?php
/**
 * Admin.
 *
 * @package Noesia_Commerce_Suite
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- View templates receive local variables from their renderer.
$range        = isset( $stats['date_range_days'] ) ? absint( $stats['date_range_days'] ) : 30;
$range_label  = isset( $stats['range_label'] ) ? $stats['range_label'] : $range_label;
$format_money = function ( $amount ) {
	return function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( $amount ) ) : number_format_i18n( (float) $amount, 2 );
};
$dashboard_top_products   = isset( $dashboard_top_products ) && is_array( $dashboard_top_products ) ? $dashboard_top_products : array();
$dashboard_product_range  = isset( $dashboard_product_range ) ? sanitize_key( $dashboard_product_range ) : 'all';
$recent_orders_preview    = isset( $recent_orders_preview ) && is_array( $recent_orders_preview ) ? $recent_orders_preview : array();
$customer_retention       = isset( $customer_retention ) && is_array( $customer_retention ) ? $customer_retention : array();
$render_ranked = function ( $title, $items, $metric_key, $metric_label, $empty_message ) use ( $format_money ) {
	?>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php echo esc_html( $title ); ?></h2><span><?php echo esc_html( $metric_label ); ?></span></div>
		<div class="noesia-cs-ranking-list">
			<?php foreach ( $items as $label => $data ) : ?>
				<?php
				$display_label  = isset( $data['label'] ) ? $data['label'] : $label;
				$value          = isset( $data[ $metric_key ] ) ? $data[ $metric_key ] : 0;
				$value_text    = 'revenue' === $metric_key ? $format_money( $value ) : number_format_i18n( absint( $value ) );
				?>
				<div class="noesia-cs-ranking-row">
					<strong><?php echo esc_html( $display_label ); ?></strong>
					<span><?php echo esc_html( $value_text ); ?></span>
				</div>
			<?php endforeach; ?>
			<?php if ( empty( $items ) ) : ?><p><?php echo esc_html( $empty_message ); ?></p><?php endif; ?>
		</div>
	</div>
	<?php
};
?>
<section class="noesia-cs-feature-hero noesia-cs-feature-hero--analytics">
	<div>
		<span><?php esc_html_e( 'Free Core', 'noesia-commerce-suite' ); ?></span>
		<h2><?php esc_html_e( 'WooCommerce Intelligence', 'noesia-commerce-suite' ); ?></h2>
		<p><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Real WooCommerce order intelligence for the selected range: %s. No analytics tracking, fake referral data or customer journey assumptions.', 'noesia-commerce-suite' ), esc_html( $range_label ) ); ?></p>
	</div>
	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<?php wp_nonce_field( 'noesia_cs_refresh_analytics' ); ?>
		<input type="hidden" name="action" value="noesia_cs_refresh_analytics">
		<button class="noesia-cs-primary-button" type="submit"><?php esc_html_e( 'Refresh Analytics Cache', 'noesia-commerce-suite' ); ?></button>
	</form>
</section>
<?php $admin->render_dashboard_date_filter( $stats ); ?>

<section class="noesia-cs-metrics noesia-cs-metrics--four">
	<?php $admin->metric_card( __( 'Orders', 'noesia-commerce-suite' ), number_format_i18n( $stats['total_orders'] ), '●', $range_label, 'bag' ); ?>
	<?php $admin->metric_card( __( 'Revenue', 'noesia-commerce-suite' ), $format_money( $stats['total_revenue'] ), '●', __( 'WooCommerce orders', 'noesia-commerce-suite' ), 'currency' ); ?>
	<?php $admin->metric_card( __( 'Average Order Value', 'noesia-commerce-suite' ), $format_money( $stats['aov'] ), '●', __( 'revenue divided by orders', 'noesia-commerce-suite' ), 'trend' ); ?>
	<?php $admin->metric_card( __( 'Orders Checked', 'noesia-commerce-suite' ), number_format_i18n( $stats['orders_checked'] ), '●', __( 'cached query', 'noesia-commerce-suite' ), 'target' ); ?>
</section>

<section class="noesia-cs-grid noesia-cs-grid--dashboard-addons noesia-cs-grid--analytics-highlights">
	<div class="noesia-cs-panel noesia-cs-panel--dashboard-products">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Top Products Performance', 'noesia-commerce-suite' ); ?></h2><span><?php esc_html_e( 'by quantity sold', 'noesia-commerce-suite' ); ?></span></div>
		<?php $admin->render_dashboard_top_products( $dashboard_top_products, $dashboard_product_range, 'intelligence-analytics' ); ?>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Order Health', 'noesia-commerce-suite' ); ?></h2><span><?php echo esc_html( $range_label ); ?></span></div>
		<?php $admin->render_dashboard_order_health( $stats ); ?>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Customer Retention', 'noesia-commerce-suite' ); ?></h2><span><?php echo esc_html( $range_label ); ?></span></div>
		<?php $admin->render_customer_retention( $customer_retention, $range_label ); ?>
	</div>
</section>

<section class="noesia-cs-grid noesia-cs-grid--analytics">
	<div class="noesia-cs-panel noesia-cs-panel--wide">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Revenue Overview', 'noesia-commerce-suite' ); ?></h2><span><?php esc_html_e( 'Cached from WooCommerce orders', 'noesia-commerce-suite' ); ?></span></div>
		<?php $admin->render_revenue_svg( $stats['revenue_series'] ); ?>
	</div>
	<div class="noesia-cs-panel">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Order Status Overview', 'noesia-commerce-suite' ); ?></h2></div>
		<?php $admin->render_order_health( $stats ); ?>
	</div>
</section>

<section class="noesia-cs-grid noesia-cs-grid--bottom">
	<?php $render_ranked( __( 'Orders by Payment Method', 'noesia-commerce-suite' ), $stats['payment_methods_by_orders'], 'orders', __( 'orders', 'noesia-commerce-suite' ), __( 'No payment method order data in this range.', 'noesia-commerce-suite' ) ); ?>
	<?php $render_ranked( __( 'Revenue by Payment Method', 'noesia-commerce-suite' ), $stats['payment_methods_by_revenue'], 'revenue', __( 'revenue', 'noesia-commerce-suite' ), __( 'No payment method revenue data in this range.', 'noesia-commerce-suite' ) ); ?>
	<?php $render_ranked( __( 'Cancelled / Failed by Payment Method', 'noesia-commerce-suite' ), $stats['payment_cancelled_or_failed'], 'cancelled_failed', __( 'cancelled or failed orders', 'noesia-commerce-suite' ), __( 'No cancelled or failed payment-method data in this range.', 'noesia-commerce-suite' ) ); ?>
</section>

<section class="noesia-cs-grid noesia-cs-grid--analytics-payment-recent">
	<div class="noesia-cs-panel noesia-cs-panel--payment-detail">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Payment Method Detail', 'noesia-commerce-suite' ); ?></h2><span><?php echo esc_html( $range_label ); ?></span></div>
		<div class="noesia-cs-table-wrap"><table class="noesia-cs-table"><thead><tr><th><?php esc_html_e( 'Payment Method', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Orders', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Revenue', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Average Order Value', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Cancelled / Failed', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Top Products', 'noesia-commerce-suite' ); ?></th></tr></thead><tbody>
		<?php foreach ( $stats['payment_methods_by_revenue'] as $method ) : ?>
			<tr><td><strong><?php echo esc_html( $method['label'] ?? __( 'Payment method', 'noesia-commerce-suite' ) ); ?></strong></td><td><?php echo esc_html( number_format_i18n( absint( $method['orders'] ?? 0 ) ) ); ?></td><td><?php echo esc_html( $format_money( $method['revenue'] ?? 0 ) ); ?></td><td><?php echo esc_html( $format_money( $method['aov'] ?? 0 ) ); ?></td><td><?php echo esc_html( number_format_i18n( absint( $method['cancelled_failed'] ?? 0 ) ) ); ?></td><td><?php echo esc_html( implode( ', ', array_map( 'sanitize_text_field', $method['top_products'] ?? array() ) ) ); ?></td></tr>
		<?php endforeach; ?>
		<?php if ( empty( $stats['payment_methods_by_revenue'] ) ) : ?><tr><td colspan="6"><?php esc_html_e( 'No payment method data in the selected date range.', 'noesia-commerce-suite' ); ?></td></tr><?php endif; ?>
		</tbody></table></div>
	</div>
	<div class="noesia-cs-panel noesia-cs-panel--analytics-recent-orders">
		<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Recent Orders', 'noesia-commerce-suite' ); ?></h2><a href="<?php echo esc_url( admin_url( 'edit.php?post_type=shop_order' ) ); ?>"><?php esc_html_e( 'View all', 'noesia-commerce-suite' ); ?></a></div>
		<?php $admin->render_recent_orders_preview( $recent_orders_preview ); ?>
	</div>
</section>

<section class="noesia-cs-grid noesia-cs-grid--bottom">
	<?php $render_ranked( __( 'Top Products by Revenue', 'noesia-commerce-suite' ), $stats['top_products_by_revenue'], 'revenue', __( 'revenue', 'noesia-commerce-suite' ), __( 'No product revenue data yet.', 'noesia-commerce-suite' ) ); ?>
	<?php $render_ranked( __( 'Top Products by Quantity', 'noesia-commerce-suite' ), $stats['top_products_by_quantity'], 'quantity', __( 'quantity', 'noesia-commerce-suite' ), __( 'No product quantity data yet.', 'noesia-commerce-suite' ) ); ?>
	<?php if ( 'yes' === $settings['show_analytics_categories'] ) : ?>
		<?php $render_ranked( __( 'Top Categories', 'noesia-commerce-suite' ), $stats['top_categories'], 'revenue', __( 'revenue', 'noesia-commerce-suite' ), __( 'No category data yet.', 'noesia-commerce-suite' ) ); ?>
	<?php endif; ?>
	<?php if ( 'yes' === $settings['show_analytics_top_cities'] ) : ?>
		<?php $render_ranked( __( 'Top Areas by Orders', 'noesia-commerce-suite' ), $stats['top_cities_by_orders'], 'orders', __( 'orders', 'noesia-commerce-suite' ), __( 'No city or region data yet.', 'noesia-commerce-suite' ) ); ?>
		<?php $render_ranked( __( 'Top Areas by Revenue', 'noesia-commerce-suite' ), $stats['top_cities_by_revenue'], 'revenue', __( 'revenue', 'noesia-commerce-suite' ), __( 'No city or region revenue data yet.', 'noesia-commerce-suite' ) ); ?>
	<?php endif; ?>
	<?php if ( 'yes' === $settings['show_analytics_top_customers'] ) : ?>
		<?php $render_ranked( __( 'Top Customers by Orders', 'noesia-commerce-suite' ), $stats['top_customers_by_orders'], 'orders', __( 'orders', 'noesia-commerce-suite' ), __( 'No customer ranking data yet.', 'noesia-commerce-suite' ) ); ?>
		<?php $render_ranked( __( 'Top Customers by Spend', 'noesia-commerce-suite' ), $stats['top_customers_by_spend'], 'revenue', __( 'spend', 'noesia-commerce-suite' ), __( 'No customer spend data yet.', 'noesia-commerce-suite' ) ); ?>
	<?php else : ?>
		<div class="noesia-cs-panel">
			<div class="noesia-cs-panel__head"><h2><?php esc_html_e( 'Top Customers', 'noesia-commerce-suite' ); ?></h2><span><?php esc_html_e( 'disabled', 'noesia-commerce-suite' ); ?></span></div>
			<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Customer rankings are hidden by the analytics setting. Enable Show Top Customers to calculate and display anonymized/customer-ID based admin rankings.', 'noesia-commerce-suite' ); ?></p>
		</div>
	<?php endif; ?>
</section>

<section class="noesia-cs-pro-grid">
	<?php $admin->pro_edition_card( __( 'Checkout Confidence Analytics', 'noesia-commerce-suite' ), __( 'Understand where orders come from, how customers pay and where checkout confidence can improve.', 'noesia-commerce-suite' ), 'checkout_confidence_analytics' ); ?>
	<?php $admin->pro_edition_card( __( 'Live Checkout Radar', 'noesia-commerce-suite' ), __( 'A live checkout command center for real buying intent: see active carts, checkout stage, cart value and hesitation while the customer is still on your store.', 'noesia-commerce-suite' ), 'checkout_confidence_live_radar' ); ?>
	<?php $admin->pro_edition_card( __( 'Doctor Pro Deep Store Scan', 'noesia-commerce-suite' ), __( 'Check large stores with many products and reveal the issues that need attention before they cost trust or sales.', 'noesia-commerce-suite' ), 'doctor_deep_scan' ); ?>
	<?php $admin->pro_edition_card( __( 'Doctor Pro CSV Fix Report', 'noesia-commerce-suite' ), __( 'Download the Doctor Pro fix plan as CSV after the scan, so improvements can be shared or handled by your team.', 'noesia-commerce-suite' ), 'doctor_csv_export' ); ?>
</section>
