<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Notifications {

	public function __construct() {
		$this->register_hooks();
	}

	private function register_hooks() {
		add_action( 'admin_notices', array( $this, 'show_in_dashboard_notices' ) );
		add_action( 'wp_ajax_zacls_dismiss_notification', array( $this, 'ajax_dismiss' ) );
	}

	public static function add( $type, $message, $dismissible = true, $user_id = 0 ) {
		if ( ! $user_id ) {
			$user_id = get_current_user_id();
		}
		if ( ! $user_id ) {
			return;
		}

		$notifications = get_user_meta( $user_id, 'zacls_notifications', true );
		if ( ! is_array( $notifications ) ) {
			$notifications = array();
		}

		$notifications[] = array(
			'id'        => uniqid( 'zacls_' ),
			'type'      => sanitize_key( $type ),
			'message'   => wp_kses_post( $message ),
			'dismissible'=> (bool) $dismissible,
			'created'   => current_time( 'mysql' ),
			'dismissed' => false,
		);

		if ( count( $notifications ) > 50 ) {
			array_shift( $notifications );
		}

		update_user_meta( $user_id, 'zacls_notifications', $notifications );
	}

	public static function get_all( $user_id = 0 ) {
		if ( ! $user_id ) {
			$user_id = get_current_user_id();
		}
		if ( ! $user_id ) {
			return array();
		}

		$notifications = get_user_meta( $user_id, 'zacls_notifications', true );
		if ( ! is_array( $notifications ) ) {
			return array();
		}

		$active = array();
		foreach ( $notifications as $n ) {
			if ( empty( $n['dismissed'] ) ) {
				$active[] = $n;
			}
		}

		return $active;
	}

	public static function count_unread( $user_id = 0 ) {
		return count( self::get_all( $user_id ) );
	}

	public function show_in_dashboard_notices() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$notifications = self::get_all();

		foreach ( $notifications as $n ) {
			$classes = 'notice notice-' . esc_attr( $n['type'] );
			if ( $n['dismissible'] ) {
				$classes .= ' is-dismissible zacls-notification';
			}
			?>
			<div class="<?php echo esc_attr( $classes ); ?>" data-notification-id="<?php echo esc_attr( $n['id'] ); ?>">
				<p><?php echo wp_kses_post( $n['message'] ); ?></p>
			</div>
			<?php
		}
	}

	public function ajax_dismiss() {
		check_ajax_referer( 'zacls_admin_nonce', 'nonce' );

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

		$id      = isset( $_POST['id'] ) ? sanitize_text_field( wp_unslash( $_POST['id'] ) ) : '';
		$user_id = get_current_user_id();

		$notifications = get_user_meta( $user_id, 'zacls_notifications', true );
		if ( ! is_array( $notifications ) ) {
			wp_send_json_error();
		}

		foreach ( $notifications as &$n ) {
			if ( $n['id'] === $id ) {
				$n['dismissed'] = true;
				break;
			}
		}

		update_user_meta( $user_id, 'zacls_notifications', $notifications );
		wp_send_json_success();
	}
}
