<?php

/**
 * WPPFM Product Feed Manager Page Class.
 *
 * @package WP Product Feed Manager/User Interface/Classes
 */

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

if ( ! class_exists( 'WPPFM_Feed_Editor_Page' ) ) :

	/**
	 * Feed Editor Form Class
	 *
	 * @since 3.2.0
	 */
	class WPPFM_Feed_Editor_Page {

		/**
		 * @var string|null contains the feed id, null for a new feed.
		 */
		private $_feed_id;

		/**
		 * @var array|null  contains the feed data.
		 */
		private $_feed_data;

		/** @noinspection PhpVoidFunctionResultUsedInspection */
		public function __construct() {

			wppfm_check_db_version();

			$this->_feed_id = wppfm_get_url_parameter( 'id' );

			$this->set_feed_data();

			add_option( 'wp_enqueue_scripts', WPPFM_i18n_Scripts::wppfm_feed_settings_i18n() );
			add_option( 'wp_enqueue_scripts', WPPFM_i18n_Scripts::wppfm_list_table_i18n() );
		}

		/**
		 * Generates the main part of the Feed Editor page.
		 *
		 * @since 3.2.0
		 */
		public function display() {
			$this->add_data_storage();
			$this->feed_editor_page();
		}

		/**
		 * Renders the edit Google Product Feed form page and displays it on the screen.
		 */
		private function feed_editor_page() {
			echo '<div class="wppfm-page__title" id="wppfm-edit-feed-title"><h1>' . esc_html__( 'Product Feed Editor', 'wp-product-feed-manager' ) . '</h1></div>';
			$this->sub_title();
			echo '</div>';


			echo '<div class="wppfm-feed-editor-wrapper">';

			$this->main_input_table_wrapper();

			$this->category_selector_table_wrapper();

			$this->feed_top_buttons();

			$this->attribute_mapping_table_wrapper();

			$this->google_analytics_table_wrapper();

			$this->feed_bottom_buttons();

			echo '</div>';

		}

		/**
		 * Fetches feed data from the database and stores it in the _feed_data variable. This data is required to build the edit feed page. Stores empty
		 * data when the page is opened for a new feed.
		 */
		private function set_feed_data() {
			$feed_data       = null;
			$feed_filter     = '';
			$source_fields   = array();
			$attribute_data  = array();
			$performance_meta = array();
			$queries_class   = null;

			if ( $this->_feed_id ) {
				$queries_class = new WPPFM_Queries();
				$data_class    = new WPPFM_Data();
				$feed_rows     = $queries_class->read_feed( $this->_feed_id );
				$feed_data     = ! empty( $feed_rows ) ? $feed_rows[0] : null;

				// Fallback when the joined read fails but the feed row still exists.
				if ( ! $feed_data ) {
					$feed_data = $this->build_feed_data_from_feed_row( $queries_class->get_feed_row( $this->_feed_id ) );
				}

				$channel_id = $this->resolve_feed_channel_id( $feed_data );
				$feed_type  = $feed_data ? (string) ( $feed_data['feed_type_id'] ?? '1' ) : '1';

				$feed_filter    = $queries_class->get_product_filter_query( $this->_feed_id );
				$source_fields  = $data_class->get_source_fields();
				$attribute_data = $data_class->get_attribute_data( $this->_feed_id, $channel_id, $feed_type );

				if ( $feed_data ) {
					// Verify the categories in the stored category mapping are still active.
					$feed_data['category_mapping'] = $data_class->verify_categories_in_mapping( $feed_data['category_mapping'] ?? '' );
				}

				$performance_meta = $queries_class->get_feed_performance_meta( $this->_feed_id );
			}

			if ( ! is_array( $feed_data ) ) {
				$feed_data = array();
			}

			$this->_feed_data = array(
				'feed_id'             => $this->_feed_id ?: false,
				'feed_file_name'      => $feed_data['title'] ?? '',
				'channel_id'          => $this->resolve_feed_channel_id( $feed_data ),
				'feed_type_id'        => $feed_data['feed_type_id'] ?? '',
				'language'            => $feed_data['language'] ?? '',
				'currency'            => $feed_data['currency'] ?? '',
				'target_country'      => $feed_data['country'] ?? '',
				'category_mapping'    => $feed_data['category_mapping'] ?? '',
				'main_category'       => $feed_data['main_category'] ?? '',
				'include_variations'  => $feed_data['include_variations'] ?? '',
				'is_aggregator'       => $feed_data['is_aggregator'] ?? '',
				'aggregator_name'     => $feed_data['aggregator_name'] ?? '',
				'url'                 => $feed_data['url'] ?? '',
				'source'              => $feed_data['source'] ?? '',
				'feed_title'          => $feed_data['feed_title'] ?? '',
				'feed_description'    => $feed_data['feed_description'] ?? '',
				'schedule'            => $feed_data['schedule'] ?? '',
				'status_id'           => $feed_data['status_id'] ?? '',
				'feed_filter'         => $feed_filter ?: null,
				'attribute_data'      => $attribute_data,
				'source_fields'       => $source_fields,
				'google_analytics'    => $feed_data['google_analytics'] ?? 0,
				'wppfm_performance_enabled'            => $performance_meta['wppfm_performance_enabled'] ?? 'false',
				'wppfm_performance_period_days'         => $performance_meta['wppfm_performance_period_days'] ?? '30',
				'wppfm_performance_high_percentage'     => $performance_meta['wppfm_performance_high_percentage'] ?? '20',
				'wppfm_performance_last_update_gmt'     => $performance_meta['wppfm_performance_last_update_gmt'] ?? '',
				'wppfm_performance_last_analyzed_count' => $performance_meta['wppfm_performance_last_analyzed_count'] ?? '',
				'utm_id'              => $feed_data['utm_id'] ?? '',
				'utm_source'          => $feed_data['utm_source'] ?? '',
				'utm_medium'          => $feed_data['utm_medium'] ?? '',
				'utm_campaign'        => $feed_data['utm_campaign'] ?? '',
				'utm_source_platform' => $feed_data['utm_source_platform'] ?? '',
				'utm_term'            => $feed_data['utm_term'] ?? '',
				'utm_content'         => $feed_data['utm_content'] ?? '',
			);
		}

		/**
		 * Resolves the channel id used by the Feed Editor JavaScript.
		 *
		 * @param array|null $feed_data Feed row from read_feed() or the fallback builder.
		 *
		 * @return string
		 */
		private function resolve_feed_channel_id( $feed_data ) {
			if ( ! is_array( $feed_data ) ) {
				return '1';
			}

			$channel_id = $feed_data['channel'] ?? $feed_data['feed_channel_id'] ?? $feed_data['channel_id'] ?? '';

			if ( null === $channel_id || '' === (string) $channel_id ) {
				return '1';
			}

			return (string) $channel_id;
		}

		/**
		 * Builds a minimal feed data array from a raw product feed row.
		 *
		 * @param object|null $feed_row Raw feedmanager_product_feed row.
		 *
		 * @return array|null
		 */
		private function build_feed_data_from_feed_row( $feed_row ) {
			if ( ! $feed_row ) {
				return null;
			}

			$country_code = '';
			if ( ! empty( $feed_row->country_id ) ) {
				global $wpdb;

				$country_code = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT name_short FROM {$wpdb->prefix}feedmanager_country WHERE country_id = %d",
						$feed_row->country_id
					)
				);

				$country_code = is_string( $country_code ) ? $country_code : '';
			}

			return array(
				'product_feed_id'    => $feed_row->product_feed_id,
				'source'             => $feed_row->source_id,
				'title'              => $feed_row->title,
				'feed_title'         => $feed_row->feed_title,
				'feed_description'   => $feed_row->feed_description,
				'main_category'      => $feed_row->main_category,
				'url'                => $feed_row->url,
				'include_variations' => $feed_row->include_variations,
				'is_aggregator'      => $feed_row->is_aggregator,
				'aggregator_name'    => $feed_row->aggregator_name,
				'status_id'          => $feed_row->status_id,
				'feed_type_id'       => $feed_row->feed_type_id,
				'schedule'           => $feed_row->schedule,
				'google_analytics'   => $feed_row->google_analytics,
				'utm_id'             => $feed_row->utm_id ?? '',
				'utm_source'         => $feed_row->utm_source ?? '',
				'utm_medium'         => $feed_row->utm_medium ?? '',
				'utm_campaign'       => $feed_row->utm_campaign ?? '',
				'utm_source_platform'=> $feed_row->utm_source_platform ?? '',
				'utm_term'           => $feed_row->utm_term ?? '',
				'utm_content'        => $feed_row->utm_content ?? '',
				'feed_channel_id'    => $feed_row->channel_id,
				'channel'            => $feed_row->channel_id,
				'country'            => $country_code,
				'language'           => $feed_row->language,
				'currency'           => $feed_row->currency,
				'category_mapping'   => '',
			);
		}

		/**
		 * Stores data in the DOM for the Feed Manager Feed Editor page.
		 */
		private function add_data_storage() {
			// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- wc_esc_json() is used for proper JSON escaping in data attribute.
			echo
			'<div id="wppfm-feed-editor-page-data-storage" class="wppfm-data-storage-element"
				data-wppfm-feed-data="' . wc_esc_json( wp_json_encode( $this->_feed_data ), false ) . '"
				data-wppfm-ajax-feed-data-to-database-conversion-array=' . esc_attr( wp_json_encode( wppfm_ajax_feed_data_to_database_array( 'product-feed' ) ) ) . '
				data-wppfm-feed-url="' . esc_url( $this->_feed_data['url'] ) . '"
				data-wppfm-all-feed-names="' . esc_attr( implode( ';;',  wppfm_get_all_feed_names() ) ) . '"
				data-wppfm-plugin-version-id="' . esc_attr( WPPFM_PLUGIN_VERSION_ID ) . '" 
				data-wppfm-plugin-version-nr="' . esc_attr( WPPFM_VERSION_NUM ) . '"
				data-wppfm-plugin-distributor="' . esc_attr( WPPFM_PLUGIN_DISTRIBUTOR ) . '"
				data-wppfm-show-product-identifiers="' . esc_attr( get_option( 'wppfm_show_product_identifiers', 'false' ) ) . '">
			</div>';
			// phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
		}

		/**
		 * Gets the Feed Editor subtitle.
		 */
		private function sub_title() {
			WPPFM_Form_Element::feed_editor_sub_title( wppfm_feed_form_sub_header_text() );
		}

		/**
		 * The main input table.
		 */
		private function main_input_table_wrapper() {
			$main_input_wrapper = new WPPFM_Product_Feed_Main_Input_Wrapper();
			$main_input_wrapper->display();
		}

		/**
		 * The category mapping table.
		 */
		private function category_selector_table_wrapper() {
			$category_table_wrapper = new WPPFM_Product_Feed_Category_Wrapper();
			$category_table_wrapper->display();
		}

		/**
		 * Returns the Save & Generate Feed and Save Feed buttons at the top of the attribute list.
		 */
		private function feed_top_buttons() {
			WPPFM_Form_Element::feed_generation_buttons( 'wppfm-top-buttons-wrapper', 'page-top-buttons', 'wppfm-generate-feed-button-top', 'wppfm-save-feed-button-top', 'wppfm-view-feed-button-top', 'block' );
		}

		/**
		 * Returns the Save & Generate Feed and Save Feed buttons at the bottom of the attribute list.
		 */
		private function feed_bottom_buttons() {
			WPPFM_Form_Element::feed_generation_buttons( 'wppfm-center-buttons-wrapper', 'page-center-buttons', 'wppfm-generate-feed-button-bottom', 'wppfm-save-feed-button-bottom', 'wppfm-view-feed-button-bottom' );
		}

		/**
		 * Return the attribute mapping table.
		 */
		private function attribute_mapping_table_wrapper() {
			$attribute_mapping_wrapper = new WPPFM_Product_Feed_Attribute_Mapping_Wrapper();
			$attribute_mapping_wrapper->display();
		}

		/**
		 * Returns the Google Analytics table.
		 */
		private function google_analytics_table_wrapper() {
			$google_analytics_wrapper = new WPPFM_Product_Feed_Google_Analytics_Wrapper();
			$google_analytics_wrapper->display();
		}
	}

	// end of WPPFM_Feed_Editor_Page class

endif;
