<?php
/**
 * Settings section registry.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Admin\Settings;

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

/**
 * Collects all registered settings sections and exposes them to the JS layer.
 *
 * Core sections are added via {@see Registry::addSection()}.
 * Third-party plugins can add their own sections by filtering
 * `pdfdraft_woocommerce_settings_sections`.
 *
 * Example (add a custom section from another plugin):
 *
 *   add_filter( 'pdfdraft_woocommerce_settings_sections', function( array $sections ) {
 *       $sections[] = new MyCustomSection();
 *       return $sections;
 *   } );
 */
class Registry {

	/**
	 * Core sections registered by the plugin itself.
	 *
	 * @var SectionInterface[]
	 */
	private array $sections = [];

	/**
	 * Register a built-in section.
	 *
	 * @param SectionInterface $section Section to register.
	 * @return void
	 */
	public function addSection( SectionInterface $section ): void {
		$this->sections[] = $section;
	}

	/**
	 * Return all sections after applying third-party filters.
	 *
	 * @return SectionInterface[]
	 */
	public function getSections(): array {
		/**
		 * Filter the list of settings sections shown in the WooCommerce PDF settings sidebar.
		 *
		 * @param SectionInterface[] $sections Registered sections.
		 */
		return (array) apply_filters( 'pdfdraft_woocommerce_settings_sections', $this->sections );
	}

	/**
	 * Build the localized data array that will be passed to the settings JS bundle.
	 *
	 * The returned array always contains a `sections` key (sidebar items) plus any
	 * additional data each section contributes via {@see SectionInterface::getLocalizedData()}.
	 *
	 * @return array<string, mixed>
	 */
	public function getLocalizedData(): array {
		$data = array( 'sections' => array() );

		foreach ( $this->getSections() as $section ) {
			$data['sections'][] = array(
				'key'   => $section->getKey(),
				'label' => $section->getLabel(),
			);

			$data = array_merge( $data, $section->getLocalizedData() );
		}

		return $data;
	}
}
