<?php

/**
 * Custom post type 'scos-status'.
 * copyright Simple Direct Plugins - support@simpledirectplugins.com
 *
 * @author 			Simple Direct Plugins
 * @link			https://simpledirectplugins.com
 * @since			1.0.0
 * @package			SCOSWoo
 *
 */

defined ('ABSPATH') or exit;

if (!class_exists('SCOS_CPT')) :

	Class SCOS_CPT {

		const CPT         = 'scos-status';
		const CACHE_KEY   = 'scos_cache_key';
		const CACHE_GROUP = 'scos';

		public function __construct () {

			$this->crea_cpt();

			add_action ('save_post', [$this, 'save_functions'], 10, 1);

			add_action ('admin_notices', [$this, 'drag_drop_message'], 10);
			add_filter ('post_updated_messages', [$this, 'updated_messages'], 10, 1);
			add_filter ('bulk_post_updated_messages', [$this, 'bulk_updated_messages'], 10, 2);

			add_filter ('manage_' . self::CPT . '_posts_columns', [$this, 'columns'], 10, 1);
			add_action ('manage_' . self::CPT . '_posts_custom_column', [$this, 'populate_columns'], 10, 2);

			add_filter ('post_row_actions', [$this, 'row_actions'], 10, 1);
			add_filter ('pre_get_posts', [$this, 'order_cpt_admin'], 10, 1);

			add_action ('wp_ajax_scos_importa_estados', [$this, 'import_order_statuses'], 10);
			add_action ('wp_ajax_scos_actualiza_orden_cpt', [$this, 'change_cpt_admin'], 10);

			add_action ('admin_footer', [$this, 'import_button_data'], 10);
			add_action ('admin_enqueue_scripts', [$this, 'scripts_and_styles'], 10);
			}

		private function crea_cpt () {

			$labels_safe = [
				'name'                  => esc_html__('Custom order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'singular_name'         => esc_html__('Order status', 'sdp-custom-order-status-for-woocommerce'),
				'menu_name'             => esc_html__('Order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'name_admin_bar'        => esc_html__('Order status', 'sdp-custom-order-status-for-woocommerce'),
				'archives'              => esc_html__('Order statuses archives', 'sdp-custom-order-status-for-woocommerce'),
				'attributes'            => esc_html__('Order status attributes', 'sdp-custom-order-status-for-woocommerce'),
				'all_items'             => esc_html__('Order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'add_new_item'          => esc_html__('Add order status', 'sdp-custom-order-status-for-woocommerce'),
				'add_new'               => esc_html__('Add status', 'sdp-custom-order-status-for-woocommerce'),
				'new_item'              => esc_html__('New order status', 'sdp-custom-order-status-for-woocommerce'),
				'edit_item'             => esc_html__('Edit order status', 'sdp-custom-order-status-for-woocommerce'),
				'update_item'           => esc_html__('Update order status', 'sdp-custom-order-status-for-woocommerce'),
				'view_item'             => esc_html__('View order status', 'sdp-custom-order-status-for-woocommerce'),
				'view_items'            => esc_html__('View order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'search_items'          => esc_html__('Search order status', 'sdp-custom-order-status-for-woocommerce'),
				'not_found'             => esc_html__('No order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'not_found_in_trash'    => esc_html__('No order statuses in the trash.', 'sdp-custom-order-status-for-woocommerce'),
				'items_list'            => esc_html__('Order status list', 'sdp-custom-order-status-for-woocommerce'),
				'items_list_navigation' => esc_html__('Order status list navigation', 'sdp-custom-order-status-for-woocommerce'),
				'filter_items_list'     => esc_html__('Filter order status list', 'sdp-custom-order-status-for-woocommerce'),
				];

			$args_safe = [
				'label'                 => esc_html__('Order status', 'sdp-custom-order-status-for-woocommerce'),
				'description'           => esc_html__('Manage order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'labels'                => $labels_safe,
				'supports'              => ['title'],
				'hierarchical'          => false,
				'public'                => false,
				'show_ui'               => true,
				'show_in_menu'          => 'woocommerce',
				'show_in_admin_bar'     => true,
				'show_in_nav_menus'     => false,
				'can_export'            => true,
				'has_archive'           => false,		
				'exclude_from_search'   => true,
				'publicly_queryable'    => true,
				'capability_type'       => 'post',
				'register_meta_box_cb'	=> [$this, 'scos_metabox_devinfo_safe'],
				];

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

		/**
		 * Los slugs con más de dos guiones (incluyendo el de 'wc-') o más largos de 15 caracteres generan un bug.
		 *
		 * @since 	1.3.1
		 *
		 * @param 	int 	post ID
		 * @return 	null
		 *
		 */
		public function save_functions ($post_id) {

			if (defined ('DOING_AUTOSAVE') && DOING_AUTOSAVE) //Evitamos la ejecución en autoguardados.
				return;

			if (!current_user_can ('edit_post', $post_id)) //Seguridad ante todo.
				return;

			remove_action ('save_post', [$this, 'save_functions']); //Evitamos que entre en bucle.

			$post = get_post ($post_id);
			$slug = $post->post_name;

			if (self::CPT === $post->post_type && (strlen ($slug) > 15 || substr_count ($slug, '-') > 1)) {

				$slug = substr (str_replace ("-", "", $slug), 0, 12) . (string) wp_rand (100, 999);

				wp_update_post (
					[
						'ID'		=> $post->ID,
						'post_name'	=> $slug,
						]
					);
				}

			//Solo un estado por defecto.
			if (get_field ('scos_default', $post_id))
				foreach (SCOS_CPT::pide_query() as $estado)
					if ($estado->ID != $post_id && get_field ('scos_default', $estado->ID))
						update_field ('scos_default', 0, $estado->ID);

			//WooCommerce PDF Invoices & Packing Slips.
			if (is_plugin_active ('woocommerce-pdf-invoices-packing-slips/woocommerce-pdf-invoices-packingslips.php')) {

				$invoice		   = get_field ('scos_invoice', $post_id);
				$settings_invoice  = get_option ('wpo_wcpdf_documents_settings_invoice');
				$notification_slug = 'scos_order_status_' . $slug;

				if (is_array ($invoice) && count ($invoice) && in_array ('factura', $invoice)) {
					
					$settings_invoice['attach_to_email_ids'][$notification_slug] = '1';
					update_option ('wpo_wcpdf_documents_settings_invoice', $settings_invoice);
					}

				else if (isset ($settings_invoice['attach_to_email_ids'][$notification_slug])) {

					unset ($settings_invoice['attach_to_email_ids'][$notification_slug]);
					update_option ('wpo_wcpdf_documents_settings_invoice', $settings_invoice);
					}
				}

			return;
			}

		public function updated_messages ($mensajes) {

			$mensajes[self::CPT] = [
				1 => esc_html__('Order status updated.', 'sdp-custom-order-status-for-woocommerce'),
				4 => esc_html__('Order status updated.', 'sdp-custom-order-status-for-woocommerce'),
				6 => esc_html__('Order status created.', 'sdp-custom-order-status-for-woocommerce'),
				7 => esc_html__('Order status saved.', 'sdp-custom-order-status-for-woocommerce'),
				];

			return $mensajes;
			}

		public function bulk_updated_messages ($mensajes, $cuantos) {

			$mensajes[self::CPT] = [
				/* translators: number of order statuses that have been updated */
				'updated'	=> esc_html (_n('%s order status updated successfully.','%s order statuses updated successfully.', $cuantos['updated'], 'sdp-custom-order-status-for-woocommerce')),
				/* translators: number of order statuses that could'n have been updated */
				'locked'	=> esc_html (_n('%s order status couldn’t be updated, someone else is editing it.', '%s order statuses couldn’t be updated, someone else is editing them.', $cuantos['locked'], 'sdp-custom-order-status-for-woocommerce')),
				/* translators: number of order statuses that have been deleted */
				'deleted'	=> esc_html (_n('%s order status deleted successfully.', '%s order statuses deleted successfully.', $cuantos['deleted'], 'sdp-custom-order-status-for-woocommerce')),
				/* translators: number of order statuses that have been moved to the trash */
				'trashed'	=> esc_html (_n('%s order status moved to the trash.', '%s order statuses moved to the trash.', $cuantos['trashed'], 'sdp-custom-order-status-for-woocommerce')),
				/* translators: number of order statuses that have been restored from the trash */
				'untrashed'	=> esc_html (_n('%s order status restored from the trash.', '%s order statuses restored from the trash.', $cuantos['untrashed'], 'sdp-custom-order-status-for-woocommerce')),
				];

			return $mensajes;
			}

		public function drag_drop_message () {

			if (!$screen = get_current_screen())
				return;

			if ('edit-' . self::CPT === $screen->id)
				printf ('<div class="notice notice-info scos-notice">⚡ %s</div>', esc_html__('You can reorder statuses by dragging and dropping them.', 'sdp-custom-order-status-for-woocommerce'));
			}

		public function columns ($columnas) {

			return [
				'cb' 		=> '<input type="checkbox" />',
				'titulo' 	=> esc_html__('Status', 'sdp-custom-order-status-for-woocommerce'),
				'icon'		=> '<span class="status_head">' . esc_html__('Icon', 'sdp-custom-order-status-for-woocommerce') . '</span>',
				'estdef'	=> sprintf ('<span class="status_head">%s <span class="dashicons dashicons-editor-help" title="%s"></span></span>', esc_html__('Default', 'sdp-custom-order-status-for-woocommerce'), esc_html__('Order status that will be assigned by default when a payment is completed. This overrides WooCommerce\'s default behavior.', 'sdp-custom-order-status-for-woocommerce')),
				'notif'		=> '<span class="dashicons dashicons-email-alt"></span>',
				];
			}

		public function populate_columns ($columna, $id) {

			switch ($columna) {

				case 'titulo':

					/* translators: ID of custom status, just in case the user didn't set a title for it */
					$title = get_the_title ($id) ?: sprintf (__('Custom #%s', 'sdp-custom-order-status-for-woocommerce'), absint ($id));
					
					if ('draft' === ($status = get_post_status ($id)))
						$status_show = sprintf (' —(%s)', __('Draft', 'default'));

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

					else
						$status_show = '';

					printf ('<strong><a class="row-title scos-status-%1$s" href="post.php?post=%1$s&action=edit" aria-label="%2$s">%3$s</a>%4$s</strong>',
						absint ($id),
						esc_attr ($title),
						esc_html ($title),
						esc_html ($status_show)
						);

					break;

				case 'icon':

					$iconos = SCOS_Fields::devuelve_iconos();
					$campo  = get_field ('scos_icono', $id);
					$icono  = isset ($campo) ? (is_array ($campo) ? $campo['value'] : $campo) : '159';
					wp_kses (
						printf ('%s id="scos-icon-%s" title="%s"></span>', 
							substr ($iconos[$icono], 0, strpos ($iconos[$icono], ">")), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped - Filtered by wp_kses
							absint ($id),
							esc_html__('Order status', 'sdp-custom-order-status-for-woocommerce') . ': ' . (esc_attr (get_the_title ($id)) ?:
								/* translators: the ID of the custom order status */
								sprintf (esc_html__('Custom #%s', 'sdp-custom-order-status-for-woocommerce'), absint ($id))
								)
							),
						['span' => ['class' => [], 'id' => [], 'title' => []]]
						);

					break;

				case 'estdef':

					echo get_field ('scos_default', $id) ?
						'<span title="' . esc_attr__('Selected', 'sdp-custom-order-status-for-woocommerce') . '"><span class="dashicons dashicons-yes-alt estdef"></span></span>' :
						'<span title="' . esc_attr__('Not selected', 'sdp-custom-order-status-for-woocommerce') . '"><span class="dashicons dashicons-no estdef"></span></span>';

					break;

				case 'notif':

					if (is_array ($notificaciones = get_field ('scos_notificaciones', $id))) {

						$destinatarios = [];

						foreach ($notificaciones as $notificacion) {

							if ('admin' === $notificacion) {

								if ($admin_email = get_field ('scos_email_admin', $id))
									$destinatarios = explode (';', $admin_email);

								else
									$destinatarios[] = get_option ('admin_email');
								}

							else if ('cliente' === $notificacion)
								$destinatarios[] = esc_html__('Customer', 'sdp-custom-order-status-for-woocommerce');
							}

						echo wp_kses_post (implode ('<br>', $destinatarios));
						}

					break;
				}
			}

		/**
		 * Importa mediante AJAX los estados de pedido creados por otros plugins.
		 *
		 * @since 	2.2.0
		 *
		 */
		public function import_order_statuses () {

			if (!defined ('DOING_AJAX') || !DOING_AJAX)
				return false;

			$estados  = wp_list_pluck ($this->pide_query(), 'post_name');
			$terceros = $this->estados_pedidos_terceros();

			$campos = [
				'color'		=> 'field_scos_appearance_color',
				'sigestado'	=> 'field_scos_next_status',
				'icono'		=> 'field_scos_appearance_icon',
				'informes'	=> 'field_scos_settings',
				];

			foreach ($terceros as $tercero) {

				if (!in_array ($tercero->post_name, $estados)) { //Si no es de los nuestros.

					$nuevo  = [
						'post_title'	=> esc_html ($tercero->post_title),
						'post_type'		=> self::CPT,
						'post_status' 	=> 'publish',
						'post_name'		=> $tercero->post_name,
						];

					if (is_int ($id = wp_insert_post ($nuevo, false))) { //Generamos el nuevo estado de pedido.

						/**
						 * YITH Custom Order Status (YITH).
						 * https://yithemes.com/themes/plugins/yith-woocommerce-custom-order-status/
						 * 
						 */
						if ($color = get_post_meta ($tercero->ID, 'color', true)) {

							update_post_meta ($id, '_color', $campos['color']);
							update_post_meta ($id, 'color', $color);
							}

						if ($siguiente = get_post_meta ($tercero->ID, 'nextactions')) {

							update_post_meta ($id, '_sigestado', $campos['sigestado']);
							update_post_meta ($id, 'sigestado', $siguiente[0]);
							}

						/**
						 * Order Status Manager for WooCommerce (SkyVerge).
						 * https://woocommerce.com/products/woocommerce-order-status-manager/
						 * 
						 */
						if ($color = get_post_meta ($tercero->ID, '_color', true)) {

							update_post_meta ($id, '_color', $campos['color']);
							update_post_meta ($id, 'color', $color);
							}

						$icono = get_post_meta ($tercero->ID, '_action_icon', true) or
							$icono = get_post_meta ($tercero->ID, '_icon', true);

						if ($icono && $codigo = array_search ('<span class="' . $icono . '"></span>', Campos_Estados_Pedido::devuelve_iconos())) {

							update_post_meta ($id, '_icono', $campos['icono']);
							update_post_meta ($id, 'icono', $codigo);
							}

						if ($siguiente = get_post_meta ($tercero->ID, '_next_statuses', true)) {

							update_post_meta ($id, '_sigestado', $campos['sigestado']);
							update_post_meta ($id, 'sigestado', $siguiente[0]);
							}

						if ('yes' === get_post_meta ($tercero->ID, '_is_paid', true)) {

							update_post_meta ($id, '_informes', $campos['informes']);
							update_post_meta ($id, 'informes', ['incluir']);
							}
						}
					}
				}

			die();
			}

		/**
		 * Establece una cabecera con los datos para generar el botón de importación de estados de pedido:
		 *		Nombre del CPT (para que sea dinámico).
		 *		Texto del botón (para que sea traducible).
		 *		Textos de confirmación (para que sean traducibles).
		 *
		 * Los datos son recuperados y utilizados por estados.js.
		 *
		 * @since 2.2.0
		 *
		 */
		public function import_button_data () {

			//Si no existen estados de pedido personalizados que no hayamos importado no hacemos nada.
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if (!isset ($_GET['post_type']) || self::CPT != $_GET['post_type'] || !count ($this->estados_pedidos_terceros()))
				return;

			$textos = [
				'texto'		=> __('Import order statuses', 'sdp-custom-order-status-for-woocommerce'),
				'pregunta'	=> __('Are you sure?', 'sdp-custom-order-status-for-woocommerce'),
				'frase'		=> __('This will import the custom order statuses created by other plugins.', 'sdp-custom-order-status-for-woocommerce'),
				'si'		=> __('Yes', 'default'), // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
				'no'		=> __('No', 'default'), // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
				'exito'		=> __('Importing new order statuses, please wait...', 'sdp-custom-order-status-for-woocommerce'),
				'import'	=> __('Order statuses imported, please wait for the page to reload...', 'sdp-custom-order-status-for-woocommerce'),
				];

			printf ('<meta name="boton-importar-estados" id="meta-boton-importar-estados" data-cpt="%s" data-texto="%s" data-pregunta="%s" data-frase="%s" data-si="%s" data-no="%s" data-exito="%s" data-import="%s">', esc_html (self::CPT), esc_html ($textos['texto']), esc_html ($textos['pregunta']), esc_html ($textos['frase']), esc_html ($textos['si']), esc_html ($textos['no']), esc_html ($textos['exito']), esc_html ($textos['import']));
			}


		/**
		 * Devuelve los estados de pedido registrados, excepto:
		 * 		* Los estados estándar de Woo.
		 * 		* Los estados generados por la pasarela de pago de Redsys.
		 * 		* Los estados excluidos mediante el filtro 'scos_excluded_statuses'.
		 *
		 * @return 	array
		 * @since 	2.2.0
		 *
		 */
		private function estados_pedidos_terceros () {

			$terceros = [];
			$propios  = $this->pide_query();
			$excluye  = apply_filters ('scos_excluded_statuses', ['failed', 'refunded', 'cancelled', 'completed', 'on-hold', 'processing', 'pending', 'draft', 'checkout-draft', 'redsys-pre', 'redsys-residentp', 'redsys-pbankt']);

			$registrados = new WP_Query(
				[
					'post_type'			=> ['wc_order_status', 'yith-wccos-ostatus'], //YITH WooCommerce Custom Order Status Premium.
					'post_status'		=> 'publish',
					'posts_per_page'	=> -1,
					]
				);

			foreach ($registrados->posts as $registrado) {

				if (!in_array ($registrado->post_name, $excluye)) {
					
					$propio = get_page_by_path ($registrado->post_name, OBJECT, self::CPT);

					isset ($propio->ID) and $propio->ID or //Si ya está importado, lo dejamos pasar.
						$terceros[] = $registrado;
					}
				}

			return $terceros;
			}

		public static function pide_query ($menu_order = false, $status = 'publish') {

			$query = [
				'post_type'			=> self::CPT,
				'post_status' 		=> $status,
				'posts_per_page'	=> -1,
				'orderby'			=> $menu_order ? 'menu_order' : 'ID', //Para establecer la prioridad de las automatizaciones.
				'order'				=> $menu_order ? 'ASC' : 'DESC',
				];

			if (!$menu_order && 'publish' === $status && $cache = wp_cache_get (self::CACHE_KEY, self::CACHE_GROUP)) //Si se han pedido por menu_order no devolvemos el resultado cacheado.
				return $cache;

			else if ($estados = new WP_Query($query)) {

				if (!$menu_order && 'publish' === $status) //Ni cacheamos el resultado.
					wp_cache_set (self::CACHE_KEY, $estados->posts, self::CACHE_GROUP, 30);

				return $estados->posts;
				}
			}

		/**
		 * Mostramos el listado de campos ordenado según el orden personalizado, no por ID.
		 *
		 * @since 2.0.0
		 *
		 * @param 	WP_Query
		 * @return 	WP_Query
		 *
		 */
		public function order_cpt_admin ($query) {

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

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

			return $query;
			}

		/**
		 * Actualizamos el orden de los campos según lo hemos recibido de jQuery.sortable.
		 *
		 * @since 2.0.0
		 *
		 */
		public function change_cpt_admin () {

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

			check_ajax_referer ('scos_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();
			}

		/**
		 * Crea la metabox con la información técnica.
		 *
		 * @since 4.6.0
		 *
		 */
		public function scos_metabox_devinfo_safe () {
			
			if (!isset ($_GET['post']) || 'publish' != get_post_status (absint (wp_unslash ($_GET['post'])))) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				return;

			add_meta_box ('scos_custom_order_status_devinfo', sprintf ('<span style="text-align:%s!important">ℹ️ %s</span> ', is_rtl() ? 'right' : 'left', esc_html__('Order status info', 'sdp-custom-order-status-for-woocommerce')), [$this, 'scos_metabox_devinfo_html'], self::CPT, 'normal', 'low');
			}

		public function scos_metabox_devinfo_html () {

			global $post;

			$cantidad = wc_orders_count ($post->post_name);
			$url      = SCOS_HPOS_ACTIVE ? 'admin.php?page=wc-orders&status=wc-' : 'edit.php?post_type=shop_order&post_status=wc-';

			printf ('<p><b>%s:</b> %s %s<br><b>%s:</b> %s (wc-%s)<br><b>%s:</b> scos_order_status_%s<br><b>%s:</b></p>',
				/* translators: the title of the order status, between i tags */
				sprintf (esc_html__('Number of orders in %s status', 'sdp-custom-order-status-for-woocommerce'), '&laquo;' . esc_html ($post->post_title) . '&raquo;'),
				absint ($cantidad),
				absint ($cantidad) ? sprintf ('<a target="_blank" href="%s"><span class="dashicons dashicons-external" style="text-decoration:none"></span></a>', esc_url ($url) . esc_attr ($post->post_name)) : '',
				esc_html__('Status identifier', 'sdp-custom-order-status-for-woocommerce'),
				esc_attr ($post->post_name),
				esc_attr ($post->post_name),
				esc_html__('Action (hook)', 'sdp-custom-order-status-for-woocommerce'),
				esc_attr ($post->post_name),
				esc_html__('Hook usage example', 'sdp-custom-order-status-for-woocommerce'));

			/* translators: the title of the order status */
			printf ('<p><code>add_action (\'%s%s\', function ($order_id) {<br><span style="margin-left:30px">//%s</span><br><span style="margin-left:30px">}, 10, 1);</span></code></p>', esc_attr (SCOS_Statuses::ENVIO), esc_attr ($post->post_name), sprintf (esc_html__('Your code to execute when an order changes to the %s status', 'sdp-custom-order-status-for-woocommerce'), esc_html ($post->post_title)));
			}

		public function row_actions ($acciones) {

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

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

			return $acciones;
			}

		public function scripts_and_styles () {

			$screen = get_current_screen();

			if (!$screen)
				return;

			if (self::CPT === $screen->id) {

				wp_enqueue_style ('scos-status', esc_url (SCOS_ASSETS . 'css/status.min.css'), [], '1.6'); //Hides visibility and preview options.

				if (!wp_style_is ('fontawesome') && !wp_style_is ('font-awesome')) {

					wp_enqueue_style ('fontawesome', esc_url (SCOS_ASSETS . 'css/font-awesome.min.css'), [], '7.0.1');
					wp_enqueue_script ('fontawesome', esc_url (SCOS_ASSETS . 'js/font-awesome.min.js'), [], '7.0.1', true);
					}
				}

			else if ('edit-' . self::CPT === $screen->id) {

				wp_enqueue_style ('scos-statuses', esc_url (SCOS_ASSETS . 'css/statuses.min.css'), [], '1.5');
				wp_enqueue_style ('sweetalert', esc_url (SCOS_ASSETS . 'css/sweetalert.min.css'), [], '1.0');

				wp_enqueue_script ('sweetalert', esc_url (SCOS_ASSETS . 'js/sweetalert.min.js'), [], '1.0', true);
				wp_enqueue_script ('scos-statuses', esc_url (SCOS_ASSETS . 'js/statuses.min.js'), ['jquery', 'jquery-ui-sortable', 'sweetalert'], '1.3', true);

				wp_localize_script ('scos-statuses', 'scos_estados', [
					'ajax_url' => admin_url ('admin-ajax.php'),
					'nonce'    => wp_create_nonce ('scos_actualiza_orden_cpt'),
					]);

				$dynamic_css = '';

				foreach (self::pide_query(false, ['any', 'trash']) as $status) {

					$color = get_field ('scos_color', $status->ID) ?: '#1e73be';
					$label = get_field ('scos_color_label', $status->ID) ?: '#fff';

					$dynamic_css .= sprintf ('
						a.scos-status-%1$s,a.scos-status-%1$s:hover{
							background-color:%2$s;
							color:%3$s;
							}
						#scos-icon-%1$s{
							color:%2$s;
							}',
						absint ($status->ID),
						esc_attr ($color),
						esc_attr ($label)
						);
					}

				wp_add_inline_style ('scos-statuses', $dynamic_css);
				}
			}

		}

endif;