<?php
/**
 * Order Columns — Event Status column for WooCommerce Order List.
 *
 * Registers a single column `capiflow_event_status` showing CAPI sync status only:
 *  - ✅ Sent (purchase CAPI event sent)
 *  - ⏳ Queued (in processing queue)
 *  - ❌ Failed (API error)
 *  - — Pending (not yet triggered)
 *
 * Risk scoring, success rate, and tooltip have been removed.
 * All risk/fraud features are now exclusively in CapiFlow Pro
 * (Reputation Engine + 🧠 Risk column).
 *
 * HPOS-compatible (uses WC order meta API, not raw DB).
 * WP.org compliant upsell: 🔒 tooltip on column header (FREE only).
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined( 'ABSPATH' ) || exit;

class Order_Columns {

	/**
	 * Register hooks.
	 */
	public function register_hooks(): void {
		// HPOS: works on both shop_order and woocommerce_page_wc-orders screens.
		add_filter( 'manage_edit-shop_order_columns',              array( $this, 'add_columns' ) );
		add_filter( 'manage_woocommerce_page_wc-orders_columns',   array( $this, 'add_columns' ) );
		add_action( 'manage_shop_order_posts_custom_column',       array( $this, 'render_column' ), 10, 2 );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $this, 'render_column' ), 10, 2 );
	}

	/**
	 * Add the Event Status column.
	 *
	 * Placed between "order_status" and "order_date" for maximum visibility.
	 * FREE: shows 🔒 upsell tooltip on column header (WP.org compliant).
	 *
	 * @param array $columns Existing WC order columns.
	 * @return array Modified columns.
	 */
	public function add_columns( array $columns ): array {
		$new = array();

		// Build header label. FREE gets a lock icon with tooltip.
		$label = __( 'Event Status', 'capiflow' );
		if ( ! License_Manager::is_pro_active() ) {
			$label .= ' <span class="capiflow-pro-hint" title="'
				. esc_attr__( 'Unlock AI Risk Detection & Courier Sync — CapiFlow Pro', 'capiflow' )
				. '" style="cursor:help;font-size:10px;">🔒</span>';
		}

		foreach ( $columns as $key => $col_label ) {
			$new[ $key ] = $col_label;
			if ( 'order_status' === $key ) {
				$new['capiflow_event_status'] = $label;
			}
		}

		// Fallback: if order_status column not found, append.
		if ( ! isset( $new['capiflow_event_status'] ) ) {
			$new['capiflow_event_status'] = $label;
		}

		return $new;
	}

	/**
	 * Render the Event Status column cell.
	 *
	 * Shows CAPI sync status only (✅⏳❌—).
	 * Outputs data-capi-status attribute for JS row-border coloring.
	 *
	 * @param string         $column      Column key.
	 * @param int|\WC_Order  $order_or_id Order ID (legacy) or WC_Order (HPOS).
	 */
	public function render_column( string $column, $order_or_id ): void {
		if ( 'capiflow_event_status' !== $column ) {
			return;
		}

		$order = $order_or_id instanceof \WC_Order
			? $order_or_id
			: wc_get_order( $order_or_id );

		if ( ! $order instanceof \WC_Order ) {
			echo '<span style="color:#9ca3af;">—</span>';
			return;
		}

		// ── Sync status (DB-backed — reads from queue table) ────────────────
		$db_events    = DB_Manager::get_events_by_order( $order->get_id() );
		$purchase_row = null;

		foreach ( $db_events as $ev ) {
			if ( 'Purchase' === $ev->event_name ) {
				$purchase_row = $ev;
				break;
			}
		}

		if ( $purchase_row ) {
			switch ( $purchase_row->status ) {
				case 'sent':
					$icon  = '✅';
					$class = 'sent';
					$label = __( 'Sent', 'capiflow' );
					break;
				case 'pending':
				case 'processing':
					$icon  = '⏳';
					$class = 'queued';
					$label = __( 'Queued', 'capiflow' );
					break;
				case 'failed':
					$icon  = '❌';
					$class = 'failed';
					$label = sprintf(
						/* translators: %d: retry count */
						__( 'Failed (%d retries)', 'capiflow' ),
						(int) $purchase_row->retry_count
					);
					break;
				default:
					$icon  = '⏳';
					$class = 'queued';
					$label = __( 'Queued', 'capiflow' );
			}
		} else {
			// Fallback: check meta (for events before queue table existed).
			$purchase_sent = $order->get_meta( '_capiflow_purchase_sent', true );
			if ( ! empty( $purchase_sent ) ) {
				$icon  = '⏳';
				$class = 'queued';
				$label = __( 'Queued', 'capiflow' );
			} else {
				$icon  = '—';
				$class = 'pending';
				$label = __( 'N/A', 'capiflow' );
			}
		}

		// ── Render ───────────────────────────────────────────────────────────
		printf(
			'<span class="capiflow-event-status capiflow-es-%s" data-capi-status="%s">%s %s</span>',
			esc_attr( $class ),
			esc_attr( $class ),
			esc_html( $icon ),
			esc_html( $label )
		);
	}
}
