<?php
namespace um_ext\um_user_notes\core;

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

/**
 * Class Profile
 * @package um_ext\um_user_notes\core
 */
class Profile {

	/**
	 * @var bool
	 */
	private $modal_inited = false;

	/**
	 * Profile constructor.
	 */
	public function __construct() {
		add_filter( 'um_profile_tabs', array( $this, 'add_profile_tab' ), 802 );
		add_filter( 'um_user_profile_tabs', array( &$this, 'add_user_tab' ), 5, 1 );

		if ( defined( 'UM_DEV_MODE' ) && UM_DEV_MODE && UM()->options()->get( 'enable_new_ui' ) ) {
			// default tab is handled in UM core
		} else {
			add_action( 'um_profile_content_notes_default', array( $this, 'user_notes_profile_tab' ) );
		}
		add_action( 'um_profile_content_notes_view', array( $this, 'user_notes_profile_tab' ) );
		add_action( 'um_profile_content_notes_add', array( $this, 'get_add_note_form' ) );

		add_action( 'um_delete_user', array( $this, 'delete_user' ), 10, 1 );

		add_filter( 'um_notes_query_args', array( $this, 'change_query' ), 20, 2 );
		add_filter( 'um_notes_oembed', array( $this, 'oembed' ) );

		add_filter( 'um_user_profile_subnav_link', array( $this, 'um_user_profile_subnav_link' ), 20 );
	}

	public function user_notes_profile_tab() {
		// phpcs:disable WordPress.Security.NonceVerification
		if ( ! empty( $_GET['note_id'] ) ) {
			$note_id = absint( $_GET['note_id'] );
			$output  = apply_shortcodes( '[um_user_notes_single_view note_id="' . $note_id . '"]' );
		} else {
			$profile_id = um_profile_id();
			$output     = apply_shortcodes( '[um_user_notes_view user_id="' . $profile_id . '"]' );
		}
		// phpcs:enable WordPress.Security.NonceVerification
		echo wp_kses( $output, UM()->get_allowed_html( 'templates' ) );
	}

	/**
	 * Add notes tab on user profile
	 *
	 * @param $tabs
	 *
	 * @return mixed
	 */
	public function add_profile_tab( $tabs ) {
		$tabs['notes'] = array(
			'name' => __( 'Notes', 'um-user-notes' ),
			'icon' => 'um-faicon-sticky-note',
		);

		return $tabs;
	}

	public function add_user_tab( $tabs ) {
		if ( empty( $tabs['notes'] ) ) {
			return $tabs;
		}
		if ( um_user( 'disable_notes' ) ) {
			unset( $tabs['notes'] );
			return $tabs;
		}

		if ( um_is_profile_owner() ) {
			if ( defined( 'UM_DEV_MODE' ) && UM_DEV_MODE && UM()->options()->get( 'enable_new_ui' ) ) {
				$tabs['notes']['subnav'] = array(
					'view' => array(
						'title' => __( 'View notes', 'um-user-notes' ),
					),
					'add'  => array(
						'title' => __( 'Add note', 'um-user-notes' ),
					),
				);
			} else {
				$tabs['notes']['subnav'] = array(
					'view' => __( 'View notes', 'um-user-notes' ),
					'add'  => __( 'Add note', 'um-user-notes' ),
				);
			}
			$tabs['notes']['subnav_default'] = 'view';
		}

		return $tabs;
	}

	/**
	 * Return note add form on user profile subtab
	 */
	public function get_add_note_form() {
		if ( um_is_profile_owner() ) {
			UM()->Notes()->enqueue()->enqueue_scripts();
			UM()->get_template( 'profile/add.php', um_user_notes_plugin, array(), true );
		} else {
			$url = add_query_arg( 'profiletab', 'notes', um_user_profile_url( um_profile_id() ) );
			wp_safe_redirect( $url );
		}
	}

	/**
	 * Delete All user notes on delete
	 *
	 * @param $user_id
	 */
	public function delete_user( $user_id ) {
		$user_notes = get_posts(
			array(
				'posts_per_page' => -1,
				'post_type'      => 'um_notes',
				'author__in'     => $user_id,
				'fields'         => 'ids',
			)
		);

		foreach ( $user_notes as $note_id ) {
			$file_path = UM()->Notes()->get_downloadable_note_path( $note_id );
			if ( file_exists( $file_path ) ) {
				wp_delete_file( $file_path );
			}
			wp_delete_post( $note_id, true );
		}
	}

	/**
	 * Filter um_notes query
	 *
	 * @param array $args
	 * @param $profile_id
	 *
	 * @return array
	 */
	public function change_query( $args, $profile_id ) {
		$status = array( 'publish' );

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

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

		$current_user_id = null;
		if ( is_user_logged_in() ) {
			// user logged in
			$current_user_id = get_current_user_id();

			if ( absint( $profile_id ) === $current_user_id ) {
				$accessible_by_author = apply_filters( 'um_user_notes_accessible_by_author_privacy', array( 'followed', 'follower', 'friends', 'only_me' ) );

				$status[] = 'draft';
				$query[]  = array(
					'key'     => '_privacy',
					'value'   => $accessible_by_author,
					'compare' => 'IN',
				);
			}
		}

		$query = apply_filters( 'um_user_notes_change_meta_query', $query, $current_user_id, $profile_id );

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

		return $args;
	}

	/**
	 * Add note View / Edit modal to footer for easy availability
	 */
	public function add_modal() {
		if ( $this->modal_inited ) {
			return;
		}

		$this->modal_inited = true;

		$t_args = array(
			'url' => is_user_logged_in() && um_is_core_page( 'user' ) ? add_query_arg( 'profiletab', 'notes', um_user_profile_url( um_profile_id() ) ) : '',
		);
		UM()->get_template( 'profile/modal.php', um_user_notes_plugin, $t_args, true );
	}

	/**
	 * Video URLs oembed
	 */
	public function oembed( $content ) {
		preg_match_all( '#(https?://vimeo.com)/([0-9]+)#i', $content, $matches1 );
		preg_match_all( '/(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtube\.com\/watch\?v=[\w_-]{1,11}&ab_channel=[\w_-]{1,40})/', $content, $matches2 );
		preg_match_all( '/(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtube\.com\/watch\?v=[\w_-]{1,11})|(?:http(?:s)?:\/\/)?(?:youtu\.be\/[\w_-]{1,11})/', $content, $matches3 );

		if ( isset( $matches1 ) && ! empty( $matches1[0] ) ) {
			foreach ( $matches1[0] as $key => $val ) {
				$embed_content = wp_oembed_get( $val );
				if ( $embed_content ) {
					$content = str_replace( $val, $embed_content, $content );
				}
			}
		}

		if ( isset( $matches2[0] ) && ! empty( $matches2[0] ) ) {
			foreach ( $matches2[0] as $key => $val ) {
				$embed_content = wp_oembed_get( $val );
				if ( $embed_content ) {
					$content = str_replace( $val, $embed_content, $content );
				}
			}
		}

		if ( isset( $matches3[0] ) && ! empty( $matches3[0] ) ) {
			foreach ( $matches3[0] as $key => $val ) {
				$embed_content = wp_oembed_get( $val );
				if ( $embed_content ) {
					$content = str_replace( $val, $embed_content, $content );
				}
			}
		}

		$arr_urls = wp_extract_urls( $content );

		if ( ! empty( $arr_urls ) && is_array( $arr_urls ) ) {
			foreach ( $arr_urls as $key => $url ) {
				if ( ! strstr( $url, 'vimeo' ) && ! strstr( $url, 'youtube' ) && ! strstr( $url, 'youtu.be' ) ) {
					$embed_content = wp_oembed_get( $url );
					if ( $embed_content ) {
						$content = str_replace( $url, $embed_content, $content );
					}
				}
			}
		}

		return $content;
	}


	/**
	 * Change profile subtab.
	 *
	 * @param string $subnav_link
	 *
	 * @return string
	 */
	public function um_user_profile_subnav_link( $subnav_link ) {
		// phpcs:disable WordPress.Security.NonceVerification
		if ( ! empty( $_GET['note_id'] ) ) {
			$subnav_link = remove_query_arg( 'note_id', $subnav_link );
		}
		// phpcs:enable WordPress.Security.NonceVerification

		return $subnav_link;
	}
}
