<?php
/**
 * Admin menu registration and rendering.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Admin;

use PDFDraft\Traits\Hooks;
use PDFDraft\Woocommerce\Admin\Settings\Registry;

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

/**
 * Registers PDFDraft WooCommerce submenus and the unified settings section.
 */
class Menu {

	use Hooks;

	/**
	 * Settings registry — used to derive sub-section children for the unified sidebar.
	 *
	 * @var Registry
	 */
	private Registry $registry;

	/**
	 * @param Registry $registry Settings section registry.
	 */
	public function __construct( Registry $registry ) {
		$this->registry = $registry;
	}

	/**
	 * Register WordPress hooks for admin menu.
	 *
	 * @return void
	 */
	public function initHooks() {
		$this->addFilter( 'pdfdraft_settings_sections', array( $this, 'registerSettingsSection' ) );
	}

	/**
	 * Add the WooCommerce Invoices editor link to the PDFDraft menu.
	 *
	 * The separate settings page has been merged into the main PDFDraft settings page.
	 *
	 * @param array $items Existing submenu items.
	 * @return array Modified submenu items.
	 */
	public function registerSubmenus( array $items ) {
		$items[] = array(
			'slug'       => 'pdfdraft-pdf-invoices-for-woocommerce',
			'page_title' => __( 'Woo Invoices', 'pdfdraft-pdf-invoices-for-woocommerce' ),
			'menu_title' => __( 'Woo Invoices', 'pdfdraft-pdf-invoices-for-woocommerce' ),
			'capability' => 'edit_posts',
			'callback'   => array( $this, 'redirectToPdfDraftForWooCommerce' ),
		);
		return $items;
	}

	/**
	 * Register the WooCommerce Invoices section in the unified PDFDraft settings page.
	 *
	 * The `children` array tells the main settings sidebar what sub-sections to render
	 * as nested items beneath "WooCommerce Invoices". Each child's `key` matches the
	 * key used by the inner React section registry (e.g. 'invoices', 'storage').
	 *
	 * @param array $sections Existing settings sections.
	 * @return array Modified settings sections.
	 */
	public function registerSettingsSection( array $sections ): array {
		$localized_data = $this->registry->getLocalizedData();

		$children = array_map(
			function ( $s ) {
				return array(
					'key'   => $s['key'],
					'label' => $s['label'],
				);
			},
			$localized_data['sections'] ?? array()
		);

		$sections[] = array(
			'key'        => 'woocommerce-invoices',
			'label'      => __( 'WooCommerce', 'pdfdraft-pdf-invoices-for-woocommerce' ),
			'capability' => 'manage_options',
			'children'   => $children,
		);
		return $sections;
	}

	/**
	 * Redirect to the PDFDraft editor filtered for WooCommerce.
	 *
	 * @return void
	 */
	public function redirectToPdfDraftForWooCommerce() {
		wp_safe_redirect(
			admin_url( 'admin.php?page=pdfdraft&for=woo' )
		);
		exit;
	}
}
