<?php

/**
 * Helper functions
 *
 * @package Kubelio\Core
 * @since 1.0.0
 */

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

/**
 * Get theme data
 *
 * @param string $value
 * @return mixed
 */
function kubelio_get_theme($value = '') {
	$cache_key = 'kubelio_theme_data';
	$default   = wp_cache_get($cache_key, 'themes');

	if (false === $default) {
		$theme_colors    = array();
		$custom_settings = array();

		$merge_color_palettes = function ($parent_colors, $child_colors) {
			$merged     = array();
			$all_colors = array_merge($parent_colors, $child_colors);

			foreach ($all_colors as $color) {
				if (isset($color['slug']) && isset($color['color'])) {
					$merged[$color['slug']] = $color['color'];
				}
			}

			return $merged;
		};

		$parent_json_file = get_template_directory() . '/theme.json';
		$parent_colors    = array();
		$parent_custom    = array();

		if (file_exists($parent_json_file)) {
			$parent_data   = wp_json_file_decode($parent_json_file, array('associative' => true));
			$parent_colors = $parent_data['settings']['color']['palette'] ?? array();
			$parent_custom = $parent_data['settings']['custom'] ?? array();
		}

		$child_colors = array();
		$child_custom = array();

		if (get_template_directory() !== get_stylesheet_directory()) {
			$child_json_file = get_stylesheet_directory() . '/theme.json';

			if (file_exists($child_json_file)) {
				$child_data   = wp_json_file_decode($child_json_file, array('associative' => true));
				$child_colors = $child_data['settings']['color']['palette'] ?? array();
				$child_custom = $child_data['settings']['custom'] ?? array();
			}
		}

		$theme_colors    = $merge_color_palettes($parent_colors, $child_colors);
		$custom_settings = array_replace_recursive($parent_custom, $child_custom);

		$default = array(
			'product-name'    => defined('KUBELIO_THEME_NAME') ? KUBELIO_THEME_NAME : 'Kubelio',
			'product-slug'    => defined('KUBELIO_THEME_SLUG') ? KUBELIO_THEME_SLUG : 'kubelio',
			'product-version' => defined('KUBELIO_THEME_VERSION') ? KUBELIO_THEME_VERSION : '1.0.0',
			'product-docs'    => defined('KUBELIO_THEME_DOC') ? KUBELIO_THEME_DOC : 'https://docs.kubelio.com',
			'product-url'     => defined('KUBELIO_THEME_URL') ? KUBELIO_THEME_URL : '',
			'extends'         => array(),
			'typography'      => array(
				'heading' => array(
					'font-family' => 'Inter',
					'variant'     => '600',
				),
				'body'    => array(
					'font-family' => 'Inter',
					'variant'     => 'regular',
				),
				'menu'    => array(
					'font-family' => 'Inter',
					'variant'     => '600',
				),
			),
			'button'          => array(
				'primary' => array(
					'color'      => $custom_settings['button']['color'] ?? '',
					'background' => $custom_settings['button']['background'] ?? '',
				),
				'action'  => array(
					'color'      => $custom_settings['button-action']['color'] ?? '',
					'background' => $custom_settings['button-action']['background'] ?? '',
				),
			),
			'color'           => array_merge($theme_colors, ($custom_settings['color'] ?? array())),
		);

		// Store in cache for 1 hour
		wp_cache_set($cache_key, $default, 'themes', HOUR_IN_SECONDS);
	}

	if (empty($value)) {
		return $default;
	}

	return ! empty($default[$value]) ? $default[$value] : '';
}

/**
 * Get the customizer color settings that make up the color-picker swatches.
 *
 * Maps a theme.json color slug to its Customizer setting id. Shared by the
 * PHP field registration (initial swatch values) and the Customizer control
 * JS (keeps swatches live-synced when the user edits these settings).
 *
 * @return array<string,string> Slug => Customizer setting id.
 */
function kubelio_get_palette_settings() {
	return array(
		'primary'   => 'color_primary',
		'heading'   => 'color_heading',
		'body'      => 'color_body',
		'meta'      => 'color_meta',
		'text-link' => 'color_link',
		'surface'   => 'color_surface',
		'outline'   => 'color_border',
		'highlight' => 'color_hightlight',
	);
}

/**
 * Generate a tinted (lighter) or shaded (darker) hex color.
 *
 * Mimics CSS `color-mix(in srgb, $hex $percent%, white|black)` but
 * resolves to a static hex value so it works anywhere theme.json needs
 * a real color (eg. the block editor's color palette swatches).
 *
 * @param string $hex     Base color, eg. `#0f766e`.
 * @param int    $percent Percentage of the base color to keep (0-100).
 * @param string $mode    'light' mixes toward white, 'dark' mixes toward black.
 * @return string Resulting hex color, eg. `#3d8f89`.
 */
function kubelio_generate_hex_color($hex, $percent, $mode = 'light') {
	$hex = ltrim(trim((string) $hex), '#');

	if (3 === strlen($hex)) {
		$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
	}

	if (6 !== strlen($hex) || ! ctype_xdigit($hex)) {
		return '#ffffff';
	}

	$percent = max(0, min(100, (float) $percent)) / 100;
	$target  = 'dark' === $mode ? 0 : 255;

	$r = round(hexdec(substr($hex, 0, 2)) * $percent + $target * (1 - $percent));
	$g = round(hexdec(substr($hex, 2, 2)) * $percent + $target * (1 - $percent));
	$b = round(hexdec(substr($hex, 4, 2)) * $percent + $target * (1 - $percent));

	return sprintf('#%02x%02x%02x', $r, $g, $b);
}

