<?php
/**
 * Serves the published Materials Library as JSON over the
 * ?tilvora_materials=1 URL, so any visualizer's "material-grid"
 * controls can fetch the full product catalog once (assets/js/app.js
 * then filters by each control's own "target" client-side). Mirrors
 * config-endpoint.php's pattern.
 */

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

add_action( 'template_redirect', 'tilvora_maybe_serve_materials_feed' );

function tilvora_maybe_serve_materials_feed() {
	if ( ! get_query_var( TILVORA_MATERIALS_QUERY_VAR ) ) {
		return;
	}

	nocache_headers();
	header( 'Content-Type: application/json; charset=utf-8' );

	$posts = get_posts( [
		'post_type'      => TILVORA_MATERIAL_CPT,
		'post_status'    => 'publish',
		'posts_per_page' => -1,
		'orderby'        => 'title',
		'order'          => 'ASC',
		'fields'         => 'ids',
	] );

	$materials = array_map( 'tilvora_get_material_array', $posts );

	echo wp_json_encode( $materials );
	exit;
}
