<?php
/**
 * Booking email administration integration.
 *
 * @package TutorHelper_Bookings
 */

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

/**
 * Integrates Booking emails with the Booking Hub.
 */
final class TutorHelper_Booking_Email_Admin {

	/**
	 * Booking Hub tab key.
	 *
	 * @var string
	 */
	const TAB_KEY =
		'emails';

	/**
	 * Initialise admin hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_filter(
			'tutorhelper_booking_hub_tabs',
			array(
				__CLASS__,
				'register_tab',
			)
		);

		add_action(
			'tutorhelper_booking_hub_render_tab',
			array(
				__CLASS__,
				'render_tab',
			),
			10,
			2
		);
	}

	/**
	 * Add the Emails tab to the Booking Hub.
	 *
	 * @param array $tabs Existing tab definitions.
	 *
	 * @return array
	 */
	public static function register_tab(
		$tabs
	) {
		if ( ! is_array( $tabs ) ) {
			$tabs = array();
		}

		$tabs[
			self::TAB_KEY
		] =
			array(
				'label' =>
					__(
						'Emails',
						'tutorhelper-bookings'
					),

				'icon' =>
					'dashicons-email-alt',

				'status' =>
					'available',

				'description' =>
					__(
						'Manage automatic Booking email messages.',
						'tutorhelper-bookings'
					),
			);

		return $tabs;
	}

	/**
	 * Render the Booking email templates tab.
	 *
	 * @param string $selected_tab Selected Booking Hub tab.
	 * @param array  $active_tab   Active tab definition.
	 *
	 * @return void
	 */
	public static function render_tab(
		$selected_tab,
		$active_tab
	) {
		unset( $active_tab );

		if (
			self::TAB_KEY
			!== sanitize_key(
				$selected_tab
			)
		) {
			return;
		}

		if (
			! current_user_can(
				'manage_options'
			)
		) {
			return;
		}

		/**
		 * Allow an extension to replace the Booking Hub
		 * email-template interface.
		 *
		 * Returning true indicates that the Email tab has
		 * already been rendered by an extension.
		 *
		 * @param bool $rendered Whether an extension rendered the tab.
		 */
		$rendered_by_extension =
			apply_filters(
				'tutorhelper_booking_emails_rendered',
				false
			);

		if ( $rendered_by_extension ) {
			return;
		}

		TutorHelper_Email_Admin::
			render_module_templates(
				'bookings'
			);
	}
}
