<?php if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


if ( ! class_exists( 'UM_Notes_Functions' ) ) {


	/**
	 * Class UM_Notes_Functions
	 */
	class UM_Notes_Functions {


		/**
		 * UM_Notes_Functions constructor.
		 */
		public function __construct() {
			add_filter( 'query_vars', array( &$this, 'query_vars' ) );
			add_filter( 'rewrite_rules_array', array( &$this, 'add_rewrite_rules' ) );
			add_action( 'template_redirect', array( &$this, 'download_routing' ), 1 );
		}


		/**
		 * Modify global query vars
		 *
		 * @param $public_query_vars
		 *
		 * @return array
		 */
		public function query_vars( $public_query_vars ) {
			$public_query_vars[] = 'um_note_id';

			return $public_query_vars;
		}


		public function add_rewrite_rules( $rules ) {
			$newrules = array();

			// NGINX-config `rewrite ^/um-user-notes-download/([^/]+)/([^/]+)/([^/]+)/?$ /index.php?um_action=um-user-notes-download&um_verify=$1&um_note_id=$2 last;`
			$newrules['um-user-notes-download/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?um_action=um-user-notes-download&um_verify=$matches[1]&um_note_id=$matches[2]';

			return $newrules + $rules;
		}

		private function get_filename( $note_id ) {
			$author_id = get_post_field( 'post_author', $note_id );
			$filename  = 'um-note-' . wp_hash( $author_id ) . '-' . wp_hash( $note_id ) . '.pdf';

			return $filename;
		}

		public function get_downloadable_note_path( $post_id, $force_dir = null ) {
			$upload_dir     = wp_upload_dir();
			$upload_basedir = $upload_dir['basedir'] . '/ultimatemember/um-user-notes/';
			$filename       = $this->get_filename( $post_id );

			if ( $force_dir ) {
				global $wp_filesystem;

				if ( ! is_a( $wp_filesystem, '\WP_Filesystem_Base' ) ) {
					require_once ABSPATH . 'wp-admin/includes/file.php';

					$credentials = request_filesystem_credentials( site_url() );
					\WP_Filesystem( $credentials );
				}
				if ( ! $wp_filesystem->is_dir( $upload_basedir ) ) {
					wp_mkdir_p( $upload_basedir );
				}
			}

			return wp_normalize_path( $upload_basedir . $filename );
		}

		/**
		 * Download Note routing.
		 */
		public function download_routing() {
			if ( 'um-user-notes-download' !== get_query_var( 'um_action' ) ) {
				return;
			}

			$post_id = get_query_var( 'um_note_id' );
			if ( empty( $post_id ) ) {
				return;
			}

			$verify = get_query_var( 'um_verify' );
			if ( empty( $verify ) || ! wp_verify_nonce( $verify, 'um-notes-' . $post_id ) ) {
				return;
			}

			if ( get_post_status( $post_id ) && UM()->Notes()->can_view( $post_id ) ) {
				$file_path = $this->get_downloadable_note_path( $post_id );
				if ( ! file_exists( $file_path ) ) {
					return;
				}

				$title = get_post_field( 'post_title', $post_id ) . '_' . time();
				$this->file_download( $file_path, $title );
			}
		}

		/**
		 * @param string $file_path Path to downloadable file
		 * @param string $filename  Name of the downlodable file in headers.
		 */
		private function file_download( $file_path, $filename ) {
			$size = filesize( $file_path );
			$type = 'application/pdf';

			header( 'Content-Description: File Transfer' );
			header( 'Content-Type: ' . $type );
			header( 'Content-Disposition: attachment; filename="' . $filename . '.pdf"' );
			header( 'Content-Transfer-Encoding: binary' );
			header( 'Expires: 0' );
			header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
			header( 'Pragma: public' );
			header( 'Content-Length: ' . $size );

			$levels = ob_get_level();
			for ( $i = 0; $i < $levels; $i++ ) {
				@ob_end_clean();
			}

			readfile( $file_path );
			exit;
		}

		/**
		 * @return array
		 */
		public function get_allowed_filetypes() {
			$allowed = array(
				'image/jpeg',
				'image/png',
				'image/jpg',
				'image/gif',
			);

			return $allowed;
		}

		/**
		 * Is note author
		 *
		 * @param bool $note_id
		 * @param bool $user_id
		 *
		 * @return bool
		 */
		public function is_note_author( $note_id = false, $user_id = false ) {

			if ( ! is_user_logged_in() || ! $note_id ) {
				return false;
			}

			$note = get_post( $note_id );
			if ( empty( $note ) || is_wp_error( $note ) ) {
				return false;
			}

			if ( empty( $user_id ) ) {
				$user_id = get_current_user_id();
			}

			return ( absint( $user_id ) === absint( $note->post_author ) );
		}


		/**
		 * Get load more text from setting
		 */
		public function load_more_text() {
			$text = UM()->options()->get( 'um_user_notes_load_more_text' );
			echo apply_filters( 'um_user_notes_load_more_text', $text );
		}


		/**
		 * Get read more text from setting
		 */
		public function read_more_text() {
			$text = UM()->options()->get( 'um_user_notes_read_more_text' );
			echo apply_filters( 'um_user_notes_read_more_text', $text );
		}

		/**
		 * Get number of note to display on profile
		 *
		 * @param bool $return
		 *
		 * @return int
		 */
		public function get_per_page( $return = false ) {
			$number = UM()->options()->get( 'um_user_notes_per_page' );

			$per_page = apply_filters( 'um_user_notes_per_page', $number );

			if ( $return ) {
				return absint( $per_page );
			}

			echo esc_html( $per_page );
			return '';
		}

		/**
		 * Get excerpt length from setting
		 *
		 * @param bool $return
		 *
		 * @return string
		 */
		public function get_excerpt_length( $return = false ) {

			$number = UM()->options()->get( 'um_user_notes_excerpt_length' );

			$count = apply_filters( 'um_user_notes_excerpt_length', intval( $number ) );

			if ( $return ) {

				return $count;

			} else {

				echo $count;
				return '';
			}

		}


		/**
		 * Check if user can view note
		 *
		 * @param int|null $note_id
		 *
		 * @return bool
		 */
		public function can_view( $note_id = null ) {
			if ( ! $note_id ) {
				return false;
			}

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

			if ( um_profile_id() === $user_id ) {
				return true;
			}

			$privacy   = get_post_meta( $note_id, '_privacy', true );
			$is_author = $this->is_note_author( $note_id, $user_id );

			if ( ! $is_author ) {
				if ( 'only_me' === $privacy ) {
					return false;
				} else {
					$status = get_post_status( $note_id );
					if ( 'draft' === $status ) {
						return false;
					}
				}
			}

			if ( 'everyone' === $privacy ) {
				return true;
			}

			$custom_privacy = apply_filters( 'um_user_notes_custom_privacy', true, $privacy, $user_id );
			return $custom_privacy;
		}


		public function um_notes_get_latest( $profile_id, $per_page ) {
			$query_args = array(
				'post_type'      => 'um_notes',
				'author__in'     => $profile_id,
				'posts_per_page' => $per_page,
			);

			$query_args = apply_filters( 'um_notes_query_args', $query_args, $profile_id );

			$latest_notes = new \WP_Query( $query_args );

			return $latest_notes;
		}


		public function um_notes_get_total( $profile_id, $per_page ) {
			$next_page_args = array(
				'post_type'      => 'um_notes',
				'author__in'     => $profile_id,
				'posts_per_page' => $per_page + 1,
			);
			$next_page_args = apply_filters( 'um_notes_query_args', $next_page_args, $profile_id );

			$next_page = new \WP_Query( $next_page_args );
			$total     = $next_page->post_count;

			return $total;
		}
	}
}
