<?php
/**
 * Order Metabox — CAPI Event timeline + Manual Send Purchase button.
 *
 * HPOS-compatible: registers on shop_order post type AND wc-orders page.
 * Shows: purchase sent status, browser pixel dedup, context data, queue status.
 * Pro extensibility via capiflow_order_metabox_after action.
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined( 'ABSPATH' ) || exit;

class Order_Metabox {

	/**
	 * Register hooks.
	 */
	public function register_hooks(): void {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
	}

	/**
	 * Add CapiFlow metabox to order edit screens (HPOS + legacy).
	 */
	public function add_meta_boxes(): void {
		// HPOS-safe screen detection.
		if ( function_exists( 'wc_get_container' ) ) {
			try {
				$hpos_enabled = wc_get_container()
					->get( \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class )
					->custom_orders_table_usage_is_enabled();
				$screen = $hpos_enabled
					? wc_get_page_screen_id( 'shop-order' )
					: 'shop_order';
			} catch ( \Exception $e ) {
				$screen = 'shop_order';
			}
		} else {
			$screen = 'shop_order';
		}

		add_meta_box(
			'capiflow-event-timeline',
			__( '⚡ CapiFlow Events', 'capiflow' ),
			array( $this, 'render_metabox' ),
			$screen,
			'side',
			'default'
		);
	}

	/**
	 * Render the metabox content.
	 *
	 * @param \WP_Post|\WC_Order $post_or_order Post or Order object.
	 */
	public function render_metabox( $post_or_order ): void {
		$order = ( $post_or_order instanceof \WC_Order )
			? $post_or_order
			: wc_get_order( $post_or_order->ID );

		if ( ! $order ) {
			echo '<p>' . esc_html__( 'Order not found.', 'capiflow' ) . '</p>';
			return;
		}

		$order_id = $order->get_id();

		// ── Meta data ────────────────────────────────────────────────────────
		$purchase_sent = $order->get_meta( '_capiflow_purchase_sent', true );
		$event_id      = $order->get_meta( '_capiflow_purchase_event_id', true );
		$pixel_id      = $order->get_meta( '_capiflow_pixel_id', true );
		$pixel_fired   = $order->get_meta( '_capiflow_pixel_fired', true );


		// ── Timeline entries ─────────────────────────────────────────────────
		$timeline = array();

		if ( ! empty( $purchase_sent ) ) {
			$timeline[] = array(
				'icon'  => '✅',
				'label' => __( 'Purchase Queued', 'capiflow' ),
				'time'  => $purchase_sent,
				'meta'  => 'Event ID: ' . ( $event_id ?: 'N/A' ),
			);
		}

		if ( ! empty( $pixel_fired ) ) {
			$timeline[] = array(
				'icon'  => '🌐',
				'label' => __( 'Browser Pixel Fired', 'capiflow' ),
				'time'  => '',
				'meta'  => __( 'Dedup: Matching event_id', 'capiflow' ),
			);
		}

		// Pro hook: negative events, multi-pixel details etc.
		$timeline = apply_filters( 'capiflow_metabox_timeline', $timeline, $order );

		// ── Queue events from DB (for this order) ────────────────────────────
		$db_events = DB_Manager::get_events_for_order( $order_id );

		// ── Render ───────────────────────────────────────────────────────────
		echo '<div class="capiflow-timeline" style="font-size:12px;">';

		if ( empty( $timeline ) && empty( $db_events ) ) {
			echo '<p style="color:#999;font-style:italic;margin:4px 0;">'
				. esc_html__( 'No CAPI events yet for this order.', 'capiflow' )
				. '</p>';
		}

		// Meta data timeline.
		foreach ( $timeline as $entry ) {
			echo '<div style="display:flex;gap:8px;align-items:flex-start;padding:5px 0;border-bottom:1px solid #f3f4f6;">';
			echo '<span style="font-size:14px;flex-shrink:0;">' . esc_html( $entry['icon'] ) . '</span>';
			echo '<div>';
			echo '<strong>' . esc_html( $entry['label'] ) . '</strong>';
			if ( ! empty( $entry['time'] ) ) {
				echo '<br><small style="color:#9ca3af;">' . esc_html( $entry['time'] ) . '</small>';
			}
			if ( ! empty( $entry['meta'] ) ) {
				echo '<br><code style="font-size:10px;background:#f3f4f6;padding:1px 4px;border-radius:3px;">' . esc_html( $entry['meta'] ) . '</code>';
			}
			echo '</div></div>';
		}

		// Queue events from DB.
		if ( ! empty( $db_events ) ) {
			echo '<div style="margin-top:8px;font-size:11px;color:#6b7280;font-weight:600;text-transform:uppercase;letter-spacing:.4px;">Queue</div>';
			foreach ( $db_events as $ev ) {
				$status_icon  = 'sent'   === $ev->status ? '✅' : ( 'failed' === $ev->status ? '❌' : '⏳' );
				$status_color = 'sent'   === $ev->status ? '#16a34a' : ( 'failed' === $ev->status ? '#dc2626' : '#f59e0b' );
				echo '<div style="display:flex;justify-content:space-between;padding:3px 0;border-bottom:1px solid #f9fafb;">';
				echo '<span>' . esc_html( $status_icon . ' ' . $ev->event_name ) . '</span>';
				echo '<span style="color:' . esc_attr( $status_color ) . ';">' . esc_html( $ev->status );
				if ( $ev->http_code ) {
					echo ' <code style="font-size:9px;background:#f3f4f6;padding:0 3px;">' . esc_html( $ev->http_code ) . '</code>';
				}
				echo '</span></div>';
			}
		}

		echo '</div>';



		// ── Context Data ─────────────────────────────────────────────────────
		echo '<hr style="margin:8px 0;">';
		echo '<details style="font-size:11px;">';
		echo '<summary style="cursor:pointer;color:#6b7280;">📋 ' . esc_html__( 'Captured Context', 'capiflow' ) . '</summary>';
		echo '<table style="font-size:11px;width:100%;margin-top:5px;border-collapse:collapse;">';

		$context_fields = array(
			'_capiflow_client_ip'      => 'Client IP',
			'_capiflow_user_agent'     => 'User Agent',
			'_capiflow_fbc'            => '_fbc',
			'_capiflow_fbp'            => '_fbp',
			'_capiflow_external_id'    => 'External ID',
			'_capiflow_traffic_source' => 'Traffic Source',
		);

		// Payment method (from order, not meta — always available).
		$payment_method = $order->get_payment_method_title();
		if ( ! empty( $payment_method ) ) {
			$cod_gate = (bool) apply_filters( 'capiflow_cod_gate_enabled', true );
			$is_cod   = 'cod' === $order->get_payment_method();
			$pm_label = $payment_method;
			if ( $is_cod && $cod_gate ) {
				$pm_label .= ' 🔒 COD Gate';
			}
			echo '<tr>';
			echo '<td style="color:#9ca3af;padding:2px 4px;">' . esc_html__( 'Payment', 'capiflow' ) . '</td>';
			echo '<td><code style="font-size:10px;background:#f3f4f6;padding:0 4px;border-radius:2px;">' . esc_html( $pm_label ) . '</code></td>';
			echo '</tr>';
		}

		foreach ( $context_fields as $meta_key => $label ) {
			$value = $order->get_meta( $meta_key, true );
			echo '<tr>';
			echo '<td style="color:#9ca3af;padding:2px 4px;">' . esc_html( $label ) . '</td>';
			echo '<td><code style="font-size:10px;background:#f3f4f6;padding:0 4px;border-radius:2px;">' . esc_html( $value ?: '—' ) . '</code></td>';
			echo '</tr>';
		}

		if ( ! empty( $pixel_id ) ) {
			echo '<tr><td style="color:#9ca3af;padding:2px 4px;">Pixel</td>';
			echo '<td><code style="font-size:10px;background:#f3f4f6;padding:0 4px;border-radius:2px;">' . esc_html( $pixel_id ) . '</code></td></tr>';
		}

		echo '</table></details>';

		// ── EMQ Readiness ────────────────────────────────────────────────────
		echo '<details style="font-size:11px;margin-top:4px;">';
		echo '<summary style="cursor:pointer;color:#6b7280;">📊 ' . esc_html__( 'EMQ Readiness', 'capiflow' ) . '</summary>';

		// Event ID.
		$evt_id_display = ! empty( $event_id ) ? $event_id : '—';
		echo '<div style="margin-top:4px;padding:3px 0;border-bottom:1px solid #f3f4f6;">';
		echo '<span style="color:#9ca3af;font-size:10px;">Event ID:</span> ';
		echo '<code style="font-size:9px;background:#f3f4f6;padding:0 4px;border-radius:2px;word-break:break-all;">' . esc_html( $evt_id_display ) . '</code>';
		echo '</div>';

		// EMQ Parameter Checklist — these are what Meta uses for user matching.
		$emq_params = array(
			array( 'em',  'Email',      ! empty( $order->get_billing_email() ) ),
			array( 'ph',  'Phone',      ! empty( $order->get_billing_phone() ) ),
			array( 'fn',  'First Name', ! empty( $order->get_billing_first_name() ) ),
			array( 'ln',  'Last Name',  ! empty( $order->get_billing_last_name() ) ),
			array( 'ct',  'City',       ! empty( $order->get_billing_city() ) ),
			array( 'st',  'State',      ! empty( $order->get_billing_state() ) ),
			array( 'zp',  'Zip',        ! empty( $order->get_billing_postcode() ) ),
			array( 'country', 'Country', ! empty( $order->get_billing_country() ) ),
			array( 'ip',  'Client IP',  ! empty( $order->get_meta( '_capiflow_client_ip', true ) ) ),
			array( 'ua',  'User Agent', ! empty( $order->get_meta( '_capiflow_user_agent', true ) ) ),
			array( 'fbp', '_fbp',       ! empty( $order->get_meta( '_capiflow_fbp', true ) ) ),
			array( 'fbc', '_fbc',       ! empty( $order->get_meta( '_capiflow_fbc', true ) ) ),
			array( 'eid', 'External ID', ! empty( $order->get_meta( '_capiflow_external_id', true ) ) ),
		);

		$available = 0;
		$total     = count( $emq_params );

		echo '<div style="margin-top:4px;display:flex;flex-wrap:wrap;gap:2px 8px;">';
		foreach ( $emq_params as $param ) {
			$icon   = $param[2] ? '✅' : '❌';
			$color  = $param[2] ? '#16a34a' : '#dc2626';
			$available += $param[2] ? 1 : 0;
			echo '<span style="font-size:10px;color:' . esc_attr( $color ) . ';" title="' . esc_attr( $param[0] ) . '">'
				. esc_html( $icon . ' ' . $param[1] ) . '</span>';
		}
		echo '</div>';

		// EMQ Score Estimate.
		$emq_score = round( ( $available / $total ) * 10, 1 );
		$emq_color = $emq_score >= 8 ? '#16a34a' : ( $emq_score >= 6 ? '#f59e0b' : '#dc2626' );
		echo '<div style="margin-top:4px;font-size:10px;color:' . esc_attr( $emq_color ) . ';font-weight:600;">';
		/* translators: 1: EMQ score, 2: available params, 3: total params */
		echo sprintf( esc_html__( 'Estimated EMQ: %1$s/10 (%2$d/%3$d params)', 'capiflow' ), esc_html( $emq_score ), intval( $available ), intval( $total ) );

		// Note for _fbc.
		if ( empty( $order->get_meta( '_capiflow_fbc', true ) ) ) {
			echo '<br><span style="font-weight:400;color:#9ca3af;">' . esc_html__( 'ℹ️ _fbc is only set for Facebook ad click traffic', 'capiflow' ) . '</span>';
		}
		echo '</div>';

		echo '</details>';

		// ── Pro extensibility hook (after timeline + context, before button) ──
		// Pro modules (Negative Events, Fraud Gate, Courier) inject here.
		do_action( 'capiflow_order_metabox_after_timeline', $order );

		// ── Pro Teaser Cards (free version only — WP.org compliant) ──────────
		// Note: No pricing shown on WC core pages per WP.org Rule 11.
		if ( ! License_Manager::is_pro_active() ) :
			echo '<hr style="margin:10px 0;">';
			echo '<div class="capiflow-pro-teaser" style="padding:10px;font-size:11px;">';
			echo '<div style="font-weight:700;margin-bottom:6px;color:#78350f;">🔒 '
				. esc_html__( 'CapiFlow Pro Features', 'capiflow' ) . '</div>';
			echo '<div style="color:#78350f;line-height:1.8;">';
			echo '🚚 ' . esc_html__( 'Auto-Dispatch to Courier', 'capiflow' ) . '<br>';
			echo '🧠 ' . esc_html__( 'AI Risk Detection', 'capiflow' ) . '<br>';
			echo '📲 ' . esc_html__( 'OTP Verification', 'capiflow' ) . '<br>';
			echo '📉 ' . esc_html__( 'Negative Event Tracking', 'capiflow' );
			echo '</div>';
			echo '<a href="' . esc_url( admin_url( 'admin.php?page=capiflow-settings' ) ) . '" '
				. 'style="display:inline-block;margin-top:8px;font-size:11px;color:#1d4ed8;">'
				. esc_html__( 'Learn More →', 'capiflow' ) . '</a>';
			echo '</div>';
		endif;

		// ── Backwards-compat hook (keep for Pro modules hooked here already) ─
		do_action( 'capiflow_order_metabox_after', $order );

		// ── Manual Send Button ───────────────────────────────────────────────
		echo '<hr style="margin:10px 0;">';
		echo '<button type="button" class="button capiflow-send-purchase" data-order-id="' . esc_attr( $order_id ) . '"';
		echo ' data-nonce="' . esc_attr( wp_create_nonce( 'capiflow_admin' ) ) . '"';
		echo ' style="width:100%;">';
		echo esc_html( empty( $purchase_sent ) ? __( '🚀 Send Purchase', 'capiflow' ) : __( '🔄 Re-send Purchase', 'capiflow' ) );
		echo '</button>';
		echo '<span class="capiflow-send-result" style="font-size:11px;display:block;margin-top:4px;"></span>';
	}
}
