<?php
/**
 * TOC options functions.
 *
 * @package AnchorKit_TOC
 */

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

if ( ! function_exists( 'anchorkit_normalize_heading_levels' ) ) {
	/**
	 * Normalize an array/string of heading levels to lowercase h1-h6 values.
	 *
	 * @param mixed $levels   The heading levels to normalize.
	 * @param array $fallback The fallback values if normalization fails.
	 * @return array
	 */
	function anchorkit_normalize_heading_levels( $levels, $fallback = array( 'h2', 'h3', 'h4' ) ) {
		if ( is_string( $levels ) ) {
			$levels = false !== strpos( $levels, ',' ) ? explode( ',', $levels ) : array( $levels );
		}

		if ( ! is_array( $levels ) ) {
			return $fallback;
		}

		$normalized = array();
		foreach ( $levels as $level ) {
			if ( null === $level || '' === $level ) {
				continue;
			}
			$candidate = strtolower( trim( (string) $level ) );
			if ( '' === $candidate ) {
				continue;
			}
			if ( is_numeric( $candidate ) ) {
				$candidate = 'h' . $candidate;
			}
			if ( 'h' !== $candidate[0] ) {
				$candidate = 'h' . ltrim( $candidate, 'h' );
			}
			if ( preg_match( '/^h[1-6]$/', $candidate ) ) {
				$normalized[ $candidate ] = true;
			}
		}

		if ( empty( $normalized ) ) {
			return $fallback;
		}

		return array_keys( $normalized );
	}
}

if ( ! function_exists( 'anchorkit_get_global_heading_levels' ) ) {
	/**
	 * Retrieve heading level settings from options and normalize them.
	 *
	 * @return array
	 */
	function anchorkit_get_global_heading_levels() {
		$levels = anchorkit_get_option( 'anchorkit_toc_include_headings', array( 'h2', 'h3', 'h4' ) );
		return anchorkit_normalize_heading_levels( $levels, array( 'h2', 'h3', 'h4' ) );
	}
}

if ( ! function_exists( 'anchorkit_get_sanitized_color_option' ) ) {
	/**
	 * Retrieve and sanitize a color option, ensuring a valid hex value is always returned.
	 * If the stored value is invalid, it will be reset to the provided default.
	 *
	 * @param string $option_name Option key to retrieve.
	 * @param string $default     Fallback hex color (#rrggbb).
	 *
	 * @return string Sanitized hex color.
	 */
	function anchorkit_get_sanitized_color_option( $option_name, $default ) {
		$raw_value = get_option( $option_name, null );

		if ( null === $raw_value || '' === $raw_value ) {
			update_option( $option_name, $default );
			return $default;
		}

		$sanitized = sanitize_hex_color( $raw_value );

		if ( null === $sanitized ) {
			// Attempt to normalize shorthand without leading '#'.
			if ( is_string( $raw_value ) && preg_match( '/^[0-9a-fA-F]{6}$/', $raw_value ) ) {
				$sanitized = '#' . strtolower( $raw_value );
			} else {
				$sanitized = $default;
			}

			update_option( $option_name, $sanitized );
		}

		return $sanitized;
	}
}
