<?php
/**
 * Order Confirmation Widget - Render Functions
 *
 * Standalone functions used by GGM_Commerce_Widget_Order_Confirmation.
 * Prefix: ggmc_order_confirmation_
 *
 * @package GGM_Commerce
 */

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

/**
 * Get sample order data for editor preview.
 *
 * @return object Sample order object.
 */
function ggmc_order_confirmation_get_sample_order() {
	return (object) [
		'id'                  => 12345,
		'order_number'        => 'GGM-12345',
		'status'              => 'processing',
		'payment_status'      => 'paid',
		'payment_method'      => 'stripe',
		'created_at'          => gmdate( 'Y-m-d H:i:s' ),
		'customer_first_name' => 'John',
		'customer_last_name'  => 'Doe',
		'customer_email'      => 'john.doe@example.com',
		'billing_address_1'   => '123 Main Street',
		'billing_address_2'   => 'Apt 4B',
		'billing_city'        => 'London',
		'billing_state'       => 'Greater London',
		'billing_postcode'    => 'SW1A 1AA',
		'billing_country'     => 'United Kingdom',
		'shipping_address_1'  => '123 Main Street',
		'shipping_address_2'  => 'Apt 4B',
		'shipping_city'       => 'London',
		'shipping_state'      => 'Greater London',
		'shipping_postcode'   => 'SW1A 1AA',
		'shipping_country'    => 'United Kingdom',
		'subtotal'            => 149.97,
		'tax_amount'          => 30.00,
		'tax_label'           => 'VAT',
		'shipping_amount'     => 9.99,
		'shipping_method_name' => 'Standard Delivery',
		'total_amount'        => 189.96,
		'items'               => [
			(object) [
				'product_name'   => 'Premium Widget Pro',
				'product_sku'    => 'WIDGET-001',
				'variation_data' => 'Size: Large, Color: Blue',
				'quantity'       => 2,
				'price'          => 49.99,
				'total'          => 99.98,
			],
			(object) [
				'product_name'   => 'Deluxe Gadget',
				'product_sku'    => 'GADGET-002',
				'variation_data' => '',
				'quantity'       => 1,
				'price'          => 49.99,
				'total'          => 49.99,
			],
		],
	];
}

/**
 * Generate a secure order key.
 *
 * @param object $order Order object.
 * @return string Secure order key.
 */
function ggmc_order_confirmation_generate_order_key( $order ) {
	$data = $order->id . $order->order_number . $order->customer_email . $order->created_at;
	return wp_hash( $data, 'ggmc_order_key' );
}

/**
 * Get order from URL request parameters.
 * Validates the order key for security.
 *
 * @return object|null Order object or null if not found/invalid.
 */
function ggmc_order_confirmation_get_order_from_request() {
	// Check for order_id and key parameters.
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public page, key provides security
	$order_id = isset( $_GET['order_id'] ) ? absint( $_GET['order_id'] ) : 0;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$order_key = isset( $_GET['key'] ) ? sanitize_text_field( wp_unslash( $_GET['key'] ) ) : '';

	if ( ! $order_id || ! $order_key ) {
		return null;
	}

	// Get order.
	if ( ! class_exists( 'GGM_Commerce_Orders' ) ) {
		return null;
	}

	$orders = GGM_Commerce_Orders::get_instance();
	$order  = $orders->get_order( $order_id );

	if ( ! $order ) {
		return null;
	}

	// Validate order key.
	$expected_key = ggmc_order_confirmation_generate_order_key( $order );
	if ( ! hash_equals( $expected_key, $order_key ) ) {
		return null;
	}

	return $order;
}

/**
 * Render SVG icon by type.
 *
 * @param string $icon_type Icon type identifier.
 * @param string $category  Icon category ('success' or 'error').
 */
function ggmc_order_confirmation_render_svg_icon( $icon_type, $category = 'success' ) {
	$success_icons = [
		'checkmark-circle' => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>',
		'checkmark-badge'  => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z"/><path d="m9 12 2 2 4-4"/></svg>',
		'checkmark-simple' => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>',
		'shopping-bag'     => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>',
		'gift'             => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="8" width="18" height="4" rx="1"/><path d="M12 8v13"/><path d="M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"/><path d="M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"/></svg>',
		'heart'            => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/></svg>',
		'star'             => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>',
		'thumbs-up'        => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z"/></svg>',
	];

	$error_icons = [
		'warning'  => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>',
		'error'    => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>',
		'question' => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>',
		'search'   => '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
	];

	if ( 'error' === $category ) {
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG is hardcoded
		echo $error_icons[ $icon_type ] ?? $error_icons['warning'];
	} else {
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG is hardcoded
		echo $success_icons[ $icon_type ] ?? $success_icons['checkmark-circle'];
	}
}

/**
 * Render the success icon based on settings.
 *
 * @param array $settings Widget settings.
 */
function ggmc_order_confirmation_render_success_icon( $settings ) {
	if ( $settings['show_success_icon'] !== 'yes' ) {
		return;
	}

	$icon_type = $settings['success_icon_type'] ?? 'checkmark-circle';

	echo '<div class="ggmc-order-confirmation-icon">';

	if ( 'custom' === $icon_type && ! empty( $settings['success_custom_icon']['value'] ) ) {
		ggmc_render_icon( $settings['success_custom_icon'], [ 'aria-hidden' => 'true' ] );
	} else {
		ggmc_order_confirmation_render_svg_icon( $icon_type, 'success' );
	}

	echo '</div>';
}

/**
 * Render the no order found icon based on settings.
 *
 * @param array $settings Widget settings.
 */
function ggmc_order_confirmation_render_no_order_icon( $settings ) {
	$icon_type = $settings['no_order_icon_type'] ?? 'warning';

	echo '<div class="ggmc-order-not-found-icon">';

	if ( 'custom' === $icon_type && ! empty( $settings['no_order_custom_icon']['value'] ) ) {
		ggmc_render_icon( $settings['no_order_custom_icon'], [ 'aria-hidden' => 'true' ] );
	} else {
		ggmc_order_confirmation_render_svg_icon( $icon_type, 'error' );
	}

	echo '</div>';
}

/**
 * Main render function for the Order Confirmation widget.
 *
 * @param GGM_Commerce_Widget_Order_Confirmation $widget Widget instance.
 */
function ggmc_order_confirmation_render( $widget ) {
	$settings = $widget->get_settings_for_display();

	// Check if we're in editor mode and preview is enabled.
	$is_editor    = ggmc_is_editor_mode();
	$preview_mode = $settings['preview_mode'] ?? 'yes';

	// Get order from URL parameters or use sample data in editor.
	$order = ggmc_order_confirmation_get_order_from_request();

	// If no order and we're in editor with preview mode enabled, use sample data.
	if ( ! $order && $is_editor && 'yes' === $preview_mode ) {
		$order = ggmc_order_confirmation_get_sample_order();
	}

	// Currency symbol.
	$currency_options = get_option( 'ggm_commerce_currency_options', array() );
	$currency_symbol  = isset( $currency_options['symbol'] ) ? $currency_options['symbol'] : '£';

	// Shop page URL.
	$shop_page_id = get_option( 'ggm_commerce_shop_page_id' );
	$shop_url     = $shop_page_id ? get_permalink( $shop_page_id ) : home_url( '/' );

	?>
	<div class="ggmc-order-confirmation">
		<?php if ( $order ) : ?>
			<?php if ( $is_editor && 'yes' === $preview_mode ) : ?>
				<div class="ggmc-editor-notice" style="background: #fff3cd; border: 1px solid #ffc107; padding: 8px 12px; margin-bottom: 16px; border-radius: 4px; font-size: 12px; color: #856404;">
					<strong>Editor Preview:</strong> Displaying sample order data. Disable "Show Sample Data" in Editor Preview settings to see the empty state.
				</div>
			<?php endif; ?>
			<!-- Success Header -->
			<div class="ggmc-order-confirmation-header">
				<?php ggmc_order_confirmation_render_success_icon( $settings ); ?>
				<h1 class="ggmc-order-confirmation-title"><?php echo esc_html( $settings['success_title'] ); ?></h1>
				<p class="ggmc-order-confirmation-message"><?php echo esc_html( $settings['success_message'] ); ?></p>
			</div>

			<!-- Order Overview -->
			<div class="ggmc-order-details-section ggmc-order-overview">
				<?php if ( $settings['show_order_number'] === 'yes' ) : ?>
					<div class="ggmc-order-meta-item">
						<span class="ggmc-order-meta-label"><?php echo esc_html( $settings['label_order_number'] ); ?></span>
						<span class="ggmc-order-meta-value">#<?php echo esc_html( $order->order_number ); ?></span>
					</div>
				<?php endif; ?>

				<?php if ( $settings['show_order_date'] === 'yes' ) : ?>
					<div class="ggmc-order-meta-item">
						<span class="ggmc-order-meta-label"><?php echo esc_html( $settings['label_order_date'] ); ?></span>
						<span class="ggmc-order-meta-value"><?php echo esc_html( gmdate( 'F j, Y', strtotime( $order->created_at ) ) ); ?></span>
					</div>
				<?php endif; ?>

				<?php if ( $settings['show_payment_method'] === 'yes' && ! empty( $order->payment_method ) ) : ?>
					<div class="ggmc-order-meta-item">
						<span class="ggmc-order-meta-label"><?php echo esc_html( $settings['label_payment_method'] ); ?></span>
						<span class="ggmc-order-meta-value"><?php echo esc_html( ucfirst( $order->payment_method ) ); ?></span>
					</div>
				<?php endif; ?>

				<div class="ggmc-order-meta-item">
					<span class="ggmc-order-meta-label"><?php echo esc_html( $settings['label_email'] ); ?></span>
					<span class="ggmc-order-meta-value"><?php echo esc_html( $order->customer_email ); ?></span>
				</div>
			</div>

			<?php if ( $settings['show_order_items'] === 'yes' && ! empty( $order->items ) ) : ?>
				<!-- Order Items -->
				<div class="ggmc-order-details-section ggmc-order-items-section">
					<?php if ( $settings['show_order_items_title'] === 'yes' ) : ?>
						<h3 class="ggmc-order-section-title"><?php echo esc_html( $settings['order_items_title'] ); ?></h3>
					<?php endif; ?>
					<table class="ggmc-order-items-table">
						<thead>
							<tr>
								<th><?php echo esc_html( $settings['label_product'] ); ?></th>
								<th class="text-center"><?php echo esc_html( $settings['label_qty'] ); ?></th>
								<th class="text-right"><?php echo esc_html( $settings['label_price'] ); ?></th>
								<th class="text-right"><?php echo esc_html( $settings['label_total'] ); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ( $order->items as $item ) :
								// Get variation display - use stored data or look up from variation_id.
								$variation_display = '';
								if ( ! empty( $item->variation_data ) ) {
									$variation_display = $item->variation_data;
								} elseif ( ! empty( $item->variation_id ) && class_exists( 'GGM_Commerce_Variations' ) ) {
									// Fallback: look up variation attributes from variation_id.
									$variations_manager = GGM_Commerce_Variations::instance();
									$variation          = $variations_manager->get_variation( $item->variation_id );
									if ( $variation && ! empty( $variation['attributes'] ) ) {
										$attr_parts = [];
										foreach ( $variation['attributes'] as $attr ) {
											$attr_name  = $attr['attribute_name'] ?? $attr['name'] ?? '';
											$attr_value = $attr['attribute_value'] ?? $attr['value'] ?? '';
											if ( ! empty( $attr_name ) && ! empty( $attr_value ) ) {
												$attr_parts[] = $attr_name . ': ' . $attr_value;
											}
										}
										if ( ! empty( $attr_parts ) ) {
											$variation_display = implode( ', ', $attr_parts );
										}
									}
								}
							?>
								<tr>
									<td>
										<span class="ggmc-item-name"><?php echo esc_html( $item->product_name ); ?></span>
										<?php if ( ! empty( $variation_display ) ) : ?>
											<span class="ggmc-item-variation"><?php echo esc_html( $variation_display ); ?></span>
										<?php endif; ?>
										<?php if ( ! empty( $item->product_sku ) ) : ?>
											<span class="ggmc-item-sku"><?php echo esc_html( $item->product_sku ); ?></span>
										<?php endif; ?>
									</td>
									<td class="text-center"><?php echo esc_html( $item->quantity ); ?></td>
									<td class="text-right"><?php echo esc_html( $currency_symbol . number_format( (float) $item->price, 2 ) ); ?></td>
									<td class="text-right"><?php echo esc_html( $currency_symbol . number_format( (float) $item->total, 2 ) ); ?></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				</div>
			<?php endif; ?>

			<?php if ( $settings['show_totals'] === 'yes' ) : ?>
				<!-- Order Totals -->
				<div class="ggmc-order-details-section ggmc-order-totals-section">
					<?php if ( $settings['show_totals_title'] === 'yes' ) : ?>
						<h3 class="ggmc-order-section-title"><?php echo esc_html( $settings['totals_title'] ); ?></h3>
					<?php endif; ?>
					<div class="ggmc-order-totals">
						<div class="ggmc-totals-row">
							<span class="ggmc-totals-label"><?php echo esc_html( $settings['label_subtotal'] ); ?></span>
							<span class="ggmc-totals-value"><?php echo esc_html( $currency_symbol . number_format( (float) $order->subtotal, 2 ) ); ?></span>
						</div>

						<?php if ( ! empty( $order->tax_amount ) && (float) $order->tax_amount > 0 ) : ?>
							<div class="ggmc-totals-row">
								<span class="ggmc-totals-label"><?php echo esc_html( $order->tax_label ?? $settings['label_tax'] ); ?>:</span>
								<span class="ggmc-totals-value"><?php echo esc_html( $currency_symbol . number_format( (float) $order->tax_amount, 2 ) ); ?></span>
							</div>
						<?php endif; ?>

						<?php if ( ! empty( $order->shipping_amount ) || ! empty( $order->shipping_method_name ) ) : ?>
							<div class="ggmc-totals-row">
								<span class="ggmc-totals-label">
									<?php echo ! empty( $order->shipping_method_name ) ? esc_html( $order->shipping_method_name ) : esc_html( $settings['label_shipping'] ); ?>:
								</span>
								<span class="ggmc-totals-value">
									<?php
									if ( (float) $order->shipping_amount > 0 ) {
										echo esc_html( $currency_symbol . number_format( (float) $order->shipping_amount, 2 ) );
									} else {
										echo esc_html( $settings['label_free_shipping'] );
									}
									?>
								</span>
							</div>
						<?php endif; ?>

						<div class="ggmc-totals-row ggmc-totals-total">
							<span class="ggmc-totals-label"><?php echo esc_html( $settings['label_order_total'] ); ?></span>
							<span class="ggmc-totals-value"><?php echo esc_html( $currency_symbol . number_format( (float) $order->total_amount, 2 ) ); ?></span>
						</div>
					</div>
				</div>
			<?php endif; ?>

			<?php if ( $settings['show_billing_address'] === 'yes' || $settings['show_shipping_address'] === 'yes' ) : ?>
				<!-- Addresses -->
				<div class="ggmc-order-addresses">
					<?php if ( $settings['show_billing_address'] === 'yes' ) : ?>
						<div class="ggmc-order-details-section ggmc-address-section">
							<?php if ( $settings['show_billing_address_title'] === 'yes' ) : ?>
								<h3 class="ggmc-order-section-title"><?php echo esc_html( $settings['billing_address_title'] ); ?></h3>
							<?php endif; ?>
							<address class="ggmc-address">
								<?php echo esc_html( trim( ( $order->customer_first_name ?? '' ) . ' ' . ( $order->customer_last_name ?? '' ) ) ); ?><br>
								<?php echo esc_html( $order->billing_address_1 ?? '' ); ?><br>
								<?php if ( ! empty( $order->billing_address_2 ) ) : ?>
									<?php echo esc_html( $order->billing_address_2 ); ?><br>
								<?php endif; ?>
								<?php echo esc_html( $order->billing_city ?? '' ); ?>, <?php echo esc_html( $order->billing_state ?? '' ); ?> <?php echo esc_html( $order->billing_postcode ?? '' ); ?><br>
								<?php echo esc_html( $order->billing_country ?? '' ); ?>
							</address>
						</div>
					<?php endif; ?>

					<?php if ( $settings['show_shipping_address'] === 'yes' && ! empty( $order->shipping_address_1 ) ) : ?>
						<div class="ggmc-order-details-section ggmc-address-section">
							<?php if ( $settings['show_shipping_address_title'] === 'yes' ) : ?>
								<h3 class="ggmc-order-section-title"><?php echo esc_html( $settings['shipping_address_title'] ); ?></h3>
							<?php endif; ?>
							<address class="ggmc-address">
								<?php echo esc_html( trim( ( $order->customer_first_name ?? '' ) . ' ' . ( $order->customer_last_name ?? '' ) ) ); ?><br>
								<?php echo esc_html( $order->shipping_address_1 ); ?><br>
								<?php if ( ! empty( $order->shipping_address_2 ) ) : ?>
									<?php echo esc_html( $order->shipping_address_2 ); ?><br>
								<?php endif; ?>
								<?php echo esc_html( $order->shipping_city ?? '' ); ?>, <?php echo esc_html( $order->shipping_state ?? '' ); ?> <?php echo esc_html( $order->shipping_postcode ?? '' ); ?><br>
								<?php echo esc_html( $order->shipping_country ?? '' ); ?>
							</address>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>

			<?php if ( $settings['show_continue_shopping'] === 'yes' ) : ?>
				<!-- Continue Shopping -->
				<div class="ggmc-order-actions">
					<a href="<?php echo esc_url( $shop_url ); ?>" class="ggmc-continue-shopping-btn">
						<?php echo esc_html( $settings['continue_shopping_text'] ); ?>
					</a>
				</div>
			<?php endif; ?>

		<?php else : ?>
			<!-- No Order Found -->
			<div class="ggmc-order-not-found">
				<?php ggmc_order_confirmation_render_no_order_icon( $settings ); ?>
				<p class="ggmc-order-not-found-message"><?php echo esc_html( $settings['no_order_message'] ); ?></p>
				<a href="<?php echo esc_url( $shop_url ); ?>" class="ggmc-continue-shopping-btn">
					<?php echo esc_html( $settings['continue_shopping_text'] ); ?>
				</a>
			</div>
		<?php endif; ?>
	</div>
	<?php
}
