<?php

use Wordlift\Admin\Top_Entities;

class Wordlift_Admin_Dashboard_V2 {

	const TODAYS_TIP       = 'wl_todays_tip_data';
	const AVERAGE_POSITION = 'wl_search_rankings_average_position';

	/**
	 * @var \Wordlift_Entity_Service $entity_service
	 */
	private $entity_service;

	/**
	 * Wordlift_Admin_Dashboard_V2 constructor.
	 *
	 * @since 3.20.0
	 */
	public function __construct( $entity_service ) {

		add_action( 'wp_dashboard_setup', array( $this, 'dashboard_setup' ) );

		// Define where to access the tip.
		defined( 'WL_TODAYS_TIP_JSON_URL' ) || define( 'WL_TODAYS_TIP_JSON_URL', 'https://wordlift.io/blog' );
		defined( 'WL_TODAYS_TIP_JSON_URL_IT' ) || define( 'WL_TODAYS_TIP_JSON_URL_IT', '/it/wp-json/wp/v2/posts?context=embed&per_page=1&categories=27' );
		defined( 'WL_TODAYS_TIP_JSON_URL_EN' ) || define( 'WL_TODAYS_TIP_JSON_URL_EN', '/en/wp-json/wp/v2/posts?context=embed&per_page=1&categories=38' );
		$this->entity_service = $entity_service;
	}

	/**
	 * Set up the dashboard metabox.
	 *
	 * @since 3.20.0
	 */
	public function dashboard_setup() {
		/**
		 * Filter name: wl_feature__enable__wordlift-dashboard
		 * Feature flag to enable / disable dashboard
		 *
		 * @since 3.30.0
		 */
        // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
		if ( apply_filters( 'wl_feature__enable__wordlift-dashboard', true ) ) {
			wp_add_dashboard_widget(
				'wl-dashboard-v2',
				__( 'WordLift Dashboard', 'wordlift' ),
				array( $this, 'dashboard_setup_callback' )
			);
		}
	}

	/**
	 * The dashboard setup callback.
	 *
	 * @since 3.20.0
	 */
	public function dashboard_setup_callback() {

		require_once plugin_dir_path( __DIR__ ) . 'admin/partials/wordlift-admin-dashboard-v2.php';
	}

	/**
	 * Get the top entities.
	 *
	 * @return array|object|null An array of top entities.
	 * @since 3.20.0
	 */
	private function get_top_entities() {
		/**
		 * @since 3.27.7
		 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
		 * Top entities are generated by cron now.
		 */
		return get_option( Top_Entities::OPTION_KEY, array() );
	}

	/**
	 * Get the today's tip block.
	 *
	 * @since 3.20.0
	 */
	public static function get_todays_tip_block() {

        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
		$data = @self::get_todays_tip_data();

		// Unable to get data from the local cache, nor from the remote URL.
		if ( false === $data ) {
			return;
		}
		?>

		<div id="wl-todays-tip" class="wl-dashboard__block wl-dashboard__block--todays-tip">
			<header>
				<h3><?php esc_html_e( "Today's Tip", 'wordlift' ); ?></h3>
			</header>
			<article>
				<p><strong><?php echo esc_html( wp_strip_all_tags( $data['title'] ) ); ?></strong>
					<?php echo esc_html( wp_strip_all_tags( $data['excerpt'] ) ); ?>
					<a target="_blank"
						href="<?php echo esc_attr( $data['link'] ); ?>"><?php echo esc_html( __( 'Read more', 'wordlift' ) ); ?></a>
				</p>
		</div>
		<?php
	}

	/**
	 * Get the today's tip data.
	 *
	 * @return array|false The today's tip data or false in case of error.
	 * @since 3.20.0
	 */
	private static function get_todays_tip_data() {

		// Return the transient.
		if ( false !== get_transient( self::TODAYS_TIP ) ) {
			return get_transient( self::TODAYS_TIP );
		}

		// If the transient isn't available, query the remote web site.
		$url = WL_TODAYS_TIP_JSON_URL
				. ( 'it' === get_bloginfo( 'language' ) ? WL_TODAYS_TIP_JSON_URL_IT : WL_TODAYS_TIP_JSON_URL_EN );

		$response = wp_remote_get( $url );

		if ( is_wp_error( $response )
			|| ! isset( $response['response']['code'] )
			|| 2 !== (int) $response['response']['code'] / 100 ) {
			return false;
		}

		$json = json_decode( $response['body'], true );

		if ( empty( $json )
			|| ! isset( $json[0]['title']['rendered'] )
			|| ! isset( $json[0]['excerpt']['rendered'] )
			|| ! isset( $json[0]['link'] ) ) {
			return false;
		}

		$value = array(
			'title'   => $json[0]['title']['rendered'],
			'excerpt' => '<!-- cached -->' . $json[0]['excerpt']['rendered'],
			'link'    => $json[0]['link'],
		);

		// Store the results for one day.
		set_transient( self::TODAYS_TIP, $value, 86400 );

		return $value;
	}
}
