<?php
/**
 * Admin bootstrap routines for WP Mail Doctor email UI.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

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

/**
 * Shared bootstrap for the email admin controller.
 */
trait WPMD_Email_Admin_Init {


	/**
	 * Register admin actions.
	 *
	 * @return void
	 */
	public static function init(): void {
		if ( ! is_admin() ) {
			return;
		}

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
		add_action( 'admin_post_mail_doctor_save_template', array( __CLASS__, 'handle_save_template' ) );
		add_action( 'admin_post_mail_doctor_toggle_templates', array( __CLASS__, 'handle_toggle_templates' ) );
		add_action( 'admin_post_mail_doctor_restore_template', array( __CLASS__, 'handle_restore_template' ) );
	}

	/**
	 * Register top-level menu and submenus.
	 *
	 * @return void
	 */
	public static function register_menu(): void {
		$capability = self::capability();

		$parent_hook = add_menu_page(
			esc_html__( 'Mail Doctor', 'mail-doctor' ),
			esc_html__( 'Mail Doctor', 'mail-doctor' ),
			$capability,
			self::MENU_SLUG,
			array( __CLASS__, 'render_templates_page' ),
			'dashicons-email-alt',
			58
		);

		$templates_hook = add_submenu_page(
			self::MENU_SLUG,
			esc_html__( 'Email Templates', 'mail-doctor' ),
			esc_html__( 'Email Templates', 'mail-doctor' ),
			$capability,
			self::MENU_SLUG,
			array( __CLASS__, 'render_templates_page' )
		);

		$add_hook = add_submenu_page(
			self::MENU_SLUG,
			esc_html__( 'Add New Template', 'mail-doctor' ),
			esc_html__( 'Add New', 'mail-doctor' ),
			$capability,
			self::ADD_SLUG,
			array( __CLASS__, 'render_templates_page' )
		);

		self::$screen_hooks = array_filter( array( $parent_hook, $templates_hook, $add_hook ) );
	}

	/**
	 * Determine capability required for management.
	 *
	 * @return string
	 */
	protected static function capability(): string {
		return current_user_can( 'manage_woocommerce' ) ? 'manage_woocommerce' : 'manage_options';
	}

	/**
	 * Check if current admin hook matches template screens.
	 *
	 * @param string $hook Current admin hook.
	 * @return bool
	 */
	protected static function is_templates_screen( string $hook ): bool {
		return in_array( $hook, self::$screen_hooks, true );
	}
}
