<?php
/**
 * Serves a project's resolved config.json over the
 * ?tilvora_config=<project_id> URL so the visualizer engine
 * (assets/js/app.js) can load per-project configuration via its
 * existing ?config= override.
 */

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

add_action( 'template_redirect', 'tilvora_maybe_serve_config_feed' );

function tilvora_maybe_serve_config_feed() {
	if ( ! get_query_var( TILVORA_CONFIG_QUERY_VAR ) ) {
		return;
	}

	$project_id = absint( get_query_var( TILVORA_CONFIG_QUERY_VAR ) );

	if ( ! $project_id || ! tilvora_is_enabled_for_project( $project_id ) ) {
		status_header( 404 );
		header( 'Content-Type: application/json; charset=utf-8' );
		echo wp_json_encode( [ 'error' => 'Visualizer not found.' ] );
		exit;
	}

	nocache_headers();
	header( 'Content-Type: application/json; charset=utf-8' );
	$resolved = json_decode( tilvora_get_resolved_config_json( $project_id ), true );
	echo wp_json_encode( $resolved );
	exit;
}
