<?php
namespace PowerpackElements\Modules\Posts;

use PowerpackElements\Base\Module_Base;

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

class Module extends Module_Base {

	public static $displayed_ids = [];

	/**
	 * Constructor.
	 */
	public function __construct() {
		parent::__construct();

		add_action( 'wp_ajax_pp_get_post', array( $this, 'get_post_data' ) );
		add_action( 'wp_ajax_nopriv_pp_get_post', array( $this, 'get_post_data' ) );

		add_action( 'elementor/frontend/after_register_styles', [ $this, 'register_styles' ] );
	}

	public function get_name() {
		return 'pp-posts';
	}

	public function get_widgets() {
		return [
			'Card_Slider',
			'Content_Ticker',
			'Magazine_Slider',
			'Tiled_Posts',
			'Posts',
			'Timeline',
		];
	}

	public static function add_to_avoid_list( $ids ) {
		self::$displayed_ids = array_unique( array_merge( self::$displayed_ids, $ids ) );
	}

	public static function get_avoid_list_ids() {
		return self::$displayed_ids;
	}

	/**
	 * Whether the visitor is allowed to be served content from a document.
	 *
	 * The nonce on this endpoint is created for logged-out visitors too, so it
	 * proves the request came from one of our pages — not that the requester may
	 * read the document it names. Without this check any visitor could walk post
	 * IDs and have a draft or private page rendered back to them.
	 *
	 * @since 3.0.1
	 * @access private
	 *
	 * @param int $post_id Document ID.
	 *
	 * @return bool
	 */
	private function is_document_readable( $post_id ) {
		$post = get_post( $post_id );

		if ( ! $post ) {
			return false;
		}

		if ( post_password_required( $post ) ) {
			return false;
		}

		$status = get_post_status_object( $post->post_status );

		if ( $status && $status->public ) {
			return true;
		}

		// Drafts, private and pending: only for someone who could read them anyway.
		return current_user_can( 'read_post', $post_id );
	}

	public function get_post_data() {

		check_ajax_referer( 'pp-posts-widget-nonce', 'nonce' );

		$post_id = isset( $_POST['page_id'] ) ? absint( wp_unslash( $_POST['page_id'] ) ) : 0;

		// Elementor element ids are short alphanumeric strings; keep the case so
		// the lookup still matches, but allow nothing else through.
		$widget_id = isset( $_POST['widget_id'] ) ? preg_replace( '/[^a-zA-Z0-9_-]/', '', wp_unslash( $_POST['widget_id'] ) ) : '';

		$filter          = isset( $_POST['category'] ) ? sanitize_text_field( wp_unslash( $_POST['category'] ) ) : '';
		$filter          = str_replace( '.', '', $filter );
		$taxonomy_filter = isset( $_POST['taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['taxonomy'] ) ) : '';
		$search_filter   = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '';
		$ajax_for        = isset( $_POST['ajax_for'] ) ? sanitize_key( wp_unslash( $_POST['ajax_for'] ) ) : '';

		$data = array(
			'message'    => esc_html__( 'Saved', 'powerpack' ),
			'ID'         => '',
			'skin_id'    => '',
			'html'       => '',
			'not_found'  => '',
			'pagination' => '',
		);

		if ( ! $post_id || ! $widget_id || ! $this->is_document_readable( $post_id ) ) {
			wp_send_json_error( $data );
		}

		$elementor = \Elementor\Plugin::$instance;
		$document  = $elementor->documents->get( $post_id );

		if ( ! $document ) {
			wp_send_json_error( $data );
		}

		$widget_data = $this->find_element_recursive( $document->get_elements_data(), $widget_id );

		if ( ! $widget_data ) {
			wp_send_json_error( $data );
		}

		if ( isset( $widget_data['templateID'] ) ) {
			$template_data = \Elementor\Plugin::$instance->templates_manager->get_template_data( [
				'source'        => 'local',
				'template_id'   => $widget_data['templateID'],
			] );

			if ( is_array( $template_data ) && isset( $template_data['content'] ) ) {
				$widget_data = $template_data['content'][0];
			}
		}

		$widget = $elementor->elements_manager->create_element_instance( $widget_data );

		if ( ! $widget ) {
			wp_send_json_error( $data );
		}

		// The id names an element on the page, but not necessarily one of ours —
		// render_ajax_post_body() only exists on the widgets that serve this endpoint.
		if ( 'coupon' === $ajax_for || 'timeline' === $ajax_for ) {
			if ( ! method_exists( $widget, 'render_ajax_post_body' ) ) {
				wp_send_json_error( $data );
			}

			$skin_body  = $widget->render_ajax_post_body( $filter, $taxonomy_filter, $search_filter );
			$not_found  = '';
			$pagination = $widget->render_ajax_pagination( $filter, $taxonomy_filter, $search_filter );
		} else {
			$skin = method_exists( $widget, 'get_current_skin' ) ? $widget->get_current_skin() : null;

			if ( ! $skin || ! method_exists( $skin, 'render_ajax_post_body' ) ) {
				wp_send_json_error( $data );
			}

			$skin_body  = $skin->render_ajax_post_body( $filter, $taxonomy_filter, $search_filter );
			$not_found  = $skin->render_ajax_not_found( $filter, $taxonomy_filter, $search_filter );
			$pagination = $skin->render_ajax_pagination();
		}

		$data['ID']         = $widget->get_id();
		$data['skin_id']    = $widget->get_current_skin_id();
		$data['html']       = $skin_body;
		$data['not_found']  = $not_found;
		$data['pagination'] = $pagination;

		wp_send_json_success( $data );
	}

	/**
	 * Get Widget Setting data.
	 *
	 * @since 1.7.0
	 * @access public
	 * @param array  $elements Element array.
	 * @param string $form_id Element ID.
	 * @return Boolean True/False.
	 */
	public function find_element_recursive( $elements, $form_id ) {

		foreach ( $elements as $element ) {
			if ( $form_id === $element['id'] ) {
				return $element;
			}

			if ( ! empty( $element['elements'] ) ) {
				$element = $this->find_element_recursive( $element['elements'], $form_id );

				if ( $element ) {
					return $element;
				}
			}
		}

		return false;
	}

	/**
	 * Get Post Parts
	 *
	 * @since  1.4.11.0
	 * @return array
	 */
	public static function get_post_parts() {
		$post_parts = [
			'thumbnail',
			'terms',
			'title',
			'meta',
			'excerpt',
			'button',
		];

		return $post_parts;
	}

	/**
	 * Get Meta Items
	 *
	 * @since  1.4.11.0
	 * @return array
	 */
	public static function get_meta_items() {
		$meta_items = [
			'author',
			'date',
			'comments',
		];

		return $meta_items;
	}

	/**
	 * Register styles.
	 *
	 * @return void
	 */
	public function register_styles() {
		wp_register_style(
			'widget-pp-card-slider',
			$this->get_css_assets_url( 'widget-card-slider', null, true, true ),
			[],
			POWERPACK_ELEMENTS_VER
		);

		wp_register_style(
			'widget-pp-content-ticker',
			$this->get_css_assets_url( 'widget-content-ticker', null, true, true ),
			[],
			POWERPACK_ELEMENTS_VER
		);

		wp_register_style(
			'widget-pp-posts',
			$this->get_css_assets_url( 'widget-posts', null, true, true ),
			[],
			POWERPACK_ELEMENTS_VER
		);

		wp_register_style(
			'widget-pp-tiled-posts',
			$this->get_css_assets_url( 'widget-tiled-posts', null, true, true ),
			[],
			POWERPACK_ELEMENTS_VER
		);

		wp_register_style(
			'widget-pp-timeline',
			$this->get_css_assets_url( 'widget-timeline', null, true, true ),
			[],
			POWERPACK_ELEMENTS_VER
		);
	}
}
