<?php
/**
 * Library api class
 */
namespace CSSIgniter\Ignition\Elementor;

use Elementor\TemplateLibrary\Source_Base;

defined( 'ABSPATH' ) || die();

class Library_Source extends Source_Base {

	/**
	 * Template library data cache
	 */
	const LIBRARY_CACHE_KEY = 'ignition_elementor_library_cache';

	const LIBRARY_CACHE_EXPIRATION = DAY_IN_SECONDS;

	/**
	 * Template info api url
	 */
	const API_TEMPLATES_INFO_URL = 'https://cssigniter.com/wp-json/ignition-elementor-templates/v1/info';

	/**
	 * Template data api url
	 */
	const API_TEMPLATE_DATA_URL = 'https://cssigniter.com/wp-json/ignition-elementor-templates/v1/get-template';

	/**
	 * Returns username and API key from CSSIgniter updater.
	 *
	 * @since 1.3.0
	 *
	 * @return array $data CSSIgniter Updater data
	 */
	public static function get_cssigniter_credentials() {
		if ( function_exists( 'CSSIgniter_Updater' ) ) {
			$credentials = CSSIgniter_Updater()->get_api_credentials();
		} else {
			$credentials = array(
				'username' => '',
				'url'      => '',
				'hmac'     => '',
			);
		}

		return $credentials;
	}

	/**
	 * Get remote template ID.
	 *
	 * Retrieve the remote template ID.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @return string The remote template ID.
	 */
	public function get_id() {
		return 'ci-library';
	}

	/**
	 * Get remote template title.
	 *
	 * Retrieve the remote template title.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @return string The remote template title.
	 */
	public function get_title() {
		return __( 'CSSIgniter Template Library', 'ignition-elementor-widgets' );
	}

	/**
	 * Register remote template data.
	 *
	 * Used to register custom template data like a post type, a taxonomy or any
	 * other data.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 */
	public function register_data() {}

	/**
	 * Save remote template.
	 *
	 * Remote template from Elementor.com servers cannot be saved on the
	 * database as they are retrieved from remote servers.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @param array $template_data Remote template data.
	 *
	 * @return \WP_Error
	 */
	public function save_item( $template_data ) {
		return new \WP_Error( 'invalid_request', 'Cannot save template' );
	}

	/**
	 * Update remote template.
	 *
	 * Remote template from Elementor.com servers cannot be updated on the
	 * database as they are retrieved from remote servers.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @param array $new_data New template data.
	 *
	 * @return \WP_Error
	 */
	public function update_item( $new_data ) {
		return new \WP_Error( 'invalid_request', 'Cannot update template' );
	}

	/**
	 * Delete remote template.
	 *
	 * Remote template from Elementor.com servers cannot be deleted from the
	 * database as they are retrieved from remote servers.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @param int $template_id The template ID.
	 *
	 * @return \WP_Error
	 */
	public function delete_template( $template_id ) {
		return new \WP_Error( 'invalid_request', 'Cannot delete template' );
	}

	/**
	 * Export remote template.
	 *
	 * Remote template from Elementor.com servers cannot be exported from the
	 * database as they are retrieved from remote servers.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @param int $template_id The template ID.
	 *
	 * @return \WP_Error
	 */
	public function export_template( $template_id ) {
		return new \WP_Error( 'invalid_request', 'Cannot export template' );
	}

	/**
	 * Get remote templates.
	 *
	 * Retrieve remote templates from Elementor.com servers.
	 *
	 * @since 1.3.0
	 *
	 * @access public
	 *
	 * @param array $args Optional. Nou used in remote source.
	 *
	 * @return array Remote templates.
	 */
	public function get_items( $args = array() ) {
		$library_data = self::get_library_data();

		$templates = array();

		if ( ! empty( $library_data['templates'] ) ) {
			foreach ( $library_data['templates'] as $template_data ) {
				$templates[] = $this->prepare_template( $template_data );
			}
		}

		return $templates;
	}

	public function get_tags() {
		$library_data = self::get_library_data();

		return ( ! empty( $library_data['tags'] ) ? $library_data['tags'] : array() );
	}

	public function get_type_tags() {
		$library_data = self::get_library_data();

		return ( ! empty( $library_data['type_tags'] ) ? $library_data['type_tags'] : array() );
	}

	public function get_buttons() {
		$library_data = self::get_library_data();

		return ( ! empty( $library_data['buttons'] ) ? $library_data['buttons'] : array() );
	}

	/**
	 * Prepare template items to match model
	 *
	 * @param array $template_data
	 * @return array
	 */
	private function prepare_template( array $template_data ) {
		return array(
			'template_id' => $template_data['id'],
			'title'       => $template_data['title'],
			'type'        => $template_data['type'],
			'thumbnail'   => $template_data['thumbnail'],
			'date'        => $template_data['created_at'],
			'tags'        => $template_data['tags'],
			'url'         => $template_data['url'],
			'isAvailable' => $template_data['is_available'],
		);
	}

	/**
	 * Get library data from remote source and cache
	 *
	 * @param boolean $force_update
	 * @return array
	 */
	private static function request_library_data( $force_update = false ) {
		$data = get_transient( self::LIBRARY_CACHE_KEY );

		if ( $force_update || false === $data ) {
			$timeout = ( $force_update ) ? 25 : 8;

			$base_url = self::API_TEMPLATES_INFO_URL;
			$url      = add_query_arg( array_merge( self::get_cssigniter_credentials(), array(
				'theme'     => get_template(),
				'variation' => get_theme_mod( 'theme_variation', '' ),
			) ), $base_url );

			$response = wp_remote_get(
				$url,
				array(
					'timeout' => $timeout,
				)
			);

			if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
				set_transient( self::LIBRARY_CACHE_KEY, array(), self::LIBRARY_CACHE_EXPIRATION );
				return array();
			}

			$data = json_decode( wp_remote_retrieve_body( $response ), true );

			if ( empty( $data ) || ! is_array( $data ) ) {
				set_transient( self::LIBRARY_CACHE_KEY, array(), self::LIBRARY_CACHE_EXPIRATION );
				return array();
			}

			set_transient( self::LIBRARY_CACHE_KEY, $data, self::LIBRARY_CACHE_EXPIRATION );
		}

		return $data;
	}

	/**
	 * Get library data
	 *
	 * @param boolean $force_update
	 * @return array
	 */
	public static function get_library_data( $force_update = false ) {
		self::request_library_data( $force_update );

		$data = get_transient( self::LIBRARY_CACHE_KEY );

		if ( empty( $data ) ) {
			return array();
		}

		return $data;
	}

	/**
	 * Get remote template.
	 *
	 * Retrieve a single remote template from Elementor.com servers.
	 *
	 * @param int $template_id The template ID.
	 *
	 * @return array Remote template.
	 */
	public function get_item( $template_id ) {
		$templates = $this->get_items();

		return $templates[ $template_id ];
	}

	public static function request_template_data( $template_id ) {
		if ( empty( $template_id ) ) {
			return null;
		}

		$body = array(
			'home_url' => trailingslashit( home_url() ),
			'version'  => IGNITION_ELEMENTOR_WIDGETS_VERSION,
		);

		$base_url = self::API_TEMPLATE_DATA_URL;
		$url      = add_query_arg( array_merge( self::get_cssigniter_credentials(), array(
			'template-id' => $template_id,
		) ), $base_url );

		$response = wp_remote_get(
			$url,
			array(
				'body'    => $body,
				'timeout' => 25,
			)
		);

		return wp_remote_retrieve_body( $response );
	}

	/**
	 * Get remote template data.
	 *
	 * Retrieve the data of a single remote template from Elementor.com servers.
	 *
	 * @return array|\WP_Error Remote Template data.
	 */
	public function get_data( array $args, $context = 'display' ) {
		$data = self::request_template_data( $args['template_id'] );

		$data = json_decode( $data, true );

		if ( is_null( $data ) || ! isset( $data['success'] ) ) {
			throw new \Exception( __( 'Invalid response', 'ignition-elementor-widgets' ) );
		}

		if ( ! $data['success'] ) {
			throw new \Exception( $data['error'] );
		}

		if ( empty( $data ) || empty( $data['content'] ) ) {
			throw new \Exception( __( 'Template does not have any content', 'ignition-elementor-widgets' ) );
		}

		$data['content'] = $this->replace_elements_ids( $data['content'] );
		$data['content'] = $this->process_export_import_content( $data['content'], 'on_import' );

		$post_id  = $args['editor_post_id'];
		$document = Ignition_Elementor_Widgets()->elementor->documents->get( $post_id );

		if ( $document ) {
			$data['content'] = $document->get_elements_raw_data( $data['content'], true );
		}

		return $data;
	}
}
