<?php
namespace AcademyProNotifications\Frontend;

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

use AcademyProNotifications\Helper;

class Ajax {
	public static function init() {
		$self = new self();
		add_action( 'wp_ajax_academy_pro_notifications/frontend/render_notifications', array( $self, 'render_notifications' ) );
		add_action( 'wp_ajax_academy_pro_notifications/frontend/mark_as_read_notifications', array( $self, 'mark_as_read_notifications' ) );
		add_action( 'wp_ajax_academy_pro_notifications/frontend/mark_as_unread_notifications', array( $self, 'mark_as_unread_notifications' ) );
		add_action( 'wp_ajax_academy_pro_notifications/frontend/delete_notifications', array( $self, 'delete_notifications' ) );
	}

	public function render_notifications() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! is_user_logged_in() ) {
			wp_die();
		}
		$user_id = get_current_user_id();
		$response = Helper::get_all_notifications_by_user_id( $user_id );
		wp_send_json_success( $response );
	}

	public function mark_as_read_notifications() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! is_user_logged_in() ) {
			wp_die();
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		$notification_id = isset( $_POST['ID'] ) ? sanitize_text_field( $_POST['ID'] ) : 0;

		if ( ! $notification_id ) {
			wp_send_json_success( array( 'message' => __( 'Please provide Notification ID', 'academy-pro' ) ) );
		}

		if ( Helper::mark_as_read( $notification_id ) ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}

	public function mark_as_unread_notifications() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! is_user_logged_in() ) {
			wp_die();
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		$notification_id = isset( $_POST['ID'] ) ? sanitize_text_field( $_POST['ID'] ) : 0;

		if ( Helper::mark_as_unread( $notification_id ) ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}

	public function delete_notifications() {
		check_ajax_referer( 'academy_nonce', 'security' );
		if ( ! is_user_logged_in() ) {
			wp_die();
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash 
		$notification_id = isset( $_POST['ID'] ) ? sanitize_text_field( $_POST['ID'] ) : 0;

		if ( Helper::delete_notification( $notification_id ) ) {
			wp_send_json_success();
		}

		wp_send_json_error();
	}
}
