<?php
/**
 * ActiveTrail Product Feed Template
 *
 * @package ActiveTrail_WooCommerce
 * @since 1.0.0
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Initialize logger if available
$activetrail_logger = function_exists( 'activetrail_logger' ) ? activetrail_logger() : null;

if ( $activetrail_logger ) {
	$activetrail_logger->product_feed( '🎬 Product feed template started', ActiveTrail_Logger::LEVEL_INFO );
}

// Get export type and format from global variables
$activetrail_export_type = isset( $GLOBALS['activetrail_export_type'] ) ? $GLOBALS['activetrail_export_type'] : 'google';
$activetrail_feed_format = isset( $GLOBALS['activetrail_feed_format'] ) ? $GLOBALS['activetrail_feed_format'] : 'xml';

if ( $activetrail_logger ) {
	$activetrail_logger->product_feed(
		'📋 Export type and format determined',
		ActiveTrail_Logger::LEVEL_DEBUG,
		array(
			'export_type'    => $activetrail_export_type,
			'feed_format'    => $activetrail_feed_format,
			'global_var_set' => isset( $GLOBALS['activetrail_export_type'] ),
		)
	);
}

// Initialize the feed generator
if ( ! class_exists( 'ActiveTrail_Product_Feed_Generator' ) ) {
	if ( $activetrail_logger ) {
		$activetrail_logger->product_feed(
			'📦 Loading Product Feed Generator class',
			ActiveTrail_Logger::LEVEL_DEBUG,
			array(
				'class_file' => ACTIVETRAIL_WC_PLUGIN_DIR . 'includes/class-product-feed-generator.php',
			)
		);
	}
	require_once ACTIVETRAIL_WC_PLUGIN_DIR . 'includes/class-product-feed-generator.php';
} elseif ( $activetrail_logger ) {
	$activetrail_logger->product_feed( '✅ Product Feed Generator class already loaded', ActiveTrail_Logger::LEVEL_DEBUG );
}

if ( $activetrail_logger ) {
	$activetrail_logger->product_feed( '🏭 Creating feed generator instance', ActiveTrail_Logger::LEVEL_DEBUG );
}

$activetrail_feed_generator = new ActiveTrail_Product_Feed_Generator();

if ( $activetrail_logger ) {
	$activetrail_logger->product_feed(
		'🚀 Starting feed generation',
		ActiveTrail_Logger::LEVEL_INFO,
		array(
			'export_type' => $activetrail_export_type,
		)
	);
}

// Generate and output the appropriate feed based on format and export_type
try {
	if ( $activetrail_feed_format === 'xml' ) {
		if ( $activetrail_logger ) {
			$activetrail_logger->product_feed(
				'🔄 Generating XML feed',
				ActiveTrail_Logger::LEVEL_INFO,
				array(
					'export_type' => $activetrail_export_type,
				)
			);
		}
		// Use different XML generators for Google and Facebook
		if ( $activetrail_export_type === 'google' ) {
			$activetrail_feed_content = $activetrail_feed_generator->generate_google_xml();
		} else {
			// Facebook uses standard RSS 2.0 without Google namespace
			$activetrail_feed_content = $activetrail_feed_generator->generate_facebook_xml();
		}

		if ( $activetrail_logger ) {
			$activetrail_logger->product_feed(
				'✅ XML feed generated successfully',
				ActiveTrail_Logger::LEVEL_INFO,
				array(
					'export_type'     => $activetrail_export_type,
					'content_length'  => strlen( $activetrail_feed_content ),
					'content_preview' => substr( $activetrail_feed_content, 0, 200 ) . '...',
				)
			);
		}

		// Store XML feed content for controller to output (controller handles headers and output).
		// Do not echo here - controller will output with proper headers.
		$GLOBALS['activetrail_feed_output'] = $activetrail_feed_content;
	} else {
		// Fallback to JSON if format is explicitly set to json (should not happen in normal flow)
		if ( $activetrail_logger ) {
			$activetrail_logger->product_feed(
				'🔄 Generating JSON feed',
				ActiveTrail_Logger::LEVEL_INFO,
				array(
					'export_type' => $activetrail_export_type,
				)
			);
		}
		$activetrail_feed_content = $activetrail_feed_generator->generate_facebook_json();

		if ( $activetrail_logger ) {
			$activetrail_logger->product_feed(
				'✅ JSON feed generated successfully',
				ActiveTrail_Logger::LEVEL_INFO,
				array(
					'export_type'     => $activetrail_export_type,
					'content_length'  => strlen( $activetrail_feed_content ),
					'content_preview' => substr( $activetrail_feed_content, 0, 200 ) . '...',
				)
			);
		}

		// Store JSON feed content for controller to output (controller handles headers and output).
		// Do not echo here - controller will output with proper headers.
		$GLOBALS['activetrail_feed_output'] = $activetrail_feed_content;
	}

	if ( $activetrail_logger ) {
		$activetrail_logger->product_feed(
			'🎉 Feed template completed successfully',
			ActiveTrail_Logger::LEVEL_INFO,
			array(
				'export_type' => $activetrail_export_type,
			)
		);
	}
} catch ( Exception $e ) {
	if ( $activetrail_logger ) {
		$activetrail_logger->product_feed(
			'💥 Exception occurred during feed generation',
			ActiveTrail_Logger::LEVEL_ERROR,
			array(
				'error_message' => $e->getMessage(),
				'error_file'    => $e->getFile(),
				'error_line'    => $e->getLine(),
				'export_type'   => $activetrail_export_type,
			)
		);
	}

	// Store error output for controller to handle.
	if ( $activetrail_feed_format === 'xml' ) {
		$GLOBALS['activetrail_feed_output'] = '<?xml version="1.0" encoding="UTF-8"?><error>Feed generation failed: ' . esc_html( $e->getMessage() ) . '</error>';
	} else {
		$activetrail_wc_error_data = array(
			'success'   => false,
			'error'     => 'Feed generation failed: ' . esc_html( $e->getMessage() ),
			'timestamp' => current_time( 'c' ),
		);
		$GLOBALS['activetrail_feed_output'] = wp_json_encode( $activetrail_wc_error_data );
		$GLOBALS['activetrail_feed_error']   = true;
	}
} catch ( Error $e ) {
	if ( $activetrail_logger ) {
		$activetrail_logger->product_feed(
			'💥 Fatal error occurred during feed generation',
			ActiveTrail_Logger::LEVEL_ERROR,
			array(
				'error_message' => $e->getMessage(),
				'error_file'    => $e->getFile(),
				'error_line'    => $e->getLine(),
				'export_type'   => $activetrail_export_type,
				'feed_format'   => $activetrail_feed_format,
			)
		);
	}

	// Store error output for controller to handle.
	if ( $activetrail_feed_format === 'xml' ) {
		$GLOBALS['activetrail_feed_output'] = '<?xml version="1.0" encoding="UTF-8"?><error>Fatal error: ' . esc_html( $e->getMessage() ) . '</error>';
	} else {
		$activetrail_wc_error_data = array(
			'success'   => false,
			'error'     => 'Fatal error: ' . esc_html( $e->getMessage() ),
			'timestamp' => current_time( 'c' ),
		);
		$GLOBALS['activetrail_feed_output'] = wp_json_encode( $activetrail_wc_error_data );
		$GLOBALS['activetrail_feed_error']   = true;
	}
}
