<?php

namespace SugarCalendarBookings\Support\Admin;

use SugarCalendarBookings\Admin\Assets;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Bootable;
use SugarCalendarBookings\Support\Helpers\UI;
use SugarCalendarBookings\Support\Helpers\WP;

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

/**
 * Dismissible admin notices.
 *
 * @since 1.0.0
 *
 * @example Dismissible - global:
 *          Plugin::get( Notices::class )->error(
 *               'Fatal error!',
 *               [
 *                   'dismiss' => Notices::DISMISS_GLOBAL,
 *                   'slug'    => 'fatal_error_3678975',
 *               ]
 *          );
 *
 * @example Dismissible - per user:
 *          Plugin::get( Notices::class )->warning(
 *               'Do something please.',
 *               [
 *                   'dismiss' => Notices::DISMISS_USER,
 *                   'slug'    => 'do_something_1238943',
 *               ]
 *          );
 *
 * @example Dismissible - global, add custom class to output and disable auto paragraph in text:
 *          Plugin::get( Notices::class )->error(
 *               'Fatal error!',
 *               [
 *                   'dismiss' => Notices::DISMISS_GLOBAL,
 *                   'slug'    => 'fatal_error_348975',
 *                   'autop'   => false,
 *                   'class'   => 'some-additional-class',
 *               ]
 *          );
 *
 * @example Not dismissible:
 *          Plugin::get( Notices::class )->success( 'Everything is good!' );
 */
class Notices implements Bootable {

	/**
	 * Not dismissible.
	 *
	 * Constant attended to use as the value of the $args['dismiss'] argument.
	 * DISMISS_NONE means that the notice is not dismissible.
	 *
	 * @since 1.0.0
	 */
	const DISMISS_NONE = 0;

	/**
	 * Dismissible global.
	 *
	 * Constant attended to use as the value of the $args['dismiss'] argument.
	 * DISMISS_GLOBAL means that the notice will have the dismiss button, and after clicking this button, the notice will be dismissed for all users.
	 *
	 * @since 1.0.0
	 */
	const DISMISS_GLOBAL = 1;

	/**
	 * Dismissible per user.
	 *
	 * Constant attended to use as the value of the $args['dismiss'] argument.
	 * DISMISS_USER means that the notice will have the dismiss button, and after clicking this button, the notice will be dismissed only for the current user..
	 *
	 * @since 1.0.0
	 */
	const DISMISS_USER = 2;

	/**
	 * Order of notices by type.
	 *
	 * @since 1.0.0
	 */
	const ORDER = [
		'error',
		'warning',
		'info',
		'success',
	];

	/**
	 * Added notices.
	 *
	 * @since 1.0.0
	 *
	 * @var array
	 */
	private $notices = [];

	/**
	 * Hooks.
	 *
	 * @since 1.0.0
	 */
	public function hooks() {

		add_action( 'admin_notices', [ $this, 'display' ], PHP_INT_MAX );
		add_action( 'wp_ajax_sugar_calendar_bookings_notice_dismiss', [ $this, 'dismiss_ajax' ] );
		add_filter( 'removable_query_args', [ $this, 'query_notice_removable_query_args' ] );
	}

	/**
	 * Enqueue assets.
	 *
	 * @since 1.0.0
	 */
	private function enqueues() {

		$assets   = Plugin::get( Assets::class );
		$manifest = $assets->get_asset_manifest( 'admin/notices' );

		if ( ! $manifest ) {
			return;
		}

		wp_enqueue_script(
			'sugar-calendar-bookings-admin-notices',
			$assets->get_src( 'admin/notices.js' ),
			$manifest['dependencies'],
			$assets->is_dev() ? $manifest['version'] : SCBOOKINGS_PLUGIN_VERSION,
			true
		);

		wp_set_script_translations(
			'sugar-calendar-bookings-admin-notices',
			'sugar-calendar-bookings-scheduling-appointments-lite',
			SCBOOKINGS_PLUGIN_PATH . 'assets/languages'
		);

		wp_localize_script(
			'sugar-calendar-bookings-admin-notices',
			'sugar_calendar_bookings_admin_notices',
			[
				'ajax_url' => WP::admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'sugar-calendar-bookings-admin' ),
			]
		);
	}

	/**
	 * Display the notices.
	 *
	 * @since 1.0.0
	 */
	public function display() {

		if ( empty( $this->notices ) ) {
			return;
		}

		$dismissed_notices = get_user_meta( get_current_user_id(), 'sugar_calendar_bookings_admin_notices', true );
		$dismissed_notices = is_array( $dismissed_notices ) ? $dismissed_notices : [];
		$dismissed_notices = array_merge( $dismissed_notices, (array) get_option( 'sugar_calendar_bookings_admin_notices', [] ) );
		$dismissed_notices = array_filter( wp_list_pluck( $dismissed_notices, 'dismissed' ) );
		$this->notices     = array_diff_key( $this->notices, $dismissed_notices );

		$output = implode( '', array_column( $this->get_sorted_notices(), 'data' ) );

		echo wp_kses_post( $output );

		// Enqueue script.
		$this->enqueues();
	}

	/**
	 * Get sorted notices by type.
	 *
	 * @since 1.0.0
	 *
	 * @return array Notices.
	 */
	private function get_sorted_notices(): array {

		$ordered_notices = [];

		foreach ( self::ORDER as $order ) {
			foreach ( $this->notices as $key => $notice ) {
				if ( $notice['type'] === $order ) {
					$ordered_notices[ $key ] = $notice;

					unset( $this->notices[ $key ] );
				}
			}
		}

		// Notices that are not in the self::ORDER array merged to the end of array.
		return array_merge( $ordered_notices, $this->notices );
	}

	/**
	 * Add notice to the registry.
	 *
	 * @since 1.0.0
	 *
	 * @param string $message Message to display.
	 * @param string $type    Type of the notice. Can be [ '' (default) | 'info' | 'error' | 'success' | 'warning' ].
	 * @param array  $args    The array of additional arguments. Please see the $defaults array below.
	 */
	public function add( $message, $type = '', $args = [] ) { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		static $uniq_id = 0;

		$defaults = [
			'dismiss' => self::DISMISS_NONE,
			// Dismissible level: one of the self::DISMISS_* const. By default notice is not dismissible.
			'slug'    => '',
			// Slug. Should be unique if dismissible is not equal self::DISMISS_NONE.
			'autop'   => true,
			// `false` if not needed to pass message through wpautop().
			'class'   => '',
			// Additional CSS class.
		];

		$args = wp_parse_args( $args, $defaults );

		$dismissible = (int) $args['dismiss'];
		$dismissible = $dismissible > self::DISMISS_USER ? self::DISMISS_USER : $dismissible;

		$class  = $dismissible > self::DISMISS_NONE ? ' is-dismissible' : '';
		$global = ( $dismissible === self::DISMISS_GLOBAL ) ? 'global-' : '';
		$slug   = sanitize_key( $args['slug'] );

		++$uniq_id;

		$uniq_id += ( $uniq_id === (int) $slug ) ? 1 : 0;

		$notice = [
			'type' => $type,
		];

		$id             = 'sugar-calendar-bookings-notice-' . $global;
		$id            .= empty( $slug ) ? $uniq_id : $slug;
		$type           = ! empty( $type ) ? 'notice-' . esc_attr( sanitize_key( $type ) ) : '';
		$class          = empty( $args['class'] ) ? $class : $class . ' ' . UI::sanitize_class( $args['class'] );
		$message        = $args['autop'] ? wpautop( $message ) : $message;
		$notice['data'] = sprintf(
			'<div class="notice sugar-calendar-bookings-notice %s%s" id="%s">%s</div>',
			esc_attr( $type ),
			esc_attr( $class ),
			esc_attr( $id ),
			$message
		);

		if ( empty( $slug ) ) {
			$this->notices[] = $notice;
		} else {
			$this->notices[ $slug ] = $notice;
		}
	}

	/**
	 * Add info notice.
	 *
	 * @since 1.0.0
	 *
	 * @param string $message Message to display.
	 * @param array  $args    Array of additional arguments. Details in the self::add() method.
	 */
	public function info( $message, $args = [] ) {

		$this->add( $message, 'info', $args );
	}

	/**
	 * Add error notice.
	 *
	 * @since 1.0.0
	 *
	 * @param string $message Message to display.
	 * @param array  $args    Array of additional arguments. Details in the self::add() method.
	 */
	public function error( $message, $args = [] ) {

		$this->add( $message, 'error', $args );
	}

	/**
	 * Add success notice.
	 *
	 * @since 1.0.0
	 *
	 * @param string $message Message to display.
	 * @param array  $args    Array of additional arguments. Details in the self::add() method.
	 */
	public function success( $message, $args = [] ) {

		$this->add( $message, 'success', $args );
	}

	/**
	 * Add warning notice.
	 *
	 * @since 1.0.0
	 *
	 * @param string $message Message to display.
	 * @param array  $args    Array of additional arguments. Details in the self::add() method.
	 */
	public function warning( $message, $args = [] ) {

		$this->add( $message, 'warning', $args );
	}

	/**
	 * AJAX routine that updates dismissed notices meta data.
	 *
	 * @since 1.0.0
	 */
	public function dismiss_ajax() {

		if (
			! check_ajax_referer( 'sugar-calendar-bookings-admin', 'nonce', false ) ||
			! current_user_can( 'manage_options' )
		) {
			wp_send_json_error();
		}

		// Sanitize POST data.
		$post = array_map( 'sanitize_key', wp_unslash( $_POST ) );

		// Update notices meta data.
		if ( strpos( $post['id'], 'global-' ) !== false ) {
			$this->dismiss_global( $post['id'] );
		} else {
			$this->dismiss_user( $post['id'] );
		}

		wp_send_json_success();
	}

	/**
	 * AJAX sub-routine that updates dismissed notices option.
	 *
	 * @since 1.0.0
	 *
	 * @param string $id Notice Id.
	 */
	private function dismiss_global( $id ) {

		$id             = str_replace( 'global-', '', $id );
		$notices        = get_option( 'sugar_calendar_bookings_admin_notices', [] );
		$notices[ $id ] = [
			'time'      => time(),
			'dismissed' => true,
		];

		update_option( 'sugar_calendar_bookings_admin_notices', $notices, true );
	}

	/**
	 *  AJAX sub-routine that updates dismissed notices user meta.
	 *
	 * @since 1.0.0
	 *
	 * @param string $id Notice Id.
	 */
	private function dismiss_user( $id ) {

		$user_id        = get_current_user_id();
		$notices        = get_user_meta( $user_id, 'sugar_calendar_bookings_admin_notices', true );
		$notices        = ! is_array( $notices ) ? [] : $notices;
		$notices[ $id ] = [
			'time'      => time(),
			'dismissed' => true,
		];

		update_user_meta( $user_id, 'sugar_calendar_bookings_admin_notices', $notices );
	}

	/**
	 * Get query notice.
	 *
	 * @since 1.0.0
	 *
	 * @return string|null
	 */
	public function get_query_notice() {

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return isset( $_GET['scbookings-notice'] ) ? sanitize_key( wp_unslash( $_GET['scbookings-notice'] ) ) : null;
	}

	/**
	 * Get query notice data.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	public function get_query_notice_data() {

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return isset( $_GET['scbookings-notice-data'] ) ? explode( ',', sanitize_text_field( wp_unslash( $_GET['scbookings-notice-data'] ) ) ) : [];
	}

	/**
	 * Add query notice query args to the removable query args.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args The removable query args.
	 *
	 * @return array
	 */
	public function query_notice_removable_query_args( $args ) {

		$args[] = 'scbookings-notice';
		$args[] = 'scbookings-notice-data';

		return $args;
	}
}
