<?php
namespace um_ext\um_user_notes\core;

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

/**
 * Integration with UM social activity
 *
 * Class Activity
 *
 * @package um_ext\um_user_notes\core
 */
class Activity {

	/**
	 * Activity constructor.
	 */
	function __construct() {
		add_action( 'um_user_notes_after_note_created', [ $this, 'um_social_activity_post' ] );
		add_action( 'um_user_notes_after_note_updated', [ $this, 'um_user_notes_after_note_updated' ] );
		add_action( 'um_user_notes_before_note_deleted', [ $this, 'um_social_activity_post_delete' ] );
		add_filter( 'um_activity_wall_args', array( $this, 'filter_social_activity' ), 30, 2 );
		add_filter( 'um_activity_post_can_view', array( $this, 'activity_post_can_view' ), 11, 2 );

		add_filter( 'um_activity_search_tpl', [ $this, 'um_activity_search_tpl' ], 10, 1 );
		add_filter( 'um_activity_replace_tpl', [ $this, 'um_activity_replace_tpl' ], 10, 2 );

		add_action( 'um_social_activity_enqueue_scripts', [ UM()->Notes()->enqueue(), 'enqueue_scripts' ] );

		add_filter( 'um_activity_global_actions', [ $this, 'add_activity_global_actions' ], 10, 1 );
	}


	/**
	 * @param int $activity
	 * @param int $note_id
	 */
	function update_activity_privacy( $activity, $note_id ) {
		$privacy = get_post_meta( $note_id , '_privacy' , true );

		if ( get_post_status( $note_id ) == 'draft' ) {
			$privacy = 'only_me';
		}

		update_post_meta( $activity , 'um_note_privacy' , $privacy  );
	}


	/**
	 * Create social activity when new note is created
	 *
	 * @param int $note_id
	 */
	public function um_social_activity_post( $note_id ) {
		$note = get_post( $note_id );
		if ( 'draft' !== $note->post_status ) {
			$user_id = $note->post_author;

			$author_profile = um_user_profile_url( $user_id );
			$link           = add_query_arg(
				array(
					'profiletab' => 'notes',
					'note_id'    => $note_id,
				),
				$author_profile
			);

			um_fetch_user( $user_id );

			$author_name = um_user( 'display_name' );

			$author_profile = um_user_profile_url();

			$excerpt = substr( strip_tags( $note->post_content ), 0, UM()->Notes()->get_excerpt_length( true ) ) . '...';

			$activity = UM()->Activity_API()->api()->save(
				array(
					'template'       => 'new-note',
					'custom_path'    => um_user_notes_path . '/templates/activity/new-note.php',
					'wall_id'        => $user_id,
					'related_id'     => $note_id,
					'author'         => $user_id,
					'author_name'    => $author_name,
					'author_profile' => $author_profile,
					'post_title'     => '<span class="post-title">' . $note->post_title . '</span>',
					'post_url'       => $link,
					'post_excerpt'   => '<span class="post-excerpt">' . $excerpt . '</span>',
				)
			);

			$this->update_activity_privacy( $activity, $note_id );
		}
	}


	/**
	 * Create social activity when note is updated.
	 *
	 * @param int $note_id
	 *
	 */
	public function um_user_notes_after_note_updated( $note_id ) {
		if ( ! $note_id ) {
			return;
		}

		$note = get_post( $note_id );

		if ( 'draft' !== $note->post_status ) {
			$activities = $this->get_activities( $note_id );

			if ( empty( $activities ) ) {
				do_action( 'um_user_notes_after_note_created', $note_id );
			} else {
				foreach ( $activities as $post ) {

					setup_postdata( $post );

					$note = get_post( $note_id );

					$user_id = $note->post_author;

					$author_profile = um_user_profile_url( $user_id );
					$link           = add_query_arg(
						array(
							'profiletab' => 'notes',
							'note_id'    => $note_id,
						),
						$author_profile
					);

					um_fetch_user( $user_id );

					$author_name = um_user( 'display_name' );

					$author_profile = um_user_profile_url();

					$excerpt = substr( strip_tags( $note->post_content ), 0, UM()->Notes()->get_excerpt_length( true ) ) . '...';

					$activity = UM()->Activity_API()->api()->save(
						array(
							'template'       => 'new-note',
							'custom_path'    => um_user_notes_path . '/templates/activity/new-note.php',
							'wall_id'        => $user_id,
							'related_id'     => $note_id,
							'author'         => $user_id,
							'author_name'    => $author_name,
							'author_profile' => $author_profile,
							'post_title'     => '<span class="post-title">' . $note->post_title . '</span>',
							'post_url'       => $link,
							'post_excerpt'   => '<span class="post-excerpt">' . $excerpt . '</span>',
						),
						true,
						$post->ID
					);

					$this->update_activity_privacy( $activity, $note_id );
				}
			}
		} else {
			do_action( 'um_user_notes_before_note_deleted', $note_id );
		}

		wp_reset_postdata();
	}


	/**
	 * Delete social activity when note is deleted.
	 *
	 * @param int $note_id
	 *
	 */
	function um_social_activity_post_delete( $note_id = 0 ) {
		if ( ! $note_id ) {
			return;
		}

		$activities = $this->get_activities( $note_id );

		if ( empty( $activities ) ) {
			return;
		}

		foreach ( $activities as $post ) {
			wp_delete_post( $post->ID );
		}
	}


	/**
	 * @param $note_id
	 *
	 * @return int[]|\WP_Post[]
	 */
	function get_activities( $note_id ) {
		$activities = get_posts( [
			'post_type'     => 'um_activity',
			'meta_query'    => [
				[
					'key'       => '_related_id',
					'value'     => $note_id,
					'compare'   => '=',
				],
				[
					'key'       => '_action',
					'value'     => 'new-note',
					'compare'   => '=',
				],
			],
		] );

		return $activities;
	}


	/**
	 * Exclude notes from wall if user does not have access to view notes
	 *
	 * @version 1.0.3
	 *
	 * @param array    $args
	 * @param int|null $wall_id
	 *
	 * @return array
	 */
	public function filter_social_activity( $args, $wall_id ) {
		global $wpdb;

		$user_id = null;
		if ( is_user_logged_in() ) {
			$user_id = get_current_user_id();

			if ( absint( $wall_id ) === $user_id ) {
				// Keep WP_Posts query simple if we are on the own profile's activity wall.
				return $args;
			}
		}

		$metarows = $wpdb->get_col(
			"SELECT DISTINCT pm.meta_value
			FROM {$wpdb->postmeta} pm
			LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
			WHERE p.post_type = 'um_activity' AND
			      pm.meta_key='um_note_privacy'"
		);

		if ( empty( $metarows ) || ( 1 === count( $metarows ) && in_array( 'everyone', $metarows, true ) ) ) {
			// Keep WP_Posts query simple if there are only 'everyone' privacy or not `um_note_privacy` postmeta
			return $args;
		}

		if ( empty( $args['meta_query'] ) ) {
			$args['meta_query'] = array( 'relation' => 'AND' );
		}

		$query = array(
			'relation' => 'OR',
			array(
				'key'     => 'um_note_privacy',
				'compare' => 'NOT EXISTS',
			),
		);

		// Activity wall on the user profile.
		if ( ! empty( $wall_id ) ) {
			$privacy_array = array();
			if ( in_array( 'everyone', $metarows, true ) ) {
				$privacy_array[] = 'everyone';
			}

			$privacy_array = apply_filters( 'um_user_notes_activity_query_privacy_array', $privacy_array, $user_id, $wall_id, $metarows, $args );

			$query[] = array(
				'key'     => 'um_note_privacy',
				'value'   => $privacy_array,
				'compare' => 'IN',
			);
		} else {
			if ( in_array( 'everyone', $metarows, true ) ) {
				$query[] = array(
					'key'     => 'um_note_privacy',
					'value'   => 'everyone',
					'compare' => '=',
				);
			}
		}

		if ( in_array( 'only_me', $metarows, true ) && is_user_logged_in() ) {
			$query[] = array(
				'relation' => 'AND',
				array(
					'key'     => 'um_note_privacy',
					'value'   => 'only_me',
					'compare' => '=',
				),
				array(
					'key'     => '_wall_id',
					'value'   => $user_id,
					'compare' => '=',
				),
			);
		}

		$query = apply_filters( 'um_user_notes_activity_query_privacy', $query, $user_id, $wall_id, $metarows, $args );

		$args['meta_query'][] = $query;

		return $args;
	}

	public function activity_post_can_view( $can_view, $post_id ) {
		if ( ! $can_view ) {
			return $can_view;
		}

		$notes_privacy = get_post_meta( $post_id, 'um_note_privacy', true );
		if ( empty( $notes_privacy ) || 'everyone' === $notes_privacy ) {
			return $can_view;
		}

		if ( 'only_me' === $notes_privacy ) {
			$wall_id = UM()->Activity_API()->api()->get_wall( $post_id );
			if ( ! is_user_logged_in() || absint( $wall_id ) !== get_current_user_id() ) {
				return false;
			}
		}

		return apply_filters( 'um_user_notes_activity_post_can_view', $can_view, $post_id );
	}

	/**
	 * Activity options
	 *
	 * @param array $actions
	 *
	 * @return array
	 */
	function add_activity_global_actions( $actions ) {
		$actions['new-note'] = __( 'New note', 'um-user-notes' );
		return $actions;
	}


	/**
	 * New tag for activity
	 *
	 * @param $search
	 *
	 * @return array
	 */
	function um_activity_search_tpl( $search ) {
		$search[] = "{related_id}";

		return $search;
	}


	/**
	 * New tag replace for activity
	 *
	 * @param $replace
	 * @param $array
	 *
	 * @return array
	 */
	function um_activity_replace_tpl( $replace, $array ) {
		$replace[] = isset( $array['related_id'] ) ? $array['related_id'] : '';

		return $replace;
	}

}
