<?php

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

/**
 * Class DateBook_Profile_Notifications
 *
 * @class DateBook_Profile_Notifications
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Profile_Notifications {


	/**
	 * Hook actions and filters.
	 * 
	 * @since 4.3.4
	 * @access public
	 */
	public static function init() {

		add_action( 'init', array( __CLASS__, 'process_set_notification_as_read' ) );
		add_action( 'datebook_profile_notifications', array( __CLASS__, 'display_all_notifications' ) );

	}


	/**
	 * Sort simple array by time
	 *
	 * @access private
	 * @return void
	 */
	public static function sort_notification_by_time($a, $b) {
		return $b['time'] - $a['time'];
	}


	/**
	 * Set a notification as read
	 *
	 * @access public
	 */
	public static function process_set_notification_as_read() {

		$referrer = isset($_GET['referrer']) ? $_GET['referrer'] : '';
		if ($referrer == 'notification') {

			if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
				$current_user_id = DATEBOOK_CURRENT_USER_ID;
			} else {
				global $current_user;
				wp_get_current_user();
				$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
			}

			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

			// Get notifications for profile
			$get_found_notifications = array();

			$get_data_notification = get_post_meta($profile_id, 'notification', true);
			
			$id = isset($_GET['id']) ? $_GET['id'] : '';

			if(is_array($get_data_notification) && !empty($get_data_notification)){

				foreach($get_data_notification as $key => $value){

					if($value['time'] == $id){
						// Set a notification as read
						$get_data_notification[$key]['status'] = 'read';
					}

				}

				// Update the post meta
				update_post_meta($profile_id, 'notification', $get_data_notification);

			}
		}
	}


	/**
	 * Show all notifications
	 *
	 * @access public
	 * @return void
	 */
	public static function display_all_notifications() {

	    // display the Edit Profile form
		echo DateBook_Template_Loader::load( 'profile/profile-notifications' );

	}


}

DateBook_Profile_Notifications::init();