<?php
/**
 * Aplicación principal JB Planeación.
 */

final class JB_App {
	private static $config = array();
	private static $activation_callbacks = array();
	private static $is_ajax = false;
	private static $is_admin = false;
	private static $current_post = null;
	private static $shortcodes = array();

	public static function load_config() {
		$config_file = dirname( __DIR__ ) . '/config/config.php';
		if ( ! is_readable( $config_file ) ) {
			$config_file = dirname( __DIR__ ) . '/config/config.example.php';
		}
		self::$config = require $config_file;
		$local_file   = dirname( __DIR__ ) . '/config/config.local.php';
		if ( is_readable( $local_file ) ) {
			$local = require $local_file;
			if ( is_array( $local ) ) {
				self::$config = array_replace_recursive( self::$config, $local );
			}
		}
		date_default_timezone_set( self::$config['timezone'] ?? 'America/Bogota' );
	}

	public static function config( $key = null, $default = null ) {
		if ( null === $key ) {
			return self::$config;
		}
		if ( str_contains( $key, '.' ) ) {
			$parts = explode( '.', $key );
			$val   = self::$config;
			foreach ( $parts as $p ) {
				if ( ! is_array( $val ) || ! array_key_exists( $p, $val ) ) {
					return $default;
				}
				$val = $val[ $p ];
			}
			return $val;
		}
		return self::$config[ $key ] ?? $default;
	}

	public static function is_debug() {
		return ( self::$config['app_env'] ?? 'production' ) === 'development';
	}

	public static function is_ajax() {
		return self::$is_ajax;
	}

	public static function set_ajax( $value ) {
		self::$is_ajax = (bool) $value;
	}

	public static function is_admin() {
		return self::$is_admin;
	}

	public static function set_admin( $value ) {
		self::$is_admin = (bool) $value;
	}

	public static function register_activation( $callback ) {
		self::$activation_callbacks[] = $callback;
	}

	public static function run_activation() {
		foreach ( self::$activation_callbacks as $cb ) {
			call_user_func( $cb );
		}
	}

	public static function set_current_post( $post ) {
		self::$current_post = $post;
	}

	public static function current_post() {
		return self::$current_post;
	}

	public static function add_shortcode( $tag, $callback ) {
		self::$shortcodes[ $tag ] = $callback;
	}

	public static function do_shortcode( $content ) {
		foreach ( self::$shortcodes as $tag => $callback ) {
			$pattern = '/\[' . preg_quote( $tag, '/' ) . '\]/';
			if ( preg_match( $pattern, $content ) ) {
				return call_user_func( $callback );
			}
		}
		return $content;
	}

	public static function bootstrap() {
		self::load_config();
		self::define_constants();
		self::load_core();
		self::init_services();
		self::load_application();
	}

	private static function define_constants() {
		if ( ! defined( 'ABSPATH' ) ) {
			define( 'ABSPATH', dirname( __DIR__ ) . '/' );
		}
		if ( ! defined( 'JB_APP_ROOT' ) ) {
			define( 'JB_APP_ROOT', dirname( __DIR__ ) . '/' );
		}
		if ( ! defined( 'JB_SRC_ROOT' ) ) {
			define( 'JB_SRC_ROOT', JB_APP_ROOT . 'src/' );
		}
	}

	private static function load_core() {
		require_once __DIR__ . '/WP_Error.php';
		require_once __DIR__ . '/WP_User.php';
		require_once __DIR__ . '/HookSystem.php';
		require_once __DIR__ . '/Database.php';
		require_once __DIR__ . '/dbDelta.php';
		require_once __DIR__ . '/Options.php';
		require_once __DIR__ . '/Password.php';
		require_once __DIR__ . '/Auth.php';
		require_once __DIR__ . '/Security.php';
		require_once __DIR__ . '/Http.php';
		require_once __DIR__ . '/Assets.php';
		require_once __DIR__ . '/Router.php';
		require_once __DIR__ . '/wp-compat.php';
	}

	private static function init_services() {
		/** @disregard P1009 Clase core cargada por require_once en load_core(). */
		JB_Database::init( self::config( 'db' ) );
		JB_Options::init( 'options' );
		JB_Auth::init();
	}

	private static function load_application() {
		require_once JB_SRC_ROOT . 'bootstrap.php';
		do_action( 'plugins_loaded' );
	}

	public static function render_page( $template = 'panel' ) {
		$post = (object) array(
			'ID'           => 1,
			'post_title'   => self::config( 'app_name' ),
			'post_content' => '',
			'post_type'    => 'page',
			'post_name'    => 'jb-planeacion-backend',
		);
		self::set_current_post( $post );

		do_action( 'wp_enqueue_scripts' );

		if ( ! empty( $_GET['config'] ) ) {
			add_filter(
				'body_class',
				static function ( $classes ) {
					$classes[] = 'logistica-config-panel-page';
					return $classes;
				}
			);
		} elseif ( ! empty( $_GET['public'] ) ) {
			add_filter(
				'body_class',
				static function ( $classes ) {
					$classes[] = 'logistica-panel-page';
					return $classes;
				}
			);
		} else {
			add_filter(
				'body_class',
				static function ( $classes ) {
					$classes[] = 'logistica-panel-page';
					return $classes;
				}
			);
		}

		include JB_APP_ROOT . 'templates/layout.php';
	}

	public static function render_admin_page() {
		self::set_admin( true );
		$post = (object) array(
			'ID'           => 2,
			'post_title'   => 'JB Planeación — Admin',
			'post_content' => '',
			'post_type'    => 'page',
			'post_name'    => 'logistica-admin',
		);
		self::set_current_post( $post );

		do_action( 'admin_enqueue_scripts', 'logistica' );

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

		add_filter(
			'body_class',
			static function ( $classes ) {
				return array_merge( (array) $classes, array( 'jb-planeacion-app', 'jb-admin', 'wp-admin' ) );
			}
		);

		/** @disregard P1009 Archivo de clase grande; Intelephense a veces no lo indexa. */
		$admin_menu = new Logistica_Admin_Menu();

		ob_start();
		$admin_menu->render_tabbed_page();
		$content = ob_get_clean();

		include JB_APP_ROOT . 'templates/admin-layout.php';
	}

	public static function handle_ajax() {
		self::set_ajax( true );
		$action = sanitize_key( $_REQUEST['action'] ?? '' );
		if ( '' === $action ) {
			wp_send_json_error( array( 'message' => 'Acción no especificada.' ), 400 );
		}
		do_action( 'wp_ajax_' . $action );
		if ( ! is_user_logged_in() ) {
			do_action( 'wp_ajax_nopriv_' . $action );
			wp_send_json_error(
				array(
					'message' => 'Sesión expirada. Vuelve a iniciar sesión.',
					'code'    => 'session_expired',
				),
				401
			);
		}
		wp_send_json_error( array( 'message' => 'Acción no registrada: ' . $action ), 404 );
	}

	public static function handle_post() {
		// Equivalente a admin-post.php de WordPress: muchas validaciones usan is_admin().
		self::set_admin( true );
		$action = sanitize_key( $_REQUEST['action'] ?? '' );
		if ( '' === $action ) {
			wp_die( 'Acción no especificada.' );
		}
		do_action( 'admin_post_' . $action );
		wp_die( 'Acción no registrada: ' . $action );
	}
}
