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

declare( strict_types = 1 );
namespace Dekode\Nisje\Components;

defined( 'ABSPATH' ) || die( 'Shame on you' );

if ( ! class_exists( '\\Dekode\\Nisje\\Components\\Grieg_Retriever' ) && class_exists( '\\Dekode\\Nisje\\Components\\Component' ) ) {
	/**
	 * Retriever Component Class
	 */
	class Grieg_Retriever extends Component {
		/**
		 * Constructor
		 */
		public function __construct() {
			$path = trailingslashit( __DIR__ );

			parent::start(
				'grieg-retriever',
				esc_html__( 'Grieg Retriever', 'nisje-grieg' ),
				$path
			);
		}

		/**
		 * Global variables
		 */
		public function setup_globals() {
			$settings = get_option( $this->option_key );
			if ( is_array( $settings ) && ! empty( $settings ) ) {
				foreach ( $settings as $key => $value ) {
					$this->settings[ $key ] = $value;
				}
			}

			$globals = [
				'post_type_name'          => 'nisje-retriever',
				'post_type_rest_endpoint' => 'nisje-retriever',
				'taxonomy_pub_name'       => 'nisje-retriever-pub',
				'field_key_prefix'        => 'nisje_grieg_retriever',
				'settings_menu_key'       => 'nisje-settings-grieg-retriever',
			];

			$defaults = array_merge( $globals, $this->default_settings() );

			$this->settings = wp_parse_args( $this->settings, $defaults );
		}

		/**
		 * Setup default settings.
		 */
		private function default_settings() {
			return [
				'author_id'            => 1,
				'override_author_name' => '',
			];
		}

		/**
		 * Global variables
		 */
		public function setup_filters() {
			add_filter( 'post_type_link', [ $this, 'rewrite_permalink' ], 10, 2 );
			add_filter( 'nisje_fpl_latest_post_types', [ $this, 'add_fpl_post_type' ] );

			$author_name = $this->settings['override_author_name'];
			if ( ! empty( $author_name ) ) {
				add_filter( 'nisje_rest_prepare_feed', [ $this, 'map_authordata' ], 10, 2 );
			}

			if ( is_admin() ) {
				$post_type_name = $this->settings['post_type_name'];
				add_filter( "manage_{$post_type_name}_posts_columns", [ $this, 'retriever_dashboard_columns' ] );
				add_action( "manage_{$post_type_name}_posts_custom_column", [ $this, 'retriever_dashboard_column_content' ], 10, 2 );

				add_action( 'nisje_settings_register_field_groups', [ $this, 'register_field_group' ] );
				add_action( 'nisje_settings_add_option_page', [ $this, 'setup_settings_menu' ] );
				add_action( 'nisje_settings_populate_options_from_acf', [ $this, 'populate_acf_settings' ] );
			}
		}

		/**
		 * Add retriever to latest post card
		 *
		 * @param array $post_types Current Post Types.
		 * @return array $post_types Populated Post Types.
		 */
		public function add_fpl_post_type( $post_types ) {
			$post_type_name = nisje_get_setting( 'post_type_name', 'grieg_retriever' );

			$post_types[ $post_type_name ] = __( 'Retriever', 'nisje-grieg' );

			return $post_types;
		}

		/**
		 * Register content types
		 */
		public function register_content_types() {
			// Post Types.
			$this->include_file( 'post-types/post-type-nisje-retriever.php' );
			// Taxonomies.
			$this->include_file( 'taxonomies/taxonomy-nisje-retriever-pub.php' );
		}

		/**
		 * Register REST Endpoints
		 */
		public function register_rest_routes() {
			$this->include_file( 'rest-handlers/extend-retriever.php' );
		}

		/**
		 * Return retriever link.
		 *
		 * @param string   $url  Url.
		 * @param \WP_Post $post Post object.
		 *
		 * @return string Url.
		 */
		public function rewrite_permalink( string $url, \WP_Post $post ) : string {
			if ( nisje_get_setting( 'post_type_name', $this->settings_key ) === get_post_type( $post ) ) {
				$retriever_link = get_post_meta( $post->ID, 'retriever_link', true );
				if ( $retriever_link ) {
					$url = $retriever_link;
				}
			}

			return $url;
		}

		/**
		 * Override author name.
		 *
		 * @param WP_REST_Response $response The response object.
		 * @param WP_Post          $post     Post object.
		 */
		public function map_authordata( $response, $post ) {
			$author_name = nisje_get_setting( 'override_author_name', $this->settings_key );
			if ( $post instanceof \WP_Post && 'nisje-retriever' === $post->post_type ) {
				if ( isset( $response->data['author_name'] ) ) {
					$response->data['author_name'] = $author_name;
				}
			}

			return $response;
		}

		/**
		 * Dashboard columns.
		 *
		 * @param array $columns Dashboard columns.
		 * @return array $columns Populated dashboard columns.
		 */
		public function retriever_dashboard_columns( array $columns ) : array {
			$columns['retriever_link'] = esc_html__( 'Retriever Link', 'nisje-grieg' );

			return $columns;
		}

		/**
		 * Dashboard column content.
		 *
		 * @param string $column_name Current column name.
		 * @param int    $post_id     Current column name.
		 */
		public function retriever_dashboard_column_content( string $column_name, int $post_id ) {
			if ( 'retriever_link' === $column_name ) {
				$link = esc_url( get_post_meta( $post_id, 'retriever_link', true ) );
				echo '<a href="' . esc_url( $link ) . '" target="_blank">Retriever</a><br>';
				echo esc_html( $link );
			}
		}


		/**
		 * Include acf field groups.
		 */
		public function register_field_group() {
			$this->include_file( 'acf/field-groups/acf-field-group-options-grieg-retriever.php' );
		}

		/**
		 * Setup the admin page.
		 */
		public function setup_settings_menu() {
			acf_add_options_sub_page( [
				'page_title'  => $this->label,
				'menu_title'  => $this->label,
				'capability'  => nisje_get_setting( 'settings_cap', 'core' ),
				'menu_slug'   => nisje_get_setting( 'settings_menu_key', $this->settings_key ),
				'parent_slug' => nisje_get_setting( 'settings_key', 'core' ),
			] );
		}

		/**
		 * Populate ACF Options General
		 *
		 * @param \WP_Screen $screen Screen object.
		 */
		public function populate_acf_settings( \WP_Screen $screen ) {
			if ( false !== strpos( $screen->id, nisje_get_setting( 'settings_menu_key', $this->settings_key ) ) ) {
				$default_settings = $this->default_settings();
				$settings         = [];

				$field_key_prefix = nisje_get_setting( 'field_key_prefix', $this->settings_key );

				foreach ( $default_settings as $key => $value ) {
					$option = get_field( $field_key_prefix . '_' . $key, 'option' );
					if ( $option && $option !== $value && ! empty( $option ) ) {
						$settings[ $key ] = $option;
					}
				}

				update_option( $this->option_key, $settings );
			}
		}
	}
}
