<?php
/**
 * Sections
 *
 * Renders each settings tab section as a method.
 * Called by Page::render() - keeps the page class lean.
 *
 * @package Relatedly\Admin\Settings
 * @since   2.0.0
 */

namespace Relatedly\Admin\Settings;

use Relatedly\Core\Options;

defined( 'ABSPATH' ) || exit;

/**
 * Renders settings tab templates and navigation metadata.
 *
 * @since 2.0.0
 */
class Sections {

	/**
	 * Plugin settings repository.
	 *
	 * @since 2.0.0
	 * @var Options
	 */
	private Options $options;

	/**
	 * Create the settings sections renderer.
	 *
	 * @since 2.0.0
	 * @param Options $options Plugin settings repository.
	 */
	public function __construct( Options $options ) {
		$this->options = $options;
	}

	/**
	 * Render a tab partial from templates/admin/.
	 *
	 * @param string $template Filename without path, e.g. 'tab-general.php'.
	 * @since 2.0.0
	 */
	public function render( string $template ): void {
		$path = RELATEDLY_PLUGIN_DIR . 'templates/admin/' . $template;
		if ( file_exists( $path ) ) {
			$options = $this->options;
			include $path;
		}
	}

	/**
	 * Return the list of tabs with their keys and labels.
	 *
	 * @return array<string, string>
	 * @since 2.0.0
	 * @since 2.2.0 Reordered settings tabs to match the admin prototype.
	 */
	public function tabs(): array {
		return array(
			'general'          => __( 'General', 'relatedly' ),
			'inline'           => __( 'Inline Posts', 'relatedly' ),
			'end-content'      => __( 'End of Content', 'relatedly' ),
			'floating-sidebar' => __( 'Floating Sidebar', 'relatedly' ),
			'rss'              => __( 'RSS Feed', 'relatedly' ),
			'email'            => __( 'Email Reports', 'relatedly' ),
		);
	}

	/**
	 * Return the active tab key, defaulting to 'general'.
	 *
	 * @since 2.0.0
	 * @since 2.2.0 Defaulted the settings page to the setup tab.
	 */
	public function active_tab(): string {
		// Read-only tab-navigation parameter - selects which settings tab renders.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$tab  = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'general';
		$tabs = $this->tabs();

		return array_key_exists( $tab, $tabs ) ? $tab : 'general';
	}
}
