<?php
/**
 * Frontend panel rendering.
 *
 * @package Logistica
 */

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

/**
 * Provides the public shortcode for the inventory panel.
 */
class Logistica_Frontend {
	/**
	 * Registers frontend hooks.
	 *
	 * @return void
	 */
	public function init() {
		add_shortcode( 'logistica_panel', array( $this, 'render_panel' ) );
		add_shortcode( 'latingraf_inventarios', array( $this, 'render_panel' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'template_redirect', array( $this, 'redirect_legacy_cierre_caracteristicas' ) );
		add_filter( 'body_class', array( $this, 'body_class' ) );
	}

	/**
	 * Redirige URLs antiguas del submenú de cierre en el panel público.
	 *
	 * @return void
	 */
	public function redirect_legacy_cierre_caracteristicas() {
		if ( ! is_singular() ) {
			return;
		}

		$post = get_post();
		if ( ! $this->is_panel_page( $post ) ) {
			return;
		}

		require_once LOGISTICA_PLUGIN_DIR . 'admin/views/partials.php';
		logistica_redirect_legacy_cierre_caracteristicas_section();
	}

	/**
	 * Marks pages that render the inventory panel so theme title bars can be hidden.
	 *
	 * @param string[] $classes Body classes.
	 * @return string[]
	 */
	public function body_class( $classes ) {
		if ( ! is_singular() ) {
			return $classes;
		}

		$post = get_post();
		if ( $this->is_panel_page( $post ) ) {
			$classes[] = 'logistica-panel-page';
			require_once LOGISTICA_PLUGIN_DIR . 'admin/views/partials.php';
			if ( logistica_is_config_panel() ) {
				$classes[] = 'logistica-config-panel-page';
			}
		}

		return $classes;
	}

	/**
	 * Loads frontend assets when the panel page or shortcode is present.
	 *
	 * @return void
	 */
	public function enqueue_assets() {
		if ( ! is_singular() ) {
			return;
		}

		$post = get_post();
		if ( ! $this->is_panel_page( $post ) ) {
			return;
		}

		require_once LOGISTICA_PLUGIN_DIR . 'admin/views/partials.php';
		$is_config_route = ! empty( $_GET['config'] );
		$is_config_panel = logistica_is_config_panel();
		$panel_context   = logistica_get_panel_context_for_post( $post );
		$asset_context   = $is_config_panel
			? 'config'
			: ( in_array( $panel_context, array( 'backend', 'frontend', 'operations' ), true ) ? 'operations' : $panel_context );

		wp_enqueue_style( 'dashicons' );

		wp_enqueue_style(
			'logistica-admin',
			LOGISTICA_PLUGIN_URL . 'assets/css/admin.css',
			array( 'dashicons' ),
			logistica_asset_version( 'assets/css/admin.css' )
		);

		wp_register_script( 'logistica-panel-loader-guard', false, array(), LOGISTICA_VERSION, false );
		wp_enqueue_script( 'logistica-panel-loader-guard' );
		wp_add_inline_script(
			'logistica-panel-loader-guard',
			"(function(){function removeThemeLoader(){var loader=document.getElementById('loader');if(!loader){return false;}loader.classList.remove('show');loader.remove();return true;}if(!removeThemeLoader()){new MutationObserver(function(mutations,observer){if(removeThemeLoader()){observer.disconnect();}}).observe(document.documentElement,{childList:true,subtree:true});}}());"
		);

		wp_enqueue_style(
			'logistica-user-panel',
			LOGISTICA_PLUGIN_URL . 'assets/css/panel.css',
			array( 'logistica-admin' ),
			logistica_asset_version( 'assets/css/panel.css' )
		);

		if ( $is_config_route ) {
			wp_enqueue_style(
				'logistica-config-panel',
				LOGISTICA_PLUGIN_URL . 'assets/css/config-panel.css',
				array( 'logistica-user-panel' ),
				logistica_asset_version( 'assets/css/config-panel.css' )
			);
		}

		Logistica_Panel_Auth::enqueue_assets();

		if ( ! is_user_logged_in() ) {
			return;
		}

		if ( $is_config_panel ) {
			if ( ! Logistica_Roles::user_can_manage_config() ) {
				return;
			}
		} elseif ( 'operations' === $panel_context || 'frontend' === $panel_context || 'backend' === $panel_context ) {
			if ( ! Logistica_Roles::user_can_access_plugin() ) {
				return;
			}
		} elseif ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( is_user_logged_in() && current_user_can( 'upload_files' ) && function_exists( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}

		Logistica_Label_Print::register_assets();
		Logistica_Rotulo_Rollos_Print::register_assets();
		Logistica_Orden_Produccion_Vasos::register_assets();

		Logistica_Panel_Auth::enqueue_session_guard();

		wp_enqueue_script(
			'logistica-panel-nav',
			LOGISTICA_PLUGIN_URL . 'assets/js/panel-nav.js',
			array( 'logistica-panel-loader-guard', 'logistica-session-guard' ),
			logistica_asset_version( 'assets/js/panel-nav.js' ),
			true
		);

		wp_enqueue_script(
			'logistica-config-nav',
			LOGISTICA_PLUGIN_URL . 'assets/js/config-nav.js',
			array( 'logistica-panel-nav' ),
			logistica_asset_version( 'assets/js/config-nav.js' ),
			true
		);

		wp_enqueue_script(
			'logistica-admin',
			LOGISTICA_PLUGIN_URL . 'assets/js/admin.js',
			array( 'logistica-session-guard', 'logistica-panel-nav', 'logistica-config-nav', 'logistica-label-print', 'logistica-rotulo-rollos-print', 'logistica-rotulo-estibas-print', 'logistica-orden-produccion-vasos' ),
			logistica_asset_version( 'assets/js/admin.js' ),
			true
		);

		if ( $is_config_panel ) {
			wp_enqueue_script(
				'logistica-menu-order',
				LOGISTICA_PLUGIN_URL . 'assets/js/menu-order.js',
				array(),
				logistica_asset_version( 'assets/js/menu-order.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-lifecycle-tables',
				LOGISTICA_PLUGIN_URL . 'assets/js/lifecycle-tables.js',
				array( 'logistica-admin' ),
				logistica_asset_version( 'assets/js/lifecycle-tables.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-user-admin',
				LOGISTICA_PLUGIN_URL . 'assets/js/user-admin.js',
				array(),
				logistica_asset_version( 'assets/js/user-admin.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-role-permissions-modal',
				LOGISTICA_PLUGIN_URL . 'assets/js/role-permissions-modal.js',
				array(),
				logistica_asset_version( 'assets/js/role-permissions-modal.js' ),
				true
			);

			if ( function_exists( 'wp_enqueue_editor' ) ) {
				wp_enqueue_editor();
			}
		}

		wp_enqueue_script(
			'logistica-user-panel',
			LOGISTICA_PLUGIN_URL . 'assets/js/panel.js',
			array( 'logistica-session-guard' ),
			logistica_asset_version( 'assets/js/panel.js' ),
			true
		);

		wp_enqueue_script(
			'logistica-user-panel-nav',
			LOGISTICA_PLUGIN_URL . 'assets/js/user-panel-nav.js',
			array( 'logistica-panel-nav' ),
			logistica_asset_version( 'assets/js/user-panel-nav.js' ),
			true
		);

		wp_localize_script(
			'logistica-user-panel',
			'LogisticaUserPanel',
			array_merge(
				array(
					'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
					'userPanelNonce' => wp_create_nonce( 'logistica_user_panel' ),
					'navTabs'        => logistica_get_nav_tabs(),
					'navTabUrls'     => ( static function () use ( $asset_context ) {
						$urls = array();
						foreach ( logistica_get_nav_tabs() as $slug => $label ) {
							$urls[ $slug ] = logistica_tab_url( $slug, $asset_context );
						}
						return $urls;
					} )(),
				),
				Logistica_User_Panel::client_config()
			)
		);

		$visible_slugs = array_keys( logistica_get_nav_tabs_for_context( $asset_context ) );

		if ( ! $is_config_panel ) {
			if ( in_array( 'logistica-planeacion-impresion', $visible_slugs, true ) ) {
			wp_enqueue_script(
				'chart-js',
				'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js',
				array(),
				'4.4.1',
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-metrics',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-metrics.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-metrics.js' ),
				true
			);

			wp_enqueue_style(
				'logistica-planeacion-impresion',
				LOGISTICA_PLUGIN_URL . 'assets/css/planeacion-impresion.css',
				array( 'logistica-admin' ),
				logistica_asset_version( 'assets/css/planeacion-impresion.css' )
			);

			wp_enqueue_script(
				'logistica-planeacion-planner',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-planner.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-planner.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-task-colors',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-task-colors.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-task-colors.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-pedidos-bridge',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-pedidos-bridge.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-pedidos-bridge.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-impresion',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-impresion.js',
				array( 'logistica-admin', 'logistica-planeacion-metrics', 'logistica-planeacion-planner', 'logistica-planeacion-task-colors', 'logistica-planeacion-pedidos-bridge', 'chart-js' ),
				logistica_asset_version( 'assets/js/planeacion-impresion.js' ),
				true
			);
		}

		if ( in_array( 'logistica-planeacion-formado', $visible_slugs, true ) ) {
			wp_enqueue_script(
				'chart-js',
				'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js',
				array(),
				'4.4.1',
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-metrics',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-metrics.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-metrics.js' ),
				true
			);

			wp_enqueue_style(
				'logistica-planeacion-formado',
				LOGISTICA_PLUGIN_URL . 'assets/css/planeacion-impresion.css',
				array( 'logistica-admin' ),
				logistica_asset_version( 'assets/css/planeacion-impresion.css' )
			);

			wp_enqueue_script(
				'logistica-planeacion-planner',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-planner.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-planner.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-task-colors',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-task-colors.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-task-colors.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-pedidos-bridge',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-pedidos-bridge.js',
				array(),
				logistica_asset_version( 'assets/js/planeacion-pedidos-bridge.js' ),
				true
			);

			wp_enqueue_script(
				'logistica-planeacion-formado',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-formado.js',
				array( 'logistica-admin', 'logistica-planeacion-metrics', 'logistica-planeacion-planner', 'logistica-planeacion-task-colors', 'logistica-planeacion-pedidos-bridge', 'chart-js' ),
				logistica_asset_version( 'assets/js/planeacion-formado.js' ),
				true
			);
		}

		if ( in_array( 'logistica-cuadro-pedidos', $visible_slugs, true ) ) {
			wp_enqueue_style(
				'logistica-planeacion-formado',
				LOGISTICA_PLUGIN_URL . 'assets/css/planeacion-impresion.css',
				array( 'logistica-admin' ),
				logistica_asset_version( 'assets/css/planeacion-impresion.css' )
			);
			wp_enqueue_script(
				'chart-js',
				'https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js',
				array(),
				'4.4.1',
				true
			);
			wp_enqueue_script(
				'logistica-planeacion-metrics',
				LOGISTICA_PLUGIN_URL . 'assets/js/planeacion-metrics.js',
				array( 'chart-js' ),
				logistica_asset_version( 'assets/js/planeacion-metrics.js' ),
				true
			);
			wp_enqueue_script(
				'logistica-pedidos-board',
				LOGISTICA_PLUGIN_URL . 'assets/js/pedidos-board.js',
				array( 'logistica-admin', 'logistica-planeacion-metrics', 'chart-js' ),
				logistica_asset_version( 'assets/js/pedidos-board.js' ),
				true
			);
		}

		if ( in_array( 'logistica-tablero-produccion', $visible_slugs, true ) ) {
			wp_enqueue_style(
				'logistica-tablero-produccion',
				LOGISTICA_PLUGIN_URL . 'assets/css/tablero-produccion.css',
				array( 'logistica-admin' ),
				logistica_asset_version( 'assets/css/tablero-produccion.css' )
			);
			wp_enqueue_script(
				'logistica-tablero-produccion',
				LOGISTICA_PLUGIN_URL . 'assets/js/tablero-produccion.js',
				array( 'logistica-admin' ),
				logistica_asset_version( 'assets/js/tablero-produccion.js' ),
				true
			);
		}
		}

		wp_localize_script(
			'logistica-admin',
			'LogisticaAdmin',
			array(
				'ajaxUrl'               => admin_url( 'admin-ajax.php' ),
				'cierreAutosaveNonce'  => wp_create_nonce( 'logistica_autosave_cierre_ordenes' ),
				'cierreRefreshNonce'   => wp_create_nonce( 'logistica_refresh_cierre_bases' ),
				'cierreNonce'          => wp_create_nonce( 'logistica_cierre_ordenes' ),
				'cierreCaracteristicasNonce' => wp_create_nonce( 'logistica_cierre_caracteristicas' ),
				'conversionTemplatesNonce' => wp_create_nonce( 'logistica_conversion_templates' ),
				'conversionTablesNonce'    => wp_create_nonce( 'logistica_conversion_tables' ),
				'warehouseNonce'           => wp_create_nonce( 'logistica_warehouse_inventory' ),
				'minutasNonce'             => wp_create_nonce( 'logistica_minutas' ),
				'planeacionNonce'          => wp_create_nonce( 'logistica_planeacion_impresion' ),
				'planeacionExportNonce'    => wp_create_nonce( 'logistica_export_planeacion_impresion' ),
				'planeacionFormadoNonce'   => wp_create_nonce( 'logistica_planeacion_formado' ),
				'planeacionFormadoExportNonce' => wp_create_nonce( 'logistica_export_planeacion_formado' ),
				'tableroProduccionNonce'   => wp_create_nonce( 'logistica_tablero_produccion' ),
				'userPanelNonce'           => wp_create_nonce( 'logistica_user_panel' ),
				'labelPrintNonce'          => wp_create_nonce( 'logistica_label_print' ),
				'labelPrintConfig'         => Logistica_Label_Print::client_config(),
				'rotulosRollosNonce'       => wp_create_nonce( 'logistica_rotulos_rollos' ),
				'rotuloRollosPrintConfig'  => Logistica_Rotulo_Rollos_Print::client_config(),
				'pedidosBoardNonce'        => wp_create_nonce( 'logistica_pedidos_board' ),
				'jsBarcodeUrl'             => LOGISTICA_PLUGIN_URL . 'assets/js/vendor/jsbarcode.all.min.js',
				'adminPostUrl'             => admin_url( 'admin-post.php' ),
				'navTabs'                  => logistica_get_nav_tabs(),
				'navTabUrls'               => ( static function () use ( $asset_context ) {
					$urls = array();
					foreach ( logistica_get_nav_tabs() as $slug => $label ) {
						$urls[ $slug ] = logistica_tab_url( $slug, $asset_context );
					}
					return $urls;
				} )(),
				'closingRollTypes'     => Logistica_Order_Closing::base_types_roll_like(),
				'closingSheetTypes'    => Logistica_Order_Closing::base_types_sheet_like(),
				'closingFormulaLabels' => Logistica_Order_Closing::formula_options(),
				'closingBaseLabels'    => Logistica_Order_Closing::base_type_options(),
				'closingBaseTypeFields' => Logistica_Order_Closing::get_base_type_fields_map(),
				'closingBaseFieldDefinitions' => Logistica_Order_Closing::base_field_definitions(),
				'lifecycleNonce'       => wp_create_nonce( 'logistica_lifecycle' ),
				'canRestoreLifecycle'  => Logistica_Entity_Lifecycle::can_restore(),
				'canPurgeLifecycle'    => Logistica_Entity_Lifecycle::can_purge(),
				'selectCatalogNonce'   => wp_create_nonce( 'logistica_select_catalog' ),
				'tabPanelNonce'        => wp_create_nonce( 'logistica_tab_panel' ),
			)
		);
	}

	/**
	 * Renders the complete inventory panel on the frontend.
	 *
	 * @return string
	 */
	public function render_panel() {
		if ( ! is_user_logged_in() ) {
			return Logistica_Panel_Auth::render_login_screen();
		}

		if ( ! Logistica_Roles::user_can_access_plugin() ) {
			return Logistica_Panel_Auth::render_denied_screen();
		}

		ob_start();
		include LOGISTICA_PLUGIN_DIR . 'admin/views/frontend-panel.php';
		return ob_get_clean();
	}

	/**
	 * @param WP_Post|null $post Post object.
	 * @return bool
	 */
	private function is_panel_page( $post ) {
		require_once LOGISTICA_PLUGIN_DIR . 'admin/views/partials.php';

		return logistica_is_panel_post( $post );
	}
}
