<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * The generic functions of the plugin.
 *
 * @link       #
 * @since      1.0.0
 *
 * @package    commenting-feature
 */
class Commenting_block_Functions {

	/**
	 * Counts opened comment and total comments in the post/page.
	 *
	 * @param int    $post_ID Post ID.
	 * @param string $content Content of the post/page.
	 * @param array  $metas Array of all meta.
	 *
	 * @return array Details of the open and total comments.
	 */
	public function multicollab_get_comment_counts( $post_ID, $content = '', $metas = array() ) {

		$metas       = empty( $metas ) ? get_post_meta( $post_ID ) : $metas;
		$content     = get_post( $post_ID )->post_content;
		$total_count = $open_counts = $resolved_counts = 0;

		$keyArr = array();
		if ((is_array($metas) && !empty($metas)) || (is_object($metas) && !empty((array)$metas))) {
			foreach ( $metas as $key => $val ) {
				if ( substr( $key, 0, 3 ) === '_el' ) {
					$key = str_replace( '_el', '', $key );
					if ( strpos( $val[0], 'resolved_timestamp' ) === false && strpos( $content, strval( $key ) ) !== false ) {
						$keyArr[] = maybe_serialize( $key );
						$open_counts ++;
					}
					if ( strpos( $val[0], 'resolved' ) !== false ) {
						$resolved_counts ++;
					}

					if ( strpos( $val[0], 'publish' ) !== false && ( strpos( $val[0], 'resolved' ) !== false || strpos( $content, strval( $key ) ) !== false ) ) {
						$total_count ++;
					}
				}
			}
		}

		// Confirm open counts with the meta value, if not
		// matched, update it. Just for double confirmation.
		$open_cf_count = isset( $metas['open_cf_count'] ) ? $metas['open_cf_count'][0] : 0;
		if ( (int) $open_cf_count !== $open_counts ) {
			update_post_meta( $post_ID, 'open_cf_count', $open_counts );
		}

		$comment_counts                     = array();
		$comment_counts['open_counts']      = $open_counts;
		$comment_counts['resolved_counts']  = $resolved_counts;
		$comment_counts['total_counts']     = $total_count;
		$comment_counts['open_comment_key'] = $keyArr;

		return $comment_counts;
	}

	/**
	 * Display Comment Activity in History Popup.
	 *
	 * @param int $post_id
	 *
	 * @return array
	 */
	public function multicollab_comments_history( $post_id = 0 ) {
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			check_ajax_referer( COMMENTING_NONCE, 'nonce' );
			$ajax_post_id = (int) filter_input( INPUT_POST, 'currentPostID', FILTER_SANITIZE_NUMBER_INT );
			if ( $ajax_post_id <= 0 || ! current_user_can( 'edit_post', $ajax_post_id ) ) {
				wp_die( -1, '', array( 'response' => 403 ) );
			}
		}
		$limit    = filter_input( INPUT_POST, 'limit', FILTER_SANITIZE_NUMBER_INT );
		$limit    = isset( $limit ) ? $limit : 10;
		$resolved = ( (int) $post_id > 0 ) ? (int) $post_id : (int) filter_input( INPUT_POST, 'currentPostID', FILTER_SANITIZE_NUMBER_INT );
		$current_post_id = $resolved;

		$ajax_call = ( (int) $post_id > 0 || ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) ? 0 : 1;

		$all_meta         = get_post_meta( $current_post_id );
		$userData         = array();
		$prepareDataTable = array();

		$date_format = get_option( 'date_format' );
		$time_format = get_option( 'time_format' );
		$dtTime      = '';

		$total_comments = 0;

		if ((is_array($all_meta) && !empty($all_meta)) || (is_object($all_meta) && !empty((array)$all_meta))) {
			foreach ( $all_meta as $dataid => $v ) {

				if ( strpos( $dataid, '_el' ) === 0 ) {
					$dataid            = str_replace( '_', '', $dataid );
					$v                 = maybe_unserialize( $v[0] );
					$comments          = ! empty( $v['comments'] ) ? $v['comments'] : array();
					$commented_on_text = isset( $v['commentedOnText'] ) ? $v['commentedOnText'] : '';
					$resolved          = isset( $v['resolved'] ) ? $v['resolved'] : 'false';
					$blockType         = isset( $v['blockType'] ) ? '-' . $v['blockType'] : '';

					if ( 'true' === $resolved ) {
						$udata = isset( $v['resolved_by'] ) ? $v['resolved_by'] : 0;
						if ( ! array_key_exists( $udata, $userData ) ) {
							$user_info = get_userdata( $udata );

							$userData[ $udata ]['username']   = $username = $user_info->display_name;
							$userData[ $udata ]['profileURL'] = $profile_url = get_avatar_url( $user_info->user_email );
							$userData[ $udata ]['userrole']   = $userrole = isset( $user_info->roles ) ? implode( ', ', $user_info->roles ) : '';
						} else {
							$username    = $userData[ $udata ]['username'];
							$profile_url = $userData[ $udata ]['profileURL'];
							$userrole    = $userData[ $udata ]['userrole'];
						}

						$timestamp = isset( $v['resolved_timestamp'] ) ? (int) $v['resolved_timestamp'] : '';
						if ( ! empty( $timestamp ) ) {
							 $dtTime = gmdate( $time_format . ' ' . $date_format, $timestamp );
						}

						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['dataid']            = $dataid;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['commented_on_text'] = $commented_on_text;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['username']          = $username;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['profileURL']        = $profile_url;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['userrole']          = $userrole;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['dtTime']            = $dtTime;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['blockType']         = $blockType;
						$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata ]['status']            = __( 'resolved thread', 'commenting-feature' );

					}

					$comment_count = 0;
					if ((is_array($comments) && !empty($comments)) || (is_object($comments) && !empty((array)$comments))) {
						foreach ( $comments as $timestamp => $c ) {
							$cstatus         = 0 === $comment_count ? __( 'commented', 'commenting-feature' ) : __( 'replied', 'commenting-feature' );
							$cstatus        .= __( ' on', 'commenting-feature' );
							$comment_status  = isset( $c['status'] ) ? $c['status'] : '';
							$cattachmentText = isset( $c['attachmentText'] ) ? $c['attachmentText'] : '';
							$cstatus         = 'deleted' === $comment_status ? __( 'deleted comment of', 'commenting-feature' ) : $cstatus;
							if ( 'publish' === $comment_status && ! empty( $c['editedTime'] ) ) {
								$cstatus = __( 'edited', 'commenting-feature' );
							}
							// Stop displaying history of comments in draft mode.
							if ( 'draft' === $comment_status || 'permanent_draft' === $comment_status ) {
								continue;
							}

							$udata = ! empty( $c['userData'] ) ? $c['userData'] : '';

							if ( ! array_key_exists( $udata, $userData ) ) {
								$user_info = get_userdata( $udata );

								$userData[ $udata ]['username']   = $username    = isset( $user_info->display_name ) ? $user_info->display_name : '';
								$userData[ $udata ]['profileURL'] = $profile_url = isset( $user_info->user_email ) ? get_avatar_url( $user_info->user_email ) : '';
								$userData[ $udata ]['userrole']   = $userrole       = isset( $user_info->roles ) ? implode( ', ', $user_info->roles ) : '';
							} else {
								$username    = $userData[ $udata ]['username'];
								$profile_url = $userData[ $udata ]['profileURL'];
								$userrole    = $userData[ $udata ]['userrole'];
							}

							$thread = ! empty( $c['thread'] ) ? $c['thread'] : '';

							$edited_timestamp = isset( $c['editedTimestamp'] ) ? (int) $c['editedTimestamp'] : '';

							if ( ! empty( $edited_timestamp ) ) {
								$dtTime = gmdate( $time_format . ' ' . $date_format, $edited_timestamp );
							} else {
								$dtTime = gmdate( $time_format . ' ' . $date_format, $timestamp );
							}

							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['dataid']            = $dataid;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['commented_on_text'] = $commented_on_text;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['username']          = $username;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['profileURL']        = $profile_url;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['userrole']          = $userrole;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['thread']            = $thread;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['dtTime']            = $dtTime;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['status']            = $cstatus;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['attachmentText']    = $cattachmentText;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['blockType']         = $blockType;
							$prepareDataTable[ $timestamp ][ $dataid . '_' . $udata . '_' . $comment_count ]['resolved']          = $resolved;
							$comment_count ++;
							$total_comments ++;
						}
					}
				}
			}
		}

		krsort( $prepareDataTable, SORT_NUMERIC );
		if ( $ajax_call ) {

			$html = '<div id="history-popup-insider">';
			if ( 0 !== $total_comments ) {

				$count = 0;
				if ((is_array($prepareDataTable) && !empty($prepareDataTable)) || (is_object($prepareDataTable) && !empty((array)$prepareDataTable))) {
					foreach ( $prepareDataTable as $timestamp => $comments ) {
						if ((is_array($comments) && !empty($comments)) || (is_object($comments) && !empty((array)$comments))) {
							foreach ( $comments as $c ) {
								// Limit the number of characters of 'Commented On' Text.
								$limit             = 50;
								$commented_on_text = $c['commented_on_text'];
								if ( $limit < strlen( $commented_on_text ) ) {
									$commented_on_text = substr( $commented_on_text, 0, $limit ) . '...';
								}
								$c['thread'] = isset( $c['thread'] ) ? $c['thread'] : '';
								$count ++;

								$html .= "<div class='user-data-row'>";
								$html .= "<div class='user-data-box'>";
								$html .= "<div class='user-avatar'><img src='" . esc_url( $c['profileURL'] ) . "' alt='" . esc_attr( $c['username'] ) . "'/></div>";
								$html .= "<div class='user-title'>
											<span class='user-name'>" . esc_html( $c['username'] ) . ' ' . esc_html( $c['status'] ) . '</span> ';

								if ( 'deleted comment of' === $c['status'] || __( 'resolved thread', 'commenting-feature' ) === $c['status'] || 'true' === $c['resolved'] ) {
									$html .= esc_html( $commented_on_text );
								} else {
									$html .= "<a href='javascript:void(0)' data-id='" . esc_attr( $c['dataid'] ) . "' class='user-commented-on'>" . esc_html( $commented_on_text ) . '</a>';
								}

								$html .= "<div class='user-comment'> " . wp_kses( $c['thread'], wp_kses_allowed_html( 'post' ) ) . '</div>
										</div>';

								$html .= "<div class='user-time'>" . esc_html( $c['dtTime'] ) . '</div>';
								$html .= '</div>';
								$html .= '</div>';

								if ( $count >= $limit ) {
									break;
								}
							}
						}
					}
				}
			} else {
				$html .= __( 'No comments found.', 'commenting-feature' );
			}
			$html .= '</div>';

			$allowed_tags = array(
				'a'    => array(
					'id'      => array(),
					'href'    => array(),
					'target'  => array(),
					'style'   => array(),
					'class'   => array(),
					'data-id' => array(),
				),
				'div'  => array(
					'id'    => array(),
					'class' => array(),
					'style' => array(),
				),
				'img'  => array(
					'src'   => array(),
					'title' => array(),
					'alt'   => array(),
				),
				'span' => array(
					'class' => array(),
					'style' => array(),
				),
			);

			echo wp_kses( $html, $allowed_tags );
			wp_die();

		} else {
			return $prepareDataTable;
		}
	}

	/**
	 * Map stored suggestion "action" values to a locale-safe display label (literals for gettext).
	 *
	 * @param mixed $action Raw action from comment data.
	 * @return string
	 */
	public function translate_suggestion_action_for_display( $action ) {
		if ( ! is_string( $action ) && ! is_numeric( $action ) ) {
			return '';
		}
		$key = strtolower( (string) $action );
		if ( 'add' === $key ) {
			return __( 'Add', 'commenting-feature' );
		}
		if ( 'delete' === $key ) {
			return __( 'Delete', 'commenting-feature' );
		}
		if ( 'remove' === $key ) {
			return __( 'Remove', 'commenting-feature' );
		}
		if ( 'replace' === $key ) {
			return __( 'Replace', 'commenting-feature' );
		}
		if ( 'move' === $key ) {
			return __( 'Move', 'commenting-feature' );
		}
		if ( 'update' === $key ) {
			return __( 'Update', 'commenting-feature' );
		}
		if ( 'insert' === $key ) {
			return __( 'Insert', 'commenting-feature' );
		}
		return (string) $action;
	}

	/**
	 * Display Translated String
	 *
	 * @param string $str Activity string to format and escape.
	 * @return string
	 */
	public function translate_strings_format( $str ) {
		$translatedStringFormats = $str;
		if ( strpos( $translatedStringFormats, 'Space (' ) !== false ) {
			$split_string = explode( ' ', $translatedStringFormats );
			$translatedStringFormats = sprintf(
				/* translators: 1: first word, 2: second token, 3: third token. */
				esc_html__( '%1$s %2$s %3$s', 'commenting-feature' ),
				esc_html( isset( $split_string[0] ) ? $split_string[0] : '' ),
				esc_html( isset( $split_string[1] ) ? $split_string[1] : '' ),
				esc_html( isset( $split_string[2] ) ? $split_string[2] : '' )
			);
		} elseif ( strpos( $translatedStringFormats, 'Remove Link with URL' ) !== false ) {
			$split_string = explode( 'Remove Link with URL ', $translatedStringFormats );
			$translatedStringFormats = sprintf(
				/* translators: %s: link target or URL text. */
				esc_html__( 'Remove Link with URL %s', 'commenting-feature' ),
				esc_html( isset( $split_string[1] ) ? $split_string[1] : '' )
			);
		} elseif ( strpos( $translatedStringFormats, 'with URL' ) !== false ) {
			$split_string = explode( 'with URL ', $translatedStringFormats );
			$translatedStringFormats = sprintf(
				/* translators: %s: URL or suffix text. */
				esc_html__( 'with URL %s', 'commenting-feature' ),
				esc_html( isset( $split_string[1] ) ? $split_string[1] : '' )
			);
		} elseif ( strpos( $translatedStringFormats, 'Replace' ) !== false ) {
			$split_string = explode( ' ', $translatedStringFormats );
			$translatedStringFormats = sprintf(
				/* translators: 1-4: phrase fragments for a replace suggestion. */
				esc_html__( '%1$s %2$s %3$s %4$s', 'commenting-feature' ),
				esc_html( isset( $split_string[0] ) ? $split_string[0] : '' ),
				esc_html( isset( $split_string[1] ) ? $split_string[1] : '' ),
				esc_html( isset( $split_string[2] ) ? $split_string[2] : '' ),
				esc_html( isset( $split_string[3] ) ? $split_string[3] : '' )
			);
		} elseif ( strpos( $translatedStringFormats, 'Line Break (' ) !== false ) {
			$split_string  = explode( ' ', $translatedStringFormats );
			$concat_b      = ( isset( $split_string[0] ) ? $split_string[0] : '' ) . ' ' . ( isset( $split_string[1] ) ? $split_string[1] : '' );
			$translatedStringFormats = sprintf(
				/* translators: 1: line break label, 2: second token, 3: third token. */
				esc_html__( '%1$s %2$s %3$s', 'commenting-feature' ),
				esc_html( $concat_b ),
				esc_html( isset( $split_string[2] ) ? $split_string[2] : '' ),
				esc_html( isset( $split_string[3] ) ? $split_string[3] : '' )
			);
		} elseif ( strpos( $translatedStringFormats, 'Block Alignment' ) !== false ) {
			$split_string = explode( ' ', wp_strip_all_tags( $translatedStringFormats ) );
			$concat_b     = ( isset( $split_string[0] ) ? $split_string[0] : '' ) . ' ' . ( isset( $split_string[1] ) ? $split_string[1] : '' );
			$translatedStringFormats = sprintf(
				wp_kses(
					/* translators: 1: block alignment context, 2-4: alignment values. */
					__( '%1$s <em>%2$s</em> %3$s <em>%4$s</em>', 'commenting-feature' ),
					array( 'em' => array() )
				),
				esc_html( $concat_b ),
				esc_html( isset( $split_string[2] ) ? $split_string[2] : '' ),
				esc_html( isset( $split_string[3] ) ? $split_string[3] : '' ),
				esc_html( isset( $split_string[4] ) ? $split_string[4] : '' )
			);
		} elseif ( strpos( $translatedStringFormats, 'Change Heading' ) !== false ) {
			$split_string = explode( ' ', wp_strip_all_tags( $translatedStringFormats ) );
			$concat_b     = ( isset( $split_string[0] ) ? $split_string[0] : '' ) . ' ' . ( isset( $split_string[1] ) ? $split_string[1] : '' );
			$translatedStringFormats = sprintf(
				wp_kses(
					/* translators: 1: heading change label, 2-6: phrase parts. */
					__( '%1$s <em> %2$s %3$s </em> %4$s <em> %5$s %6$s </em>', 'commenting-feature' ),
					array( 'em' => array() )
				),
				esc_html( $concat_b ),
				esc_html( isset( $split_string[3] ) ? $split_string[3] : '' ),
				esc_html( isset( $split_string[4] ) ? $split_string[4] : '' ),
				esc_html( isset( $split_string[5] ) ? $split_string[5] : '' ),
				esc_html( isset( $split_string[7] ) ? $split_string[7] : '' ),
				esc_html( isset( $split_string[3] ) ? $split_string[3] : '' )
			);
		}
		$str = $translatedStringFormats;
		return $str;
	}

	/**
	 * Reorder Userrole According to Default WordPress Roles
	 *
	 * @param array $needToSortArray
	 *
	 * @return array
	 */
	public function multicollab_get_reorder_user_role( $needToSortArray ) {
		global $wp_roles;
		if ( isset( $wp_roles ) ) {
			$cf_wp_roles     = new WP_Roles();
			$available_roles = $cf_wp_roles->get_names();
		}
		$available_roles = $wp_roles->get_names();
		$order           = array_keys( $available_roles );
		// Add code to reolve VIP error. @author Rishi Shah @since 3.6.1
		if( is_array( $needToSortArray ) && ! empty( $needToSortArray ) ) {
			usort(
				$needToSortArray,
				function( $key1, $key2 ) use ( $order, $needToSortArray ) {
					if(isset($needToSortArray[ $key1 ]) && isset($needToSortArray[ $key2 ])){
						return ( array_search( $needToSortArray[ $key1 ], $order, true ) <=> array_search( $needToSortArray[ $key2 ], $order, true ) );
					}
				}
			);
			return $needToSortArray;
		} else {
			return $needToSortArray;
		}
	}

	/**
	 * Return all posts categories.
	 *
	 * @return void
	 */
	public function multicollab_get_posts_categories() {

		$cf_categories = get_categories(
			array(
				'orderby'    => 'name',
				'order'      => 'ASC',
				'hide_empty' => false,
			)
		);

		return $cf_categories;

	}
	/**
	 * Return all general setting value.
	 *
	 * @return array
	 */
	public function multicollab_get_general_settings() {

		$cf_gen_hide_multicollab_comment = get_option( 'multicollab_hide_editorial_column' );
		$cf_gen_hide_floating_icons      = get_option( 'multicollab_hide_floating_icons' );
		$cf_gen_hide_save_draft_comment  = get_option( 'multicollab_show_infoboard' );
		$cf_admin_notification = get_option( 'multicollab_admin_notif' );

		$cf_suggestion_option  = get_option( 'multicollab_give_alert_message' );

		$cf_slack_default_channel              = '';
		$cf_slack_notification_add_comment     = '';
		$cf_slack_notification_resolve_comment = '';
		$cf_lang                               = get_bloginfo( 'language' );

		$cf_permissions_options = get_option( 'multicollab_permissions' );

		$cf_plugin_general_setting = array(
			'multicollab_gen_hide_multicollab_comment'       => $cf_gen_hide_multicollab_comment,
			'multicollab_gen_hide_save_draft_comment'        => $cf_gen_hide_save_draft_comment,
			'multicollab_gen_hide_floating_icons'            => $cf_gen_hide_floating_icons,
			'multicollab_admin_notification'                 => $cf_admin_notification,
			'multicollab_suggestion_option'                 => $cf_suggestion_option,
			'multicollab_slack_default_channel'              => $cf_slack_default_channel,
			'multicollab_slack_notification_add_comment'     => $cf_slack_notification_add_comment,
			'multicollab_slack_notification_resolve_comment' => $cf_slack_notification_resolve_comment,
			'multicollab_multilingual_language'              => $cf_lang,
			'multicollab_permissions_options'                => $cf_permissions_options,
		);

		return $cf_plugin_general_setting;

	}

	/**
	 * Return all open comment key when post updated
	 */
	public function multicollab_open_comment_key() {

		$current_post_id = filter_input( INPUT_POST, 'currentPostID', FILTER_SANITIZE_NUMBER_INT );
		$commentsKey     = get_post_meta( $current_post_id, 'open_cf_comment_key', true );

		echo wp_json_encode(
			array(
				'comments_key' => $commentsKey,
			)
		);

		wp_die();

	}

}
