<?php
/**
 * Helpers for use in Maintainn Tools plugin.
 *
 * @version 2.0
 * @package Maintainn Tools
 */

/**
 * Class for helper functions.
 */
class Maintainn_Tools_Helpers {
	/**
	 * REST API URL where to fetch announcements.
	 *
	 * @since 2.3.0
	 */
	const ANNOUNCEMENT_API_URL = 'https://maintainn.com/wp-json/wp/v2/announcements';

	/**
	 * Transient key for the latest announcements.
	 *
	 * @since 2.3.0
	 */
	const ANNOUNCEMENTS_TRANSIENT_KEY = 'maintainn_tools_announcements';

	/**
	 * Maintainn_Tools obj
	 *
	 * @var Maintainn_Tools
	 */
	protected $plugin;

	public function __construct( $plugin ) {
		$this->plugin = $plugin;
	}

	/**
	 * Get columns for the maintainn about page.
	 *
	 * @since  2.0
	 *
	 * @return array Columns for the about page.
	 */
	public function get_about_page_columns() {
		$columns = array(
			array(
				'img'     => esc_url( plugins_url( 'assets/img/Info.png', __DIR__ ) ),
				'title'   => esc_html__( 'Site Info', 'maintainn-tools' ),
				'content' => esc_html__( 'A top level view of your entire WordPress install. View registered post types &amp; post statuses, permalink structure, multisite network actived plugins, active &amp; inactive plugins, must-use plugins (MU), site &amp; server details, browser details, session details, and email yourself a copy.', 'maintainn-tools' ),
			),
			array(
				'img'     => esc_url( plugins_url( 'assets/img/Scanner.png', __DIR__ ) ),
				'title'   => esc_html__( 'Site Scanner', 'maintainn-tools' ),
				'content' => esc_html__( 'Compare the WordPress Core files on your website hosting server to the current WordPress files available from the WordPress.org repository, to ensure they have not been altered in any way.', 'maintainn-tools' ),
			),
			array(
				'img'     => esc_url( plugins_url( 'assets/img/Tools.png', __DIR__ ) ),
				'title'   => esc_html__( 'Tools', 'maintainn-tools' ),
				'content' => esc_html__( 'This feature has three main functions.', 'maintainn-tools' ) .
				'<ol>
					<li>' . esc_html__( 'Turn on/off automatic updates for specific plugins.', 'maintainn-tools' ) . '</li>
					<li>' . esc_html__( 'Lock a specific plugin.', 'maintainn-tools' ) . '</li>
					<li>' . esc_html__( 'Plugin admin notes.', 'maintainn-tools' ) . '</li>
				</ol>',
			),
			array(
				'img'     => esc_url( plugins_url( 'assets/img/Maintainn.png', __DIR__ ) ),
				'title'   => esc_html__( 'Maintainn Support', 'maintainn-tools' ),
				'content' => esc_html__( 'Use this simple set of tools to scan your WordPress website. Check for updates, active and inactive plugins, site and server details, and much more.', 'maintainn-tools' ),
			),
		);

		/**
		 * Filter column data that shows on the about page.
		 *
		 * Add/remove columns from the about page.
		 *
		 * @since 2.0.0
		 *
		 * @param array $columns The data for the insert/update.
		 */
		$columns = apply_filters( 'maintainn_tools_about_page_columns', $columns );

		// Holds sorted columns.
		$sorted_columns = array();

		// Keep track of counts and rows.
		$count = 0;
		$row   = 0;

		// Loop through columns and sort two to a row.
		foreach ( (array) $columns as $column ) {
			// Increment count.
			++$count;

			// Increment row if necessary.
			if ( 2 < $count ) {
				++$row;

				// Reset count.
				$count = 0;
			}

			// Add column to a row.
			$sorted_columns[ $row ][] = $column;
		}

		return $sorted_columns;
	}

	/**
	 * Get columns for the maintainn support page first column.
	 *
	 * @since  2.0
	 *
	 * @return array Columns for the support page first column.
	 */
	public function get_support_page_first_columns() {
		$columns = array(
			array(
				'title'   =>
					sprintf(
						'<a href="%s" target="_blank">%s</a>',
						esc_url( 'https://maintainn.com/features/weekly-updates/' ),
						esc_html__( 'WordPress Updates', 'maintainn-tools' )
					),
				'content' => esc_html__( 'With weekly WordPress, plugin, and theme updates, you can rest easy knowing that your website is operating exactly as it should be.', 'maintainn-tools' ),
			),
			array(
				'title'   =>
					sprintf(
						'<a href="%s" target="_blank">%s</a>',
						esc_url( 'https://maintainn.com/features/24-7-security-monitoring/' ),
						esc_html__( 'Security', 'maintainn-tools' )
					),
				'content' => esc_html__( 'Because viruses, malware, and hackers work 24 hours, and you don’t… our security monitoring does! Don’t wake up to a website that has been hacked or is infected with malware. Allow us to monitor it 24 hours a day, seven days per week.', 'maintainn-tools' ),
			),
			array(
				'title'   =>
					sprintf(
						'<a href="%s" target="_blank">%s</a>',
						esc_url( 'https://maintainn.com/features/email-support/' ),
						esc_html__( 'Our Team Is Your Team', 'maintainn-tools' )
					),
				'content' => esc_html__( 'No internal tech team? No problem. Use ours! With the click of a button, our experts are available to offer you WordPress assistance, guidance, and answers.', 'maintainn-tools' ),
			),
			array(
				'title'   =>
					sprintf(
						'<a href="%s" target="_blank">%s</a>',
						esc_url( 'https://maintainn.com/features/' ),
						esc_html__( 'Website Migrations', 'maintainn-tools' )
					),
				'content' => esc_html__( 'You’re on the move and so is your website. Let us move your website from one host to another without you lifting a finger.', 'maintainn-tools' ),
			),
			array(
				'title'   =>
					sprintf(
						'<a href="%s" target="_blank">%s</a>',
						esc_url( 'https://maintainn.com/features/staging-updates/' ),
						esc_html__( 'Staging', 'maintainn-tools' )
					),
				'content' => esc_html__( 'A botched update can ruin a live production website. Let Maintainn help you set up a staging environment to ensure that any unexpected issues will not affect your live website.', 'maintainn-tools' ),
			),
			array(
				'title'   =>
					sprintf(
						'<a href="%s" target="_blank">%s</a>',
						esc_url( 'https://maintainn.com/support-hours/' ),
						esc_html__( 'Custom Development', 'maintainn-tools' )
					),
				'content' => esc_html__( 'Your website needs are as unique as you are. When you require the development of customized functionalities, tap into our experience and expertise to achieve your WordPress goals.', 'maintainn-tools' ),
			),
		);

		/**
		 * Filter column data that shows on the support page first column.
		 *
		 * Add/remove columns from the support page first column.
		 *
		 * @since 2.0
		 *
		 * @param         array $columns      The data for the insert/update.
		 */
		$columns = apply_filters( 'maintainn_tools_support_page_first_columns', $columns );

		// Holds sorted columns.
		$sorted_columns = array();

		// Keep track of counts and rows.
		$count = 0;
		$row   = 0;

		// Loop through columns and sort two to a row.
		foreach ( (array) $columns as $column ) {
			// Increment count.
			++$count;

			// Increment row if necessary.
			if ( 3 < $count ) {
				++$row;

				// Reset count.
				$count = 0;
			}

			// Add column to a row.
			$sorted_columns[ $row ][] = $column;
		}

		return $sorted_columns;
	}

	/**
	 * Fetch the latest announcement
	 *
	 * It will first try to get last fetched announcement from transient.
	 * If the transient already expired or non-existent, it will remote get from maintainn.com.
	 *
	 * @since 2.3.0
	 *
	 * @return bool|Maintainn_Tools_Announcement Returns false if nothing was fetched. Otherwise Maintainn_Tools_Announcement.
	 */
	public function fetch_latest_announcement() {
		$json_latest_announcements = get_transient( self::ANNOUNCEMENTS_TRANSIENT_KEY );
		if ( empty( $json_latest_announcements ) ) {
			$json_latest_announcements = $this->remote_get_latest_announcements();
		}

		$latest_announcements = json_decode( $json_latest_announcements );
		if ( empty( $latest_announcements ) ) {
			return false;
		}

		return new Maintainn_Tools_Announcement( $latest_announcements[0] );
	}

	/**
	 * Remote fetch the latest announcements from maintainn.com
	 *
	 * @since 2.3.0
	 *
	 * @return array|bool|mixed
	 */
	public function remote_get_latest_announcements() {
		$announcement_api_url = defined( 'MAINTAINN_TOOLS_ANNOUNCEMENT_URL' ) ? MAINTAINN_TOOLS_ANNOUNCEMENT_URL : self::ANNOUNCEMENT_API_URL;

		$request_url = add_query_arg( [
			'per_page' => 1,
		], $announcement_api_url );

		$response = wp_remote_get( $request_url );
		if ( is_wp_error( $response ) ) {
			return false;
		}

		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
			return false;
		}

		$body          = wp_remote_retrieve_body( $response );
		$json_response = json_decode( $body );
		if ( empty( $json_response ) || ! is_array( $json_response ) ) {
			return false;
		}

		$announcements = [];
		array_walk( $json_response, function ( $json_response_obj ) use ( &$announcements ) {
			$announcement = new Maintainn_Tools_Announcement( $json_response_obj );

			if ( empty( $announcement->get_date() ) ) {
				return;
			}
			$announcements[] = $announcement;
		} );

		if ( empty( $announcements ) ) {
			return false;
		}

		$json_encoded_announcements = wp_json_encode( $announcements );
		set_transient( self::ANNOUNCEMENTS_TRANSIENT_KEY, $json_encoded_announcements, DAY_IN_SECONDS );

		return $json_encoded_announcements;
	}
}
