<?php

/**
 * Custom post type 'smat-tab'.
 * 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_CPT')) :

	#[AllowDynamicProperties]

	Class SMAT_CPT {

		const CPT       = 'smat-tab';
		const CACHE_KEY = 'smat_cache_key';

		public function __construct () {

			$this->crea_cpt();
			$this->check_endpoints();

			add_filter ('post_updated_messages', [$this, 'mensajes_guardado'], 10, 1);
			add_filter ('bulk_post_updated_messages', [$this, 'mensajes_guardados_bulk'], 10, 2);
			
			add_action ('manage_posts_extra_tablenav', [$this, 'drag_drop_message'], 10, 1);

			add_filter ('manage_' . self::CPT . '_posts_columns', [$this, 'columna_orden'], 10, 1);
			add_action ('manage_' . self::CPT . '_posts_custom_column', [$this, 'rellena_columna_orden'], 10, 2);
			
			add_action ('current_screen', [$this, 'quita_editor'], 10);
			add_filter ('post_row_actions', [$this, 'tabs_actions'], 10, 1);
			add_filter ('pre_get_posts', [$this, 'admin_cpt'], 10, 1);
			add_filter ('wp_count_posts', [$this, 'resta_tabs_ocultas'], 10, 2);

			add_action ('wp_ajax_smat_activa_tab', [$this, 'activa_tab'], 10);
			add_action ('wp_ajax_smat_actualiza_orden_cpt', [$this, 'cambia_orden_cpt'], 10);

			add_action ('admin_enqueue_scripts', [$this, 'scripts_and_styles'], 10);
			add_action ('wp_enqueue_scripts', [$this, 'my_account_scripts'], 10);
			}

		private function crea_cpt () {

			$labels_safe = [
                'name'                  => esc_html_x ('My Account Tabs', 'Post Type General Name', 'sdp-my-account-tabs-for-woocommerce'),
                'singular_name'         => esc_html_x ('My Account Tab', 'Post Type Singular Name', 'sdp-my-account-tabs-for-woocommerce'),
                'menu_name'             => esc_html__('My Account Tabs', 'sdp-my-account-tabs-for-woocommerce'),
                'name_admin_bar'        => esc_html__('My Account Tab', 'sdp-my-account-tabs-for-woocommerce'),
                'archives'              => esc_html__('Tabs archives', 'sdp-my-account-tabs-for-woocommerce'),
                'attributes'            => esc_html__('Tab attributes', 'sdp-my-account-tabs-for-woocommerce'),
                'all_items'             => esc_html__('My Account Tabs', 'sdp-my-account-tabs-for-woocommerce'),
                'add_new_item'          => esc_html__('Add new tab', 'sdp-my-account-tabs-for-woocommerce'),
                'add_new'               => esc_html__('Add new', 'sdp-my-account-tabs-for-woocommerce'),
                'new_item'              => esc_html__('New tab', 'sdp-my-account-tabs-for-woocommerce'),
                'edit_item'             => esc_html__('Edit tab', 'sdp-my-account-tabs-for-woocommerce'),
                'update_item'           => esc_html__('Update tab', 'sdp-my-account-tabs-for-woocommerce'),
                'view_item'             => esc_html__('View tab', 'sdp-my-account-tabs-for-woocommerce'),
                'view_items'            => esc_html__('View tabs', 'sdp-my-account-tabs-for-woocommerce'),
                'search_items'          => esc_html__('Search tab', 'sdp-my-account-tabs-for-woocommerce'),
                'not_found'             => esc_html__('No tabs', 'sdp-my-account-tabs-for-woocommerce'),
                'not_found_in_trash'    => esc_html__('No tabs in the trash.', 'sdp-my-account-tabs-for-woocommerce'),
                'items_list'            => esc_html__('Tabs list', 'sdp-my-account-tabs-for-woocommerce'),
                'items_list_navigation' => esc_html__('Tabs list navigation', 'sdp-my-account-tabs-for-woocommerce'),
                'filter_items_list'     => esc_html__('Filter tabs list', 'sdp-my-account-tabs-for-woocommerce'),
				];

			$argumentos = [
				'label'                 => esc_html__('My Account Tab', 'sdp-my-account-tabs-for-woocommerce'),
				'description'           => esc_html__('Manage custom tabs for the WooCommerce My Account page', 'sdp-my-account-tabs-for-woocommerce'),
				'labels'                => $labels_safe,
				'supports'              => ['title', 'editor'],
				'hierarchical'          => false,
				'public'                => false,
				'show_ui'               => true,
				'show_in_menu'          => 'woocommerce',
				'show_in_admin_bar'     => true,
				'show_in_nav_menus'     => true,
				'show_in_rest' 			=> false,
				'can_export'            => true,
				'has_archive'           => false,
				'rewrite'				=> false,
				'exclude_from_search'   => true,
				'publicly_queryable'    => true,
				'capability_type'       => 'post',
				];

			register_post_type (self::CPT, $argumentos);
			}

		protected function check_endpoints () {
			
			$core  = get_option ('smat_core_tabs') ?: [];
			$order = ($logout_post = get_page_by_path ('smat-core-customer-logout', OBJECT, self::CPT)) ? (int) $logout_post->menu_order - 5 : 10;

			$this->core_account_menu_items = function_exists ('wc_get_account_menu_items') ? wc_get_account_menu_items() : [];

			// WooCommerce Subscriptions patch.
			if (is_plugin_active ('woocommerce-subscriptions/woocommerce-subscriptions.php'))
				$this->core_account_menu_items['subscriptions'] = esc_html__('Subscriptions', 'sdp-my-account-tabs-for-woocommerce');

			// WooCommerce Memberships patch.
			if (function_exists ('wc_memberships_get_membership_plans') && count (wc_memberships_get_membership_plans (['status' => 'publish'])) && $ms_endpoint = get_option ('woocommerce_myaccount_members_area_endpoint', false))
        		$this->core_account_menu_items[$ms_endpoint] = esc_html__('Memberships', 'sdp-my-account-tabs-for-woocommerce');

			foreach ($this->core_account_menu_items as $endpoint => $title)
				$order += ($tab = SMAT_Tab::create($endpoint, $title, $order)) && in_array ($tab->id, $core) ? 0 : 10;
			}

		public function mensajes_guardado ($mensajes) {

			$mensajes[self::CPT] = [
				1 => esc_html__('Tab updated.', 'sdp-my-account-tabs-for-woocommerce'),
				4 => esc_html__('Tab updated.', 'sdp-my-account-tabs-for-woocommerce'),
				6 => esc_html__('Tab created.', 'sdp-my-account-tabs-for-woocommerce'),
				7 => esc_html__('Tab saved.', 'sdp-my-account-tabs-for-woocommerce'),
				];

			return $mensajes;
			}

		public function mensajes_guardados_bulk ($mensajes, $cuantos) {

			$mensajes[self::CPT] = [
				 // translators: number of updated tabs
				'updated'	=> esc_html (_n('%s tab updated successfully','%s tabs updated successfully.', absint ($cuantos['updated']), 'sdp-my-account-tabs-for-woocommerce')),
				// translators: number of tabs that couldn't be updated
				'locked'	=> esc_html (_n('%s tab couldn\'t be updated, someone else is editing it.', '%s tabs couldn\'t be updated, someone else is editing them.', absint ($cuantos['locked']), 'sdp-my-account-tabs-for-woocommerce')),
				// translators: number of deleted tabs
				'deleted'	=> esc_html (_n('%s tab deleted successfully.', '%s tabs deleted successfully.', absint ($cuantos['deleted']), 'sdp-my-account-tabs-for-woocommerce')),
				// translators: number of tabs sent to the trash
				'trashed'	=> esc_html (_n('%s tab moved to the trash.', '%s tabs moved to the trash.', absint ($cuantos['trashed']), 'sdp-my-account-tabs-for-woocommerce')),
				// translators: number of tabs restored from the trash
				'untrashed'	=> esc_html (_n('%s tab restored from the trash.', '%s tabs restored from the trash.', absint ($cuantos['untrashed']), 'sdp-my-account-tabs-for-woocommerce')),
				];

			return $mensajes;
			}

		public function drag_drop_message ($which) {

			 if ($which === 'top' && get_post_type () === self::CPT)
				printf ('<div class="notice notice-info smat-notice">⚡ %s</div>', esc_html__('You can reorder tabs by dragging and dropping them.', 'sdp-my-account-tabs-for-woocommerce'));
			}

		public function columna_orden ($columnas) {

			return [
				'cb' 	 => '<input type="checkbox" />',
				'titulo' => esc_html__('Title', 'default'),
				'desc'	 => esc_html__('Description', 'default'),
				'date' 	 => esc_html__('Date', 'default'),
				];
			}

		public function rellena_columna_orden ($columna, $id) {

			switch ($columna) {

				case 'titulo':

					// translators: tab ID
					$title = get_the_title ($id) ? : sprintf (__('Tab #%s', 'sdp-my-account-tabs-for-woocommerce'), $id);
					
					if ('draft' === ($status = get_post_status ($id)))
						$status_show = sprintf (' (%s)', esc_html__('Draft', 'default'));

					else if ('pending' === $status)
						$status_show = sprintf (' (%s)', esc_html__('Pending Review', 'default'));

					else
						$status_show = '';

					printf ('<a class="row-title" href="%s">%s</a>%s', esc_url (get_edit_post_link ($id)), esc_html ($title), $status_show);

					printf ('<p><label class="switch"><input type="checkbox" id="activa-%s" %s onChange="activaTab(%s)" /><span class="slider"></span></label></p>', absint ($id), checked (get_field ('smat_active', $id), true, false), absint ($id));

					break;

				case 'desc':

					$description = get_field ('smat_description', $id) ?? '';
					echo wp_kses_post ($description);

					if (get_post_meta ($id, 'smat_is_core', true))
						printf ('<p class="core-tab"><span>%s</span></p>', esc_html__('core', 'sdp-my-account-tabs-for-woocommerce'));
					break;
				}
			}

		public static function pide_query ($query_vars = false) {

			$query = [
				'post_type'			=> self::CPT,
				'post_status' 		=> 'publish',
				'posts_per_page'	=> -1,
				'orderby'			=> 'ID',
				'order'				=> 'DESC',
				];

			if (!$query_vars) {

				if ($cache = wp_cache_get (self::CACHE_KEY))
					return $cache;

				if ($cpt = new WP_Query($query)) {

					wp_cache_set (self::CACHE_KEY, $cpt->posts, '', 5);
					return $cpt->posts;
					}
				}

			foreach ($query_vars as $query_var => $valor)
				$query[$query_var] = $valor;

			if ($cpt = new WP_Query ($query))
				return $cpt->posts;
			}

		public function quita_editor () {

			$screen = get_current_screen();

			if ($screen && self::CPT === $screen->post_type)
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended
				if (in_array (isset ($_GET['post']) ? absint ($_GET['post']) : 0, get_option ('smat_core_tabs') ?: [])) 
					remove_post_type_support (self::CPT, 'editor');
			}

		public function tabs_actions ($actions) {

			if (get_post_type() !== self::CPT)
				return $actions;

			// Para las pestañas core quitamos Trash.
			if (get_post_meta (get_the_ID(), 'smat_is_core', true))
				unset ($actions['trash']);

			unset ($actions['view']);
			unset ($actions['inline hide-if-no-js']); //Edición rápida.
			
			return $actions;
			}

		/**
		 * Mostramos el listado de campos ordenado según el orden personalizado, no por ID
		 * 
		 * copyright Simple Direct Plugins - support@simpledirectplugins.com
		 *
		 * @since 	1.0.0
		 *
		 * @param 	WP_Query
		 * @return 	WP_Query
		 *
		 */
		public function admin_cpt ($query) {

			if (is_admin() && $query->is_main_query() && self::CPT === $query->get('post_type')) {

				$hide_tabs = array_filter (get_option ('smat_core_tabs') ?: [], function ($core_tab) {
					return !in_array (get_post_meta ($core_tab, 'smat_core_endpoint', true) ?: '', array_keys ($this->core_account_menu_items));
					});

				// Payment methods.
				$show_payment_tab = false;

				if (class_exists ('WC_Payment_Gateways')) {
					
					foreach (WC()->payment_gateways()->get_available_payment_gateways() as $gateway) {

						if (method_exists ($gateway, 'supports') && $gateway->supports('add_payment_method')) {

							$show_payment_tab = true;
							break;
							}
						}
					}

				if (!$show_payment_tab) 
					if ($post = get_page_by_path ('smat-core-payment-methods', OBJECT, self::CPT))
						$hide_tabs[] = $post->ID;

				if (count ($hide_tabs))
					$query->set('post__not_in', array_merge ($query->get('post__not_in') ?: [], $hide_tabs));

				$query->set('orderby', 'menu_order');
				$query->set('order', 'ASC');
				}

			return $query;
			}

		public function resta_tabs_ocultas ($counts, $type) {

			if (self::CPT !== $type)
				return $counts;

			$hide_tabs = array_filter (get_option ('smat_core_tabs') ?: [], function ($core_tab) {
				return !in_array (get_post_meta ($core_tab, 'smat_core_endpoint', true) ?: '', array_keys ($this->core_account_menu_items));
				});

			// Payment methods.
			$show_payment_tab = false;

			if (class_exists ('WC_Payment_Gateways')) {
					
				foreach (WC()->payment_gateways()->get_available_payment_gateways() as $gateway) {

					if (method_exists ($gateway, 'supports') && $gateway->supports('add_payment_method')) {

						$show_payment_tab = true;
						break;
						}
					}
				}

			if (!$show_payment_tab) 
				if ($post = get_page_by_path ('smat-core-payment-methods', OBJECT, self::CPT))
					$hide_tabs[] = $post->ID;

			$hide_tabs = array_unique ($hide_tabs);

			if (!empty ($hide_tabs) && isset ($counts->publish))
				$counts->publish -= count ($hide_tabs);

			return $counts;
			}

		/**
		 * Activamos o desactivamos una pestaña desde el listado de pestañas.
		 * 
		 * copyright Simple Direct Plugins - support@simpledirectplugins.com
		 *
		 * @since 	1.0.0
		 *
		 */
		public function activa_tab () {

			if (!defined ('DOING_AJAX') || !DOING_AJAX)
				wp_die();

			check_ajax_referer ('smat_activa_tab', 'nonce');

			if (!current_user_can ('edit_posts'))
				wp_send_json_error (esc_html__('No permission', 'sdp-my-account-tabs-for-woocommerce'));

			$id      = isset ($_POST['id']) ? absint ($_POST['id']) : 0;
			$activar = isset ($_POST['activar']) ? sanitize_text_field (wp_unslash ($_POST['activar'])) : '';

			if (!$id)
				wp_send_json_error (esc_html__('Invalid ID', 'sdp-my-account-tabs-for-woocommerce'));
			
			update_post_meta ($id, 'smat_active', $activar);
			update_option ('smat_flush_rewrite_pending', 1);

			die();
			}

		/**
		 * Actualizamos el orden de los campos según lo hemos recibido de jQuery.sortable.
		 * 
		 * copyright Simple Direct Plugins - support@simpledirectplugins.com
		 *
		 * @since 	1.0.0
		 *
		 */
		public function cambia_orden_cpt () {

			if (!defined ('DOING_AJAX') || !DOING_AJAX)
				wp_die();

			check_ajax_referer ('smat_actualiza_orden_cpt', 'nonce');

			if (!current_user_can ('edit_posts'))
				wp_die();

			$i = 0;

			if (isset ($_POST['orden'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing

				//post[]=129&post[]=132&post[]=160&post[]=128&post[]=125
				wp_parse_str (wp_unslash ($_POST['orden']), $array_orden); // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				$ids_safe = array_map ('absint', $array_orden['post'] ?? []);

				foreach ($ids_safe as $post) {

					wp_update_post (
						[
							'ID'			=> $post,
							'menu_order'	=> $i,
							]
						);

					$i++;
					}
				}

			die();
			}

		public function scripts_and_styles () {

			wp_enqueue_style ('smat-tab', esc_url (SMAT_ASSETS . 'css/tab.min.css'), [], '1.1'); //Hides visibility and preview options. Styles for Add SMAT Shortcode button.

			if (self::CPT === get_post_type()) {

				wp_enqueue_style ('smat-tabs', esc_url (SMAT_ASSETS . 'css/tabs.min.css'), [], '1.0');
				wp_enqueue_script ('smat-reordena-cpt', esc_url (SMAT_ASSETS . 'js/reordenar.min.js'), ['jquery', 'jquery-ui-sortable'], '1.2', true);
				wp_localize_script ('smat-reordena-cpt', 'smat_reordena', [
					'ajax_url'  		=> admin_url ('admin-ajax.php'),
					'nonce_activa'		=> wp_create_nonce ('smat_activa_tab'),
					'nonce_reordena'	=> wp_create_nonce ('smat_actualiza_orden_cpt'),
					]);
				}

			$hide_checkbox = '';
			$dynamic_css   = sprintf ('#smat-button .dashicons{vertical-align:%s!important}', version_compare (get_bloginfo ('version'), '7', '>=') ? 'top' : 'middle');

			foreach (get_option ('smat_core_tabs') ?: [] as $core) {

				$hide_checkbox .= sprintf ('#cb-select-%s{display:none}#post-%s td.date{color:transparent}', esc_attr ($core), esc_attr ($core));

				// phpcs:ignore WordPress.Security.NonceVerification.Recommended
				if (isset ($_GET['post']) && absint ($_GET['post']) === $core)
					$dynamic_css .= '#delete-action{display:none}';
				}

			wp_add_inline_style ('smat-tabs', $hide_checkbox);
			wp_add_inline_style ('smat-tab', $dynamic_css);
			}

		public function my_account_scripts () {

			if (apply_filters ('smat_memberships_change_title', true) && is_account_page() && 'members_area' === WC()->query->get_current_endpoint() && ($ms_endpoint = get_option ('woocommerce_myaccount_members_area_endpoint', false)) && ($tab = get_page_by_path ('smat-core-' . $ms_endpoint, OBJECT, self::CPT))) {

				wp_enqueue_style ('smat-memberships-title', SMAT_ASSETS . 'css/memberships.css', [], '1.0');
				wp_enqueue_script ('smat-memberships-title', esc_url (SMAT_ASSETS . 'js/memberships.min.js'), ['jquery'], '1.0', true);
				wp_localize_script ('smat-memberships-title', 'smatMembersData', ['title' => get_the_title ($tab->ID) ?: esc_html__('Memberships', 'sdp-my-account-tabs-for-woocommerce')]);
				}
			}

		}

endif;