<?php
/**
 * Enhancements to the WordPress backend.
 *
 * @package Tasty_Roundups
 */

namespace Tasty_Roundups;

use Tasty\Framework\Utils\Url;
use Tasty\Framework\Utils\Vars;
use Tasty\Framework\Admin\License\EDDUpdater;
use Tasty_Roundups\Block_Editor;

/**
 * Enhancements to the WordPress backend.
 */
class Admin {

	/**
	 * Capability required to manage settings.
	 *
	 * @var string
	 */
	const CAPABILITY = 'manage_options';

	/**
	 * Name of the plugin author.
	 *
	 * @var string
	 */
	const ITEM_AUTHOR = 'Tasty Roundups';

	/**
	 * Name of the product.
	 *
	 * @var string
	 */
	const ITEM_NAME = 'Tasty Roundups';

	/**
	 * Key used for the license check cache.
	 *
	 * @var string
	 */
	const LICENSE_CHECK_CACHE_KEY = 'tasty-roundups-license-check';

	/**
	 * Option used to store the license key.
	 *
	 * @var string
	 */
	const LICENSE_KEY_OPTION = 'tasty_roundup_license_key';

	/**
	 * Slug for the settings page.
	 *
	 * @var string
	 */
	const PAGE_SLUG = 'tasty-roundups';

	/**
	 * Group used for configuration settings.
	 *
	 * @var string
	 */
	const SETTINGS_GROUP_CONFIG = 'tasty-roundups-settings-config';

	/**
	 * Name for the Tasty Pins settings.
	 *
	 * @var string
	 */
	const SETTINGS_OPTION = 'tasty_roundups_settings';

	/**
	 * URL for the EDD store.
	 *
	 * @var
	 */
	const STORE_URL = 'https://www.wptasty.com';

	/**
	 * Initialize the upgrader
	 */
	public static function action_admin_init() {
		if ( ! class_exists( EDDUpdater::class ) ) {
			require_once dirname( TASTY_ROUNDUPS_PLUGIN_FILE ) . '/inc/libs/tasty-framework/inc/Admin/License/EDDUpdater.php';
		}

		new EDDUpdater(
			self::STORE_URL,
			TASTY_ROUNDUPS_PLUGIN_FILE,
			array(
				'version'   => TASTY_ROUNDUPS_PLUGIN_VERSION,
				'license'   => get_option( self::LICENSE_KEY_OPTION ),
				'item_name' => self::ITEM_NAME,
				'author'    => self::ITEM_AUTHOR,
			)
		);
	}

	/**
	 * Enqueue scripts and styles in the admin.
	 */
	public static function action_admin_enqueue_scripts() {

		$screen = get_current_screen();

		if ( ! $screen || 'wp-tasty_page_tasty-roundups' !== $screen->id ) {
			return;
		}

		$assets_dir = Utils::plugin_assets_url();
		$asset_meta = tasty_get_asset_meta( TASTY_ROUNDUPS_PATH . 'assets/dist/settings.build.asset.php' );

		wp_enqueue_style( 'tasty-roundups-block' );

		wp_enqueue_style(
			'tasty-roundups-settings',
			$assets_dir . 'settings.css',
			array(),
			$asset_meta['version']
		);

		wp_enqueue_script(
			'tasty-roundups-settings',
			$assets_dir . 'settings.build.js',
			$asset_meta['dependencies'],
			$asset_meta['version'],
			true
		);
		wp_localize_script(
			'tasty-roundups-settings',
			'tastyRoundupsSettings',
			array(
				'pluginUrl'      => Utils::plugin_url(),
				'customizations' => Block_Editor::get_customization_settings(),
			)
		);
	}

	/**
	 * Includes PHP and plugin versions in the user agent for update checks.
	 *
	 * @param array  $r   An array of HTTP request arguments.
	 * @param string $url The request URL.
	 * @return array
	 */
	public static function filter_http_request_args( $r, $url ) {
		if ( self::STORE_URL !== $url
			|| 'POST' !== $r['method']
			|| empty( $r['body'] )
			|| ! is_array( $r['body'] )
			|| empty( $r['body']['item_name'] )
			|| self::ITEM_NAME !== $r['body']['item_name'] ) {
			return $r;
		}

		$r['user-agent'] = rtrim( $r['user-agent'], ';' )
			. '; PHP/' . PHP_VERSION . '; '
			. self::ITEM_NAME . '/' . TASTY_ROUNDUPS_PLUGIN_VERSION;
		return $r;
	}

	/**
	 * Register admin menu UX.
	 */
	public static function action_admin_menu() {
		register_setting( 'tasty-roundups-settings', self::LICENSE_KEY_OPTION );
		$option_name = self::SETTINGS_OPTION;
		register_setting(
			self::SETTINGS_GROUP_CONFIG,
			$option_name,
			array(
				'sanitize_callback' => function ( $val ) use ( $option_name ) {
					$existing = get_option( $option_name );
					$retval   = array();
					foreach (
						array(
							'media_position'          => 'sanitize_title',
							'numbers'                 => 'sanitize_title',
							'heading_color'           => array( __CLASS__, 'sanitize_color' ),
							'text_color'              => array( __CLASS__, 'sanitize_color' ),
							'number_text_color'       => array( __CLASS__, 'sanitize_color' ),
							'number_background_color' => array( __CLASS__, 'sanitize_color' ),
							'number_border_color'     => array( __CLASS__, 'sanitize_color' ),
							'number_border_width'     => 'absint',
							'button_text_color'       => array( __CLASS__, 'sanitize_color' ),
							'button_background_color' => array( __CLASS__, 'sanitize_color' ),
							'button_border_radius'    => 'absint',
							'button_text'             => 'sanitize_text_field',
							'block_background_color'  => array( __CLASS__, 'sanitize_color' ),
							'block_border_color'      => array( __CLASS__, 'sanitize_color' ),
							'block_border_width'      => 'absint',
							'block_border_radius'     => 'absint',
							'shareasale_affiliate_id' => 'sanitize_title',
						)
						as $key_name => $sanitize_callback ) {
						if ( isset( $val[ $key_name ] ) ) {
							$allow_empty = array(
								'button_border_radius',
								'block_border_width',
								'block_border_radius',
								'number_border_width',
							);
							if ( '' === $val[ $key_name ]
								&& in_array( $key_name, $allow_empty, true ) ) {
								$retval[ $key_name ] = '';
							} else {
								$retval[ $key_name ] = $sanitize_callback( $val[ $key_name ] );
							}
						} elseif ( isset( $existing[ $key_name ] ) ) {
							$retval[ $key_name ] = $existing[ $key_name ];
						}
					}
					return $retval;
				},
			)
		);
	}

	/**
	 * Display an admin notice when the license key is incorrect.
	 *
	 * @deprecated 1.1
	 */
	public static function action_admin_notices_license_key() {
		_deprecated_function( __METHOD__, '1.1' );
	}

	/**
	 * Activate the license when the option is updated.
	 *
	 * @deprecated 1.1
	 */
	public static function action_update_option_register_license() {
		_deprecated_function( __METHOD__, '1.1' );
	}

	/**
	 * Clear license key cache when the option is updated.
	 */
	public static function action_update_option_clear_transient() {
		delete_transient( self::LICENSE_CHECK_CACHE_KEY );
		$cache_key = md5( 'edd_plugin_' . sanitize_key( plugin_basename( TASTY_ROUNDUPS_PLUGIN_FILE ) ) . '_version_info' );
		delete_site_transient( $cache_key );

		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
		$cache_key = 'edd_api_request_' . substr( md5( serialize( basename( TASTY_ROUNDUPS_PLUGIN_FILE, '.php' ) ) ), 0, 15 );
		delete_site_transient( $cache_key );
		delete_site_transient( 'update_plugins' );
	}

	/**
	 * Include the 'Settings' and 'Remove license' links in plugin actions
	 *
	 * @param array $links Existing plugin actions.
	 * @return array
	 */
	public static function filter_plugin_action_links( $links ) {
		$links['tro_license_manager'] = '<a href="' . esc_url( Url::get_main_admin_url() ) . '">' . esc_html__( 'License manager', 'tasty-links' ) . '</a>';
		return $links;
	}

	/**
	 * Handle AJAX request to remove the license key.
	 *
	 * @deprecated 1.1
	 */
	public static function handle_wp_ajax_remove_license_key() {
		_deprecated_function( __METHOD__, '1.1' );
	}

	/**
	 * Renders in the admin header.
	 *
	 * @deprecated 1.1
	 */
	public static function action_in_admin_header() {
		_deprecated_function( __METHOD__, '1.1' );
	}

	/**
	 * Update the admin dashboard title.
	 *
	 * @since 2.1
	 *
	 * @param string $title Title.
	 *
	 * @return string
	 */
	public static function update_admin_dashboard_title( $title ) {
		if ( 'Tasty Roundups' === $title ) {
			$title = 'Roundups';
		}

		return $title;
	}

	/**
	 * Render the settings page.
	 */
	public static function handle_settings_page() {
		$active_tab = Vars::get_param( 'tab', 'sanitize_text_field', 'settings' );
		$base_url   = menu_page_url( self::PAGE_SLUG, false );

		$add_link = array(
			'settings' => __( 'Settings', 'tasty-roundups' ),
		);

		$tabs = array();
		foreach ( $add_link as $key => $title ) {
			$tabs[] = array(
				'title'  => $title,
				'url'    => add_query_arg( array( 'tab' => $key ), $base_url ),
				'active' => $key === $active_tab,
			);
		}

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo tasty_roundups_get_template_part( 'settings', compact( 'tabs', 'active_tab' ) );
	}

	/**
	 * Sanitizes a color field.
	 *
	 * @param string $color Existing color value.
	 * @return string
	 */
	private static function sanitize_color( $color ) {
		if ( empty( $color ) || is_array( $color ) ) {
			return '';
		}

		if ( false === strpos( $color, 'rgba' ) ) {
			return sanitize_hex_color( $color );
		}

		$color = str_replace( ' ', '', $color );
		sscanf( $color, 'rgba(%d,%d,%d,%f)', $red, $green, $blue, $alpha );
		return 'rgba(' . $red . ',' . $green . ',' . $blue . ',' . $alpha . ')';
	}

	/**
	 * Add the callback for the plugin menu item.
	 *
	 * @param array $menu_items Admin menu items.
	 *
	 * @return array
	 */
	public static function add_menu_item( $menu_items ) {
		if ( empty( $menu_items['tasty-roundups'] ) ) {
			return $menu_items;
		}

		$menu_items['tasty-roundups']['callback'] = array( __CLASS__, 'handle_settings_page' );

		return $menu_items;
	}
}
