<?php

declare( strict_types=1 );

namespace DocketConnector\Common\Settings;

use DocketConnector\Common\Utilities\Strings;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Abort if this file is called directly.
}

if ( ! class_exists( Choices::class ) ) {
	/**
	 * Everything related to setting, getting, and sanitizing plugin settings/options.
	 */
	class Choices {

		/**
		 * @var string The slug/key used for the API key value.
		 */
		public $slug_api_key = 'api_key';

		/**
		 * Sanitize a Docket API Key (just trims and passes to format checker function).
		 *
		 * @param string $value
		 * @param string $default
		 *
		 * @return string
		 */
		public function sanitize_docket_api_key(
			string $value,
			string $default = ''
		): string {
			$value = trim( $value );

			if ( ! $this->is_valid_format_docket_api_key( $value ) ) {
				return $default;
			}

			return $value;
		}

		/**
		 * Determine if a string matches the Docket API Key format (10-50 alpha-numeric characters).
		 *
		 * Trim before checking!
		 *
		 * @param string $value
		 *
		 * @return bool
		 */
		public function is_valid_format_docket_api_key( string $value ): bool {
			// Was some sort of major copy-pasta blunder, since the string is not alpha-numeric.
			if (
				empty( $value )
				|| ! ctype_alnum( $value )
			) {
				return false;
			}

			$length = ( new Strings() )->stringy( $value )->count();

			// Bad length.
			if (
				10 > $length
				|| 50 < $length
			) {
				return false;
			}

			return true;
		}

	}
}
