<?php

/**
 * Main class.
 * copyright Simple Direct Plugins - support@simpledirectplugins.com
 *
 * @author 					Simple Direct Plugins
 * @link					https://simpledirectplugins.com/
 * @since					1.0.0
 * @package					SMATWoo
 *
 */

defined ('ABSPATH') or exit;

if (!class_exists ('SMAT_Core')) :

	#[AllowDynamicProperties]

	Class SMAT_Core {

		public function __construct () {

			$this->register_endpoints();

			add_filter ('woocommerce_account_menu_items', [$this, 'my_account_smat_tabs'], 999, 2);
			add_filter ('woocommerce_endpoint_subscriptions_title', [$this, 'subscriptions_title'], 10, 1); // By his own.
			add_filter ('the_title', [$this, 'change_title'], 10, 1);

			add_action ('init', [$this, 'maybe_flush_rewrite_rules'], 20);
			add_action ('save_post', [$this, 'mark_flush_rewrite'], 10, 3);
			}

		public function register_endpoints () {

			$this->smat_tabs = [];
			$this->core_tabs = get_option ('smat_core_tabs') ?: [];

			foreach (SMAT_CPT::pide_query() as $smat_tab) {

				if (!get_post_meta ($smat_tab->ID, 'smat_is_core', true) && get_field ('smat_active', $smat_tab->ID)) { // Active custom tabs.

					$this->smat_tabs[] = $smat_tab;

					add_rewrite_endpoint ($smat_tab->post_name, EP_ROOT | EP_PAGES);

					add_action ("woocommerce_account_{$smat_tab->post_name}_endpoint", function () use ($smat_tab) {
						echo (wpautop (do_shortcode ($smat_tab->post_content)));
						}, 10);
					}
				}
			}

		public function my_account_smat_tabs ($items, $endpoints) {

			$tabs = [];

			// Pestañas core y pestañas creadas por terceros plugins.
			foreach ($this->core_tabs as $tab_id) {

				if (!get_field ('smat_active', $tab_id))
					continue;

				$endpoint = get_post_meta ($tab_id, 'smat_core_endpoint', true);

				if (isset ($items[$endpoint]) && ($post = get_post ($tab_id)))
					$tabs[$endpoint] = [
						'label'		 => get_the_title ($tab_id) ?: esc_html__('Tab #', 'sdp-my-account-tabs-for-woocommerce') . $tab_id,
						'menu_order' => (int) $post->menu_order,
						];
				}

			// Pestañas personalizadas.
			foreach ($this->smat_tabs as $custom_tab)
				$tabs[$custom_tab->post_name] = [
					'label'		 => $custom_tab->post_title ?: esc_html__('Tab #', 'sdp-my-account-tabs-for-woocommerce') . $custom_tab->ID,
					'menu_order' => (int) $custom_tab->menu_order,
					];
			
			// Ordenamos por menu_order.
			uasort ($tabs, function ($a, $b) {
				return $a['menu_order'] <=> $b['menu_order'];
				});

			// Reconstruimos el array final respetando el formato que WooCommerce espera.
			$sorted_items = [];

			foreach ($tabs as $endpoint => $data)
				$sorted_items[$endpoint] = $data['label'];

			return $sorted_items;
			}

		public function change_title ($title) {

			if (is_admin() || !is_account_page() || !is_main_query() || !in_the_loop())
				return $title;

			global $wp_query;

			$ms_endpoint = get_option ('woocommerce_myaccount_members_area_endpoint', '');

			// Core tabs.
			foreach ($this->core_tabs as $tab_id) {

				$endpoint = get_post_meta ($tab_id, 'smat_core_endpoint', true);

				if ($ms_endpoint !== $endpoint && isset ($wp_query->query_vars[$endpoint])) { // WooCommerce Memberships needs to have control on this.

					if ($post = get_post ($tab_id))
						$title = $post->post_title ? esc_html ($post->post_title) : $title;

					unset ($wp_query->query_vars[$endpoint]); // Otherwise, the sky will fall on our heads.
					}
				}

			// Custom tabs.
			foreach ($this->smat_tabs as $tab) {

				if (isset ($wp_query->query_vars[$tab->post_name]) && is_account_page() && is_main_query() && in_the_loop()) {

					$title = $tab->post_title ? esc_html ($tab->post_title) : esc_html__('Tab #', 'sdp-my-account-tabs-for-woocommerce') . $tab->ID;
					unset ($wp_query->query_vars[$tab->post_name]); // Otherwise, the sky will fall on our heads.
					}
				}

			return esc_html ($title);
			}

		public function subscriptions_title ($title) {

			if ($tab = get_page_by_path ('smat-core-subscriptions', OBJECT, SMAT_CPT::CPT))
				return $tab->post_title ?: esc_html__('Subscriptions', 'sdp-my-account-tabs-for-woocommerce');

			return $title;
			}

		public function mark_flush_rewrite ($post_id, $post, $update) {

			if ((defined ('DOING_AUTOSAVE') && DOING_AUTOSAVE) ||
				SMAT_CPT::CPT !== $post->post_type ||
				'publish' !== $post->post_status ||
				wp_is_post_revision ($post_id))
					return;

			update_option ('smat_flush_rewrite_pending', 1);
			}

		public function maybe_flush_rewrite_rules () {

			if (get_option ('smat_flush_rewrite_pending')) {

				flush_rewrite_rules (true);
				delete_option ('smat_flush_rewrite_pending');
				}
			}

		}

endif;