<?php
/**
 * Settings Page
 *
 * Renders the main Relatedly settings page.
 * Uses template partials from templates/admin/ — no HTML in PHP strings.
 *
 * @package Relatedly\Admin\Settings
 * @since   2.0.0
 */

namespace Relatedly\Admin\Settings;

use Relatedly\Core\Options;
use Relatedly\Admin\SidebarBoxes;

defined( 'ABSPATH' ) || exit;

/**
 * Renders the main settings page and notices.
 *
 * @since 2.0.0
 */
class Page {

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

	/**
	 * Settings sections renderer.
	 *
	 * @since 2.0.0
	 * @var Sections
	 */
	private Sections $sections;

	/**
	 * Sidebar boxes renderer.
	 *
	 * @since 2.0.0
	 * @var SidebarBoxes
	 */
	private SidebarBoxes $sidebar;

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

	/**
	 * Register settings page notice hooks.
	 *
	 * @since 2.0.0
	 */
	public function init_hooks(): void {
		add_action( 'admin_notices', [ $this, 'show_notices' ] );
	}

	/**
	 * Render the full settings page.
	 *
	 * @since 2.0.0
	 */
	public function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$active_tab = $this->sections->active_tab();
		$tabs       = $this->sections->tabs();
		$options    = $this->options;
		$sections   = $this->sections;
		$sidebar    = $this->sidebar;

		include RELATEDLY_PLUGIN_DIR . 'templates/admin/settings-header.php';
	}

	/**
	 * Show save/reset/error notices from redirect query args.
	 *
	 * @since 2.0.0
	 */
	public function show_notices(): void {
		$screen = get_current_screen();
		if ( ! $screen || 'toplevel_page_relatedly' !== $screen->id ) {
			return;
		}

		// Read-only display parameter — drives which success/error notice to show after redirect.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$message = isset( $_GET['message'] ) ? sanitize_key( $_GET['message'] ) : '';

		$notices = [
			'saved'         => [ 'success', __( 'Settings saved.', 'relatedly' ) ],
			'reset'         => [ 'success', __( 'Settings reset to defaults.', 'relatedly' ) ],
			'cache_cleared' => [ 'success', __( 'Cache cleared.', 'relatedly' ) ],
			'error'         => [ 'error', __( 'An error occurred. Please try again.', 'relatedly' ) ],
		];

		if ( ! isset( $notices[ $message ] ) ) {
			return;
		}

		[ $type, $text ] = $notices[ $message ];
		printf(
			'<div class="notice notice-%s is-dismissible"><p>%s</p></div>',
			esc_attr( $type ),
			esc_html( $text )
		);
	}
}
