<?php
/**
 * Seventhqueen\Typer\Elementor\Component class
 *
 * @package typer
 */

namespace Seventhqueen\Typer\Plugins;

use FUP\FupPlugin;
use function Seventhqueen\Typer\typer;

/**
 * Class FUP
 * @package Seventhqueen\Typer\Plugins
 */
class FUP {

	private $posts = null;

	/**
	 * Adds the action and filter hooks to integrate with WordPress.
	 */
	public function __construct() {
		add_action( 'wp_head', [ $this, 'force_full_page' ] );
		add_filter( 'get_template_part_template-parts/content/panel', [ $this, 'cancel_load_panel' ] );
		add_action( 'get_template_part_template-parts/content/panel', [ $this, 'load_cover' ] );
		add_action( 'typer_before_archive_content', [ $this, 'get_user_feed' ], 9 );
		add_action( 'typer_post_list_after_meta', [ $this, 'add_bookmark_article' ] );
		add_action( 'pre_get_posts', [ $this, 'exclude_feed_posts' ] );
		add_action( 'init', [ $this, 'get_feed_data' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'action_lazyload_data' ], 12 );
	}

	/**
	 * Trigger lazy load and reveal on posts AJAX load
	 */
	public function action_lazyload_data() {
		$data = "window.addEventListener('fupAjaxLoaded', function(){" .
		        "var event = document.createEvent('HTMLEvents');" .
		        "event.initEvent('reveal', true, false);" .
		        "window.dispatchEvent(event);" .
		        "typerTriggerLazy();" .
		        "});";
		wp_add_inline_script( 'lazy-load-images', $data );
	}

	/**
	 * Force profile page to be full and content small
	 */
	public function force_full_page() {
		if ( fup_is_profile_page() ) {
			typer()->force_main_layout( 'full' );
			typer()->force_main_container_size( 'small' );
		}
	}

	/**
	 * Add bookmark button
	 */
	public function add_bookmark_article() {
		if ( in_array( 'bookmark', typer()->get_option( 'blog_post_meta_items' ), true ) ) {
			FupPlugin::instance()->add_meta_button_bookmark();
		}
	}

	/**
	 * Don't load default panel on profile page
	 *
	 * @param $continue
	 *
	 * @return bool
	 */
	public function cancel_load_panel( $continue ) {
		if ( fup_is_profile_page() ) {
			return false;
		}

		return $continue;
	}

	/**
	 *
	 * Check if is on action and return also for filter use
	 *
	 * @param $slug
	 *
	 * @return mixed
	 */
	public function load_cover( $slug ) {
		if ( ! is_bool( $slug ) && fup_is_profile_page() ) {
			echo fup_get_cover();
		}

		return $slug;
	}

	/**
	 * Get post data for custom feed
	 */
	public function get_feed_data() {
		if ( ! is_user_logged_in() || ! typer()->get_option( 'fup_custom_feed' ) ) {
			return;
		}

		$following_authors    = fup_get_following_authors_ids();
		$following_categories = fup_get_following_categories_ids();

		if ( empty( $following_authors ) && empty( $following_categories ) ) {
			delete_transient( 'fup_home_feed_posts_' . get_current_user_id() );

			return;
		}

		$query_authors = null;
		$exclude_ids   = [];

		if ( ! empty( $following_authors ) ) {
			$args_authors = [
				'post_status'         => 'publish',
				'author__in'          => $following_authors,
				'posts_per_page'      => 3,
				'ignore_sticky_posts' => 1,
				'post_type'           => 'post',
				'orderby'             => 'date',
				'order'               => 'DESC'
			];

			$query_authors = new \WP_Query( $args_authors );

			if ( $query_authors->have_posts() ) {
				foreach ( $query_authors->posts as $post ) {
					$exclude_ids[] = $post->ID;
				}
			}
		}

		$query_categories = null;

		if ( ! empty( $following_categories ) ) {
			$args_categories = [
				'post_status'         => 'publish',
				'post__not_in'        => $exclude_ids,
				'author__not_in'      => [ get_current_user_id() ],
				'category__in'        => $following_categories,
				'posts_per_page'      => 3,
				'ignore_sticky_posts' => 1,
				'post_type'           => 'post',
				'orderby'             => 'date',
				'order'               => 'DESC'
			];

			$query_categories = new \WP_Query( $args_categories );
		}

		if ( $query_authors && $query_categories ) {
			$query_authors->posts      = array_merge( $query_authors->posts, $query_categories->posts );
			$query_authors->post_count += $query_categories->post_count;

			$this->posts = $query_authors;
		} elseif ( $query_authors && ! $query_categories ) {
			$this->posts = $query_authors;
		} else if ( ! $query_authors && $query_categories ) {
			$this->posts = $query_categories;
		}

		if ( $this->posts->have_posts() ) {
			$posts_ids = [];

			foreach ( $this->posts->posts as $post ) {
				if ( ! in_array( $post->ID, $posts_ids, true ) ) {
					$posts_ids[] = $post->ID;
				}
			}

			set_transient( 'fup_home_feed_posts_' . get_current_user_id(), $posts_ids );
		}
	}

	/**
	 * Display user feed
	 */
	public function get_user_feed() {
		if ( ! $this->posts || is_paged() || ! is_home() || ! is_user_logged_in() || ! typer()->get_option( 'fup_custom_feed' ) ) {
			delete_transient( 'fup_home_feed_posts_' . get_current_user_id() );

			return;
		}

		global $wp_query;
		$old_wp_query = $wp_query;
		$wp_query     = $this->posts;

		// Include posts loop
		typer()->get_template_part( 'template-parts/archive/feed' );

		$wp_query = $old_wp_query;
		wp_reset_postdata();
	}

	/**
	 * Exclude posts from feed if network box
	 *
	 * @param $query
	 */
	public function exclude_feed_posts( $query ) {
		if ( ! $query->is_home() || ! $query->is_main_query() ) {
			return;
		}

		if ( is_user_logged_in() && typer()->get_option( 'fup_custom_feed' ) ) {
			$exclude = get_transient( 'fup_home_feed_posts_' . get_current_user_id() );

			if ( is_array( $exclude ) && ! empty( $exclude ) ) {
				$post__not_in = $query->get( 'post__not_in' );

				if ( ! empty( $post__not_in ) ) {
					$exclude = array_merge( (array) $post__not_in, $exclude );
					$exclude = array_unique( $exclude );
				}

				$query->set( 'post__not_in', $exclude );
			}
		}
	}

}
