<?php
namespace AIOSEO\Plugin\Common\Utils;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use AIOSEO\Plugin\Common\Traits;

/**
 * Class that holds all internal options for AIOSEO.
 *
 * @since 4.0.0
 */
class InternalOptions {
	use Traits\Options;

	/**
	 * Holds a list of all the possible deprecated options.
	 *
	 * @since 4.0.0
	 *
	 * @var array
	 */
	protected $allDeprecatedOptions = [
		'enableSchemaMarkup',
		'excludePosts',
		'excludeTerms',
		'autogenerateDescriptions',
		'descriptionFormat',
		'badBotBlocker',
		'runShortcodesInDescription',
		'staticSitemap',
		'staticVideoSitemap',
		'useContentForAutogeneratedDescriptions',
		'googleAnalytics'
	];

	/**
	 * All the default options.
	 *
	 * @since 4.0.0
	 *
	 * @var array
	 */
	protected $defaults = [
		// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
		'internal'     => [
			'validLicenseKey'   => [ 'type' => 'string' ],
			'lastActiveVersion' => [ 'type' => 'string', 'default' => '0.0' ],
			'migratedVersion'   => [ 'type' => 'string' ],
			'siteAnalysis'      => [
				'connectToken' => [ 'type' => 'string' ],
				'score'        => [ 'type' => 'number', 'default' => 0 ],
				'results'      => [ 'type' => 'string' ],
				'competitors'  => [ 'type' => 'array', 'default' => [], 'preserveHtml' => true ]
			],
			'wizard'            => [ 'type' => 'string' ],
			'category'          => [ 'type' => 'string' ],
			'categoryOther'     => [ 'type' => 'string' ],
			'deprecatedOptions' => [ 'type' => 'array', 'default' => [] ]
		],
		'integrations' => [
			'semrush' => [
				'accessToken'  => [ 'type' => 'string' ],
				'tokenType'    => [ 'type' => 'string' ],
				'expires'      => [ 'type' => 'string' ],
				'refreshToken' => [ 'type' => 'string' ]
			]
		]
		// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
	];

	/**
	 * The Construct method.
	 *
	 * @since 4.0.0
	 *
	 * @param string $optionsName An array of options.
	 */
	public function __construct( $optionsName = 'aioseo_options_internal' ) {
		$this->optionsName = is_network_admin() ? $optionsName . '_network' : $optionsName;

		$this->init();
	}

	/**
	 * Initializes the options.
	 *
	 * @since 4.0.0
	 *
	 * @return void
	 */
	protected function init() {
		// Options from the DB.
		$dbOptions = json_decode( get_option( $this->optionsName ), true );
		if ( empty( $dbOptions ) ) {
			$dbOptions = [];
		}

		// Refactor options.
		$this->defaultsMerged = array_replace_recursive( $this->defaults, $this->defaultsMerged );

		$options = array_replace_recursive(
			$this->defaultsMerged,
			$this->addValueToValuesArray( $this->defaultsMerged, $dbOptions )
		);

		$this->options = apply_filters( 'aioseo_get_options_internal', $options );

		// Get the localized options.
		$dbOptionsLocalized = get_option( $this->optionsName . '_localized' );
		if ( empty( $dbOptionsLocalized ) ) {
			$dbOptionsLocalized = [];
		}
		$this->localized = $dbOptionsLocalized;
	}

	/**
	 * Get all the deprecated options.
	 *
	 * @since 4.0.0
	 *
	 * @return void
	 */
	public function getAllDeprecatedOptions() {
		return $this->allDeprecatedOptions;
	}

	/**
	 * Sanitizes, then saves the options to the database.
	 *
	 * @since 4.0.0
	 *
	 * @param  array $options An array of options to sanitize, then save.
	 * @return void
	 */
	public function sanitizeAndSave( $options ) {
		if ( ! is_array( $options ) ) {
			return;
		}

		// Refactor options.
		$this->options = array_replace_recursive(
			$this->options,
			$this->addValueToValuesArray( $this->options, $options, [], true )
		);

		$this->options['internal']['siteAnalysis']['competitors']['value'] = $this->sanitizeField( $options['internal']['siteAnalysis']['competitors'], 'array', true );

		// Update localized options.
		update_option( $this->optionsName . '_localized', $this->localized );

		// Update values.
		$this->update();
	}
}