<?php
/**
 * Admin menu registration.
 *
 * @package MarketingConsole
 */

namespace MarketingConsole\Admin;

use MarketingConsole\Admin\Free\DashboardScreen;

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

/**
 * Registers the top-level screen and its POST-only handlers.
 */
final class Menu {

	private DashboardScreen $free_screen;

	/**
	 * @param DashboardScreen $free_screen Local FREE dashboard.
	 */
	public function __construct( DashboardScreen $free_screen ) {
		$this->free_screen = $free_screen;
	}

	/**
	 * Register WordPress hooks.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_menu', array( $this, 'add_menu' ) );
	}

	/**
	 * Add the Speedlyst top-level menu.
	 *
	 * @return void
	 */
	public function add_menu(): void {
		add_menu_page(
			__( 'Speedlyst', 'speedlyst' ),
			__( 'Speedlyst', 'speedlyst' ),
			'manage_options',
			DashboardScreen::PAGE_SLUG,
			array( $this->free_screen, 'render' ),
			$this->menu_icon(),
			58
		);
	}

	/**
	 * Menu icon as a base64 SVG data URI, which WordPress recolors to the admin
	 * color scheme (svg-painter.js) including hover and active states. The SVG
	 * uses currentColor, so a plain file URL or PNG would stay one fixed color
	 * and could vanish on the dark menu; the data URI is the form WP repaints.
	 *
	 * @return string Data URI, or a dashicon fallback when the file is missing.
	 */
	private function menu_icon(): string {
		if ( ! defined( 'MARKETING_CONSOLE_DIR' ) ) {
			return 'dashicons-performance';
		}

		$path = constant( 'MARKETING_CONSOLE_DIR' ) . '/assets/img/menu-icon.svg';
		$svg  = is_readable( $path ) ? file_get_contents( $path ) : false;

		// file_get_contents může vrátit false i po úspěšném is_readable (TOCTOU,
		// I/O chyba), proto se testuje i typ, ne jen prázdný řetězec.
		if ( ! is_string( $svg ) || '' === $svg ) {
			return 'dashicons-performance';
		}

		return 'data:image/svg+xml;base64,' . base64_encode( $svg );
	}
}
