<?php
/**
 * LicenseOption.php.
 *
 * @package RewardsWP
 */

namespace Awesomemotive\Rewardswp\Settings\Options\General;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Abstracts\AbstractOption;
use Awesomemotive\Rewardswp\Interfaces\OptionInterface;
use Awesomemotive\Rewardswp\Services\LicenseManagerService;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_plan_tier_by_price_id;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_plan_tier_names;

/**
 * Class LicenseOption.
 */
class LicenseOption extends AbstractOption implements OptionInterface {
	/**
	 * Get the setting key used in the option array.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'license';
	}

	/**
	 * Get the setting group.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_group(): string {
		return 'general';
	}

	/**
	 * Get the default value for the setting.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	public function get_default_value(): array {
		return [
			'key'       => '',
			'status'    => '',
			'expires'   => 0,
			'price_id'  => 0,
			'plan_name' => 'Lite',
		];
	}

	/**
	 * Get the label for the setting.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_label(): string {
		return esc_html__( 'License Key', 'rewardswp' );
	}

	/**
	 * Get the type of the setting (text, textarea, select, etc).
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_type(): string {
		return 'license_ui';
	}

	/**
	 * Ensure an int is returned when sanitizing.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $value The value to be sanitized.
	 *
	 * @return array
	 */
	public function sanitize( $value ): array {
		$defaults = $this->get_default_value();

		$price_id  = absint( $value['price_id'] ?? $defaults['price_id'] );
		$plan_tier = get_rewardswp_plan_tier_by_price_id( $price_id );

		return [
			'key'       => sanitize_text_field( $value['key'] ?? $defaults['key'] ),
			'status'    => sanitize_text_field( $value['status'] ?? $defaults['status'] ),
			'expires'   => absint( $value['expires'] ?? $defaults['expires'] ),
			'price_id'  => $price_id,
			'plan_name' => sanitize_text_field( get_rewardswp_plan_tier_names()[ $plan_tier ] ?? $defaults['plan_name'] ),
		];
	}
}
