<?php

namespace EasyCriticalCSS;

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

class Timed_Option {
	const TIMED_OPTION_PREFIX = 'easy_cc_timed_';

	const DEFAULT_DURATION = 5 * MINUTE_IN_SECONDS;

	private static function generate_new_timestamp( $time_to_add_in_seconds ) {
		$sanitized_time = absint( $time_to_add_in_seconds );

		return time() + $sanitized_time;
	}

	public static function set( $timed_option_name, $value, $duration_in_seconds = self::DEFAULT_DURATION ) {
		// Basic sanity check on the name.
		if ( ! is_string( $timed_option_name ) || $timed_option_name === '' ) {
			return false;
		}

		$timestamp = self::generate_new_timestamp( $duration_in_seconds );
		$new_value = [
			'value'     => $value,
			'timestamp' => $timestamp,
		];

		return update_option( self::TIMED_OPTION_PREFIX . $timed_option_name, $new_value, true );
	}

	public static function delete( $timed_option_name ) {
		return delete_option( self::TIMED_OPTION_PREFIX . $timed_option_name );
	}

	public static function get( $timed_option_name ) {
		$timed_option = get_option( self::TIMED_OPTION_PREFIX . $timed_option_name );

		// Option doesn't exist.
		if ( $timed_option === false ) {
			return false;
		}

		// Option corrupted.
		if ( ! is_array( $timed_option ) ) {
			self::delete( $timed_option_name );

			return false;
		}

		// Option value missing.
		if ( ! isset( $timed_option['value'] ) ) {
			self::delete( $timed_option_name );

			return false;
		}

		// Option timestamp missing.
		if ( ! isset( $timed_option['timestamp'] ) ) {
			self::delete( $timed_option_name );

			return false;
		}

		// Option is expired.
		if ( time() > (int) $timed_option['timestamp'] ) {
			self::delete( $timed_option_name );

			return false;
		}

		return $timed_option['value'];
	}

	public static function delete_all() {
		$timed_options = [
			'auto_mode_status',
			'is_local_site',
			'is_rest_api_reachable',
			'receive_test_nonce',
		];
		foreach ( $timed_options as $option ) {
			self::delete( $option );
		}
	}
}
