<?php
/**
 * Retriever Import
 *
 * @package Nisje
 */

declare( strict_types=1 );

namespace Dekode\Nisje\Commands;

use WP_CLI;
use Exception;
use StdClass;
use WP_Post;

if ( class_exists( 'WP_CLI' ) ) {
	/**
	 * Retriever import.
	 */
	class Grieg_Retriever {
		/**
		 * This function is run on the command "wp grieg-retriever import"
		 */
		public function import() {
			$url = 'https://app.meltwater.com/gyda/outputs/5dadb77e880b2d9f5da45577/rendering?apiKey=5d6e4c2fadcdfc00152e4cf0&type=xml';

			add_filter( 'wp_revisions_to_keep', [ $this, 'restrict_revisions' ], 10, 2 );

			$load_xml = simplexml_load_file( $url );

			if ( ! $load_xml ) {
				WP_CLI::error( 'Could not find any posts' );
			}

			WP_CLI::line( 'Found ' . count( $load_xml->feed->documents ) . ' posts.' );

			foreach ( $load_xml->feed->documents as $item ) {
				$guid = (string) $item->guid;
				WP_CLI::line( 'Importing post ' . $guid );
				$this->create_or_update( $item->document );
			}

			WP_CLI::success( 'Retriever posts successfully merged and updated' );
		}

		/**
		 * Restrict revisions when importing.
		 *
		 * @param  int      $num  Number of allowed revisions.
		 * @param  \WP_Post $post Current post.
		 *
		 * @return int Custom revisions.
		 */
		public function restrict_revisions( int $num, \WP_Post $post ): int {
			return 0;
		}

		/**
		 * Takes a retriever post and creates a new post for it or updates an existing one.
		 *
		 * @param  \SimpleXMLElement $item The item.
		 */
		private function create_or_update( \SimpleXMLElement $item ) {

			$guid = (string) $item->docId; // phpcs:ignore

			$original_post = $this->get_existing_post( $guid );
			$author        = $this->get_import_author();

			$title       = (string) $item->title;
			$link        = (string) $item->url;
			$description = (string) $item->ingress;
			$pubdate     = (string) $item->createDate; // phpcs:ignore
			$creator     = (string) $item->sourcename;

			$ret_namespace = [
				'docdate'   => isset( $item->createDate ) ? (string) $item->createDate : '', // phpcs:ignore
				'source'    => isset( $item->sourcename ) ? (string) $item->sourcename : '',
				'source_id' => isset( $item->sourceid ) ? (string) $item->sourceid : '',
				'language'  => isset( $item->language ) ? (string) $item->language : '',
			];

			$dynteaser = (string) $item->ingress;
			$date_gmt  = gmdate( 'Y-m-d H:i:s', strtotime( $pubdate ) );
			$date      = mysql2date( 'Y-m-d H:i:s', $date_gmt );

			$data = [
				'post_status'   => 'draft',
				'post_type'     => nisje_get_setting( 'post_type_name', 'grieg_retriever' ),
				'ping_status'   => 'closed',
				'post_author'   => $author,
				'post_title'    => $title,
				'post_content'  => $description,
				'post_excerpt'  => $dynteaser,
				'post_date_gmt' => $date_gmt,
				'post_date'     => $date,
			];

			if ( is_object( $original_post ) && 'WP_Post' === get_class( $original_post ) ) {
				$data['ID']          = $original_post->ID;
				$data['post_status'] = $original_post->post_status;
				WP_CLI::line( "\t" . 'Found original post so updating post ' . $original_post->ID );
			} else {
				WP_CLI::line( "\t" . 'No original post found, creating new' );
			}

			$post_id = wp_insert_post( $data );

			if ( ! $post_id ) {
				WP_CLI::line( "\t" . 'Post not imported - ' . $title );
			}

			wp_set_object_terms( $post_id, $creator, nisje_get_setting( 'taxonomy_pub_name', 'grieg_retriever' ), true );

			update_post_meta( $post_id, 'retriever_link', esc_url( $link ) );
			update_post_meta( $post_id, 'nisje_grieg_retriever_guid', $guid );

			$retriever_object = [];
			foreach ( $ret_namespace as $key => $ret_value ) {
				$retriever_object[ $key ] = $ret_value;
			}

			update_post_meta( $post_id, 'retriever_object', $retriever_object );
		}

		/**
		 * Finds existing post in WordPress
		 *
		 * @param  string $remote_id The ID of the post to be found.
		 *
		 * @return array|boolean
		 */
		private function get_existing_post( string $remote_id ) { // phpcs:ignore
			$args = [
				'post_type'   => nisje_get_setting( 'post_type_name', 'grieg_retriever' ),
				'post_status' => 'any',
				'meta_query'  => [ // phpcs:ignore
					[
						'key'     => 'nisje_grieg_retriever_guid',
						'value'   => $remote_id,
						'compare' => '=',
						'type'    => 'string',
					],
				],
			];

			$query = new \WP_Query( $args );

			$posts = $query->get_posts();
			if ( isset( $posts[0] ) ) {
				return $posts[0];
			} else {
				return null;
			}
		}

		/**
		 * Import author id
		 *
		 * @return int Author id.
		 */
		private function get_import_author(): int {
			return nisje_get_setting( 'author_id', 'grieg_retriever' );
		}
	}

	$retriever = new Grieg_Retriever();

	WP_CLI::add_command( 'grieg-retriever', $retriever );
}
