<?php
/**
 * Registro central de pestañas: panel operativo (frontend) vs administración (wp-admin).
 *
 * @package Logistica
 */

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

/**
 * Define qué módulos pertenecen al panel del usuario y cuáles a la administración.
 */
final class Logistica_Tabs {

	public const CONTEXT_ADMIN      = 'admin';

	public const CONTEXT_OPERATIONS = 'operations';

	public const CONTEXT_CONFIG     = 'config';

	/** @var list<string> */
	public const ADMIN_TAB_SLUGS = array(
		'logistica-configuracion',
	);

	/** @var list<string> Pestañas accesibles pero ocultas del menú lateral. */
	public const HIDDEN_NAV_SLUGS = array(
		'logistica-perfil',
	);

	/**
	 * @return array<string, string>
	 */
	public static function all_tabs() {
		return array(
			'logistica'                        => __( 'Inicio', 'logistica' ),
			'logistica-conversiones'           => __( 'Calculadoras', 'logistica' ),
			'logistica-calculo-tapas'          => __( 'Cálculo tapas', 'logistica' ),
			'logistica-calculos'               => __( 'Cálculos bolsas', 'logistica' ),
			'logistica-inventario-bodega'      => __( 'Inventario bodega', 'logistica' ),
			'logistica-cierre-ordenes'         => __( 'Cierre de órdenes', 'logistica' ),
			'logistica-planeacion-impresion'   => __( 'Planeación impresión', 'logistica' ),
			'logistica-planeacion-formado'     => __( 'Planeación formado', 'logistica' ),
			'logistica-tablero-produccion'     => __( 'Tablero producción', 'logistica' ),
			'logistica-cierre-caracteristicas' => __( 'Características por código', 'logistica' ),
			'logistica-codigos-etiqueta'       => __( 'Códigos etiqueta', 'logistica' ),
			'logistica-revision-minuta'        => __( 'Revisión minuta', 'logistica' ),
			'logistica-rotulos-rollos'         => __( 'Rótulos rollos', 'logistica' ),
			'logistica-orden-produccion-vasos' => __( 'Orden producción vasos', 'logistica' ),
			'logistica-cuadro-pedidos'         => __( 'Cuadro de pedidos', 'logistica' ),
			'logistica-ayuda'                  => __( 'Ayuda', 'logistica' ),
			'logistica-perfil'                 => __( 'Mi perfil', 'logistica' ),
			'logistica-configuracion'          => __( 'Configuración', 'logistica' ),
		);
	}

	/**
	 * @param string $slug Tab slug.
	 * @return bool
	 */
	public static function is_hidden_nav_tab( $slug ) {
		return in_array( sanitize_key( (string) $slug ), self::HIDDEN_NAV_SLUGS, true );
	}

	/**
	 * @return list<string>
	 */
	public static function operational_slugs() {
		return array_values(
			array_diff( array_keys( self::all_tabs() ), self::ADMIN_TAB_SLUGS )
		);
	}

	/**
	 * @return list<string>
	 */
	public static function admin_slugs() {
		return self::ADMIN_TAB_SLUGS;
	}

	/**
	 * @return array<string, string>
	 */
	public static function tab_views() {
		return array(
			'logistica'                        => 'dashboard.php',
			'logistica-conversiones'           => 'conversiones.php',
			'logistica-calculo-tapas'          => 'calculo-tapas.php',
			'logistica-calculos'               => 'calculos.php',
			'logistica-inventario-bodega'      => 'inventario-bodega.php',
			'logistica-cierre-ordenes'         => 'cierre-ordenes.php',
			'logistica-planeacion-impresion'   => 'planeacion-impresion.php',
			'logistica-planeacion-formado'     => 'planeacion-formado.php',
			'logistica-tablero-produccion'     => 'tablero-produccion.php',
			'logistica-cierre-caracteristicas' => 'cierre-caracteristicas-page.php',
			'logistica-codigos-etiqueta'       => 'codigos-etiqueta-page.php',
			'logistica-revision-minuta'        => 'revision-minuta-page.php',
			'logistica-rotulos-rollos'         => 'rotulos-rollos-page.php',
			'logistica-orden-produccion-vasos' => 'orden-produccion-vasos-page.php',
			'logistica-cuadro-pedidos'         => 'cuadro-pedidos.php',
			'logistica-ayuda'                  => 'ayuda.php',
			'logistica-perfil'                 => 'perfil.php',
			'logistica-configuracion'          => 'configuracion.php',
		);
	}

	/**
	 * Normaliza contextos heredados (backend/frontend) al modelo actual.
	 *
	 * @param string $context Contexto solicitado.
	 * @return string admin|operations
	 */
	public static function normalize_context( $context ) {
		$context = sanitize_key( (string) $context );

		if ( self::CONTEXT_ADMIN === $context ) {
			return self::CONTEXT_ADMIN;
		}

		if ( self::CONTEXT_CONFIG === $context ) {
			return self::CONTEXT_CONFIG;
		}

		return self::CONTEXT_OPERATIONS;
	}

	/**
	 * Pestañas del panel de configuración en jb-planeacion-backend (todas las del menú).
	 *
	 * @return array<string, string>
	 */
	public static function config_tabs() {
		$all = self::all_tabs();
		$tabs = array();

		foreach ( self::operational_slugs() as $slug ) {
			if ( isset( $all[ $slug ] ) ) {
				$tabs[ $slug ] = $all[ $slug ];
			}
		}

		foreach ( self::ADMIN_TAB_SLUGS as $slug ) {
			if ( isset( $all[ $slug ] ) ) {
				$tabs[ $slug ] = $all[ $slug ];
			}
		}

		return class_exists( 'Logistica_Settings', false )
			? Logistica_Settings::sort_tabs_by_menu_order( $tabs )
			: $tabs;
	}

	/**
	 * @param string $slug Tab slug.
	 * @return string
	 */
	public static function config_tab_path( $slug ) {
		$slug     = sanitize_key( (string) $slug );
		$specific = LOGISTICA_PLUGIN_DIR . 'admin/views/config/tabs/' . $slug . '.php';

		if ( is_readable( $specific ) ) {
			return $specific;
		}

		return LOGISTICA_PLUGIN_DIR . 'admin/views/config/placeholder.php';
	}

	/**
	 * @return bool
	 */
	public static function config_tab_has_settings( $slug ) {
		$slug = sanitize_key( (string) $slug );
		return is_readable( LOGISTICA_PLUGIN_DIR . 'admin/views/config/tabs/' . $slug . '.php' );
	}

	/**
	 * Pestañas visibles según superficie (administración wp-admin u operaciones en sitio).
	 *
	 * @param string $context admin|operations|backend|frontend.
	 * @return array<string, string>
	 */
	public static function tabs_for_context( $context = self::CONTEXT_ADMIN ) {
		$all      = self::all_tabs();
		$context  = self::normalize_context( $context );
		$filtered = array();

		if ( self::CONTEXT_ADMIN === $context ) {
			foreach ( self::ADMIN_TAB_SLUGS as $slug ) {
				if ( isset( $all[ $slug ] ) ) {
					$filtered[ $slug ] = $all[ $slug ];
				}
			}
			return $filtered;
		}

		if ( self::CONTEXT_CONFIG === $context ) {
			if ( ! class_exists( 'Logistica_Roles', false ) || ! Logistica_Roles::user_can_manage_config() ) {
				return array();
			}
			return self::config_tabs();
		}

		foreach ( self::operational_slugs() as $slug ) {
			if ( isset( $all[ $slug ] ) ) {
				$filtered[ $slug ] = $all[ $slug ];
			}
		}

		if ( class_exists( 'Logistica_Roles', false ) && is_user_logged_in() ) {
			$allowed = Logistica_Roles::get_user_tab_slugs( 'backend' );
			if ( ! empty( $allowed ) ) {
				$role_filtered = array();
				foreach ( $allowed as $slug ) {
					if ( isset( $filtered[ $slug ] ) ) {
						$role_filtered[ $slug ] = $filtered[ $slug ];
					}
				}
				$filtered = $role_filtered;
			} elseif ( ! current_user_can( 'manage_options' ) && ! Logistica_Roles::user_can_manage_config() ) {
				return array();
			}
		}

		// Perfil siempre disponible para usuarios con acceso al panel.
		if ( is_user_logged_in() && isset( $all['logistica-perfil'] ) && ! isset( $filtered['logistica-perfil'] ) && ! empty( $filtered ) ) {
			$filtered['logistica-perfil'] = $all['logistica-perfil'];
		}

		return class_exists( 'Logistica_Settings', false )
			? Logistica_Settings::sort_tabs_by_menu_order( $filtered )
			: $filtered;
	}

	/**
	 * Resuelve la ruta absoluta de una vista (nueva estructura + compatibilidad).
	 *
	 * @param string $relative Ruta relativa dentro de views/.
	 * @return string
	 */
	public static function view_path( $relative ) {
		$relative = ltrim( (string) $relative, '/' );
		$candidates = array(
			LOGISTICA_VIEWS_SHELLS . $relative,
			LOGISTICA_VIEWS_ADMIN . $relative,
			LOGISTICA_VIEWS_FRONTEND . $relative,
			LOGISTICA_VIEWS_SHARED . $relative,
			LOGISTICA_PLUGIN_DIR . 'admin/views/' . $relative,
		);

		foreach ( $candidates as $path ) {
			if ( is_readable( $path ) ) {
				return $path;
			}
		}

		return LOGISTICA_PLUGIN_DIR . 'admin/views/' . $relative;
	}

	/**
	 * @param string $tab     Tab slug.
	 * @param string $context admin|operations|backend|frontend.
	 * @return string
	 */
	public static function tab_url( $tab, $context = self::CONTEXT_ADMIN ) {
		$context = self::normalize_context( $context );

		if ( self::CONTEXT_OPERATIONS === $context ) {
			return class_exists( 'Logistica_Roles', false )
				? Logistica_Roles::get_operations_panel_url( $tab )
				: home_url( '/' );
		}

		if ( self::CONTEXT_CONFIG === $context ) {
			return logistica_config_panel_url( $tab );
		}

		return add_query_arg(
			array(
				'page' => 'logistica',
				'tab'  => sanitize_key( (string) $tab ),
			),
			admin_url( 'admin.php' )
		);
	}

	/**
	 * @param string $context admin|operations|backend|frontend.
	 * @return string
	 */
	public static function initial_tab( $context = self::CONTEXT_OPERATIONS ) {
		$visible = array_keys( self::tabs_for_context( $context ) );

		if ( empty( $visible ) ) {
			$normalized = self::normalize_context( $context );
			if ( self::CONTEXT_ADMIN === $normalized ) {
				return 'logistica-configuracion';
			}
			if ( self::CONTEXT_CONFIG === $normalized ) {
				return 'logistica';
			}
			return 'logistica';
		}

		if ( isset( $_GET['tab'] ) ) {
			$tab = sanitize_key( wp_unslash( $_GET['tab'] ) );
			if ( in_array( $tab, $visible, true ) ) {
				return $tab;
			}
		}

		// Sin ?tab= (login / primera visita): preferir Inicio si el usuario la tiene.
		if ( in_array( 'logistica', $visible, true ) ) {
			return 'logistica';
		}

		return (string) $visible[0];
	}

	/**
	 * Si el slug pertenece solo al panel administrativo de wp-admin.
	 *
	 * @param string $tab Tab slug.
	 * @return bool
	 */
	public static function is_admin_only_tab( $tab ) {
		return in_array( sanitize_key( (string) $tab ), self::ADMIN_TAB_SLUGS, true );
	}
}
