<?php
/**
 * Panel de operaciones (backend) sin shortcode.
 *
 * @package Logistica
 */

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

/**
 * Sirve el panel operativo mediante plantilla de página del plugin.
 */
final class Logistica_Backend {

	public const PAGE_TEMPLATE = 'jb-planeacion-operaciones.php';

	public const PAGE_SLUG = 'jb-planeacion-backend';

	/**
	 * @return void
	 */
	public static function init() {
		add_filter( 'theme_page_templates', array( __CLASS__, 'register_page_template' ) );
		add_filter( 'page_template', array( __CLASS__, 'load_page_template' ) );
		add_shortcode( 'logistica_backend', array( __CLASS__, 'render_shortcode' ) );
	}

	/**
	 * @param array<string, string> $templates Plantillas del tema.
	 * @return array<string, string>
	 */
	public static function register_page_template( $templates ) {
		$templates[ self::PAGE_TEMPLATE ] = __( 'JB Planeación — Operaciones', 'logistica' );
		return $templates;
	}

	/**
	 * @param string $template Ruta de plantilla del tema.
	 * @return string
	 */
	public static function load_page_template( $template ) {
		if ( ! is_singular( 'page' ) ) {
			return $template;
		}

		$page_id = (int) get_queried_object_id();
		if ( $page_id <= 0 ) {
			return $template;
		}

		$backend_page_id = class_exists( 'Logistica_Roles', false ) ? Logistica_Roles::get_backend_page_id() : 0;
		$page_template   = get_page_template_slug( $page_id );

		if ( ( $backend_page_id && $page_id === $backend_page_id ) || self::PAGE_TEMPLATE === $page_template ) {
			$plugin_template = self::get_template_path();
			if ( is_readable( $plugin_template ) ) {
				return $plugin_template;
			}
		}

		return $template;
	}

	/**
	 * @return string
	 */
	public static function get_template_path() {
		return LOGISTICA_PLUGIN_DIR . 'templates/page-jb-planeacion-operaciones.php';
	}

	/**
	 * @return void
	 */
	public static function render_panel_content() {
		if ( ! is_user_logged_in() ) {
			echo Logistica_Panel_Auth::render_login_screen(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			return;
		}

		if ( ! Logistica_Roles::user_can_access_plugin() ) {
			echo Logistica_Panel_Auth::render_denied_screen(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			return;
		}

		include LOGISTICA_PLUGIN_DIR . 'admin/views/backend-panel.php';
	}

	/**
	 * Compatibilidad con páginas antiguas que aún usan el shortcode.
	 *
	 * @return string
	 */
	public static function render_shortcode() {
		ob_start();
		self::render_panel_content();
		return (string) ob_get_clean();
	}
}
