<?php
/**
 * Enrutador de peticiones HTTP.
 */

final class JB_Router {
	public static function dispatch() {
		$config_file = dirname( __DIR__ ) . '/config/config.php';
		$installed   = is_readable( dirname( __DIR__ ) . '/storage/.installed' );
		$script      = basename( $_SERVER['SCRIPT_NAME'] ?? 'index.php' );

		if ( ! $installed && ! in_array( $script, array( 'install.php' ), true ) ) {
			header( 'Location: install.php' );
			exit;
		}

		$uri = parse_url( $_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH );

		if ( 'ajax.php' === $script ) {
			JB_App::handle_ajax();
			return;
		}
		if ( 'post.php' === $script ) {
			JB_App::handle_post();
			return;
		}
		if ( 'admin.php' === $script ) {
			if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
				wp_safe_redirect( home_url( '/' ) );
				exit;
			}
			// La configuración completa vive en el panel del sitio (?config=1).
			wp_safe_redirect( add_query_arg( 'config', '1', home_url( '/' ) ) );
			exit;
		}
		if ( 'install.php' === $script ) {
			require JB_APP_ROOT . 'install/install.php';
			return;
		}
		if ( 'upload.php' === $script ) {
			require JB_APP_ROOT . 'public/upload.php';
			return;
		}
		if ( 'reset-password.php' === $script ) {
			require JB_APP_ROOT . 'public/reset-password.php';
			return;
		}
		if ( 'user-edit.php' === $script ) {
			require JB_APP_ROOT . 'public/user-edit.php';
			return;
		}
		if ( 'user-new.php' === $script ) {
			require JB_APP_ROOT . 'public/user-new.php';
			return;
		}

		// Panel principal.
		do_action( 'template_redirect' );
		JB_App::render_page();
	}
}
