<?php
/**
 * Paws and Care Dynamic CSS Variables
 *
 * Generates dynamic RGBA CSS variables based on the theme color.
 *
 * @package Paws_And_Care
 * @since 0.1.2
 */

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

/**
 * Output dynamic CSS variables in the head.
 */
function paws_and_care_dynamic_css_variables() {
    $theme_color = get_theme_mod('paws_and_care_theme_color', '#ff8c42');

    // Convert Hex to RGB
    // Remove # if present
    $hex = str_replace('#', '', $theme_color);

    if (strlen($hex) == 3) {
        $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
        $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
        $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
    } else {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    }

    $opacities = array(
        '80' => 0.8,
        '40' => 0.4,
        '30' => 0.3,
        '25' => 0.25,
        '20' => 0.2,
        '15' => 0.15,
        '10' => 0.1,
        '08' => 0.08,
        '06' => 0.06,
        '05' => 0.05,
        '03' => 0.03,
    );

    $css = ":root {" . PHP_EOL;
    $css .= "    --primary-rgb: {$r}, {$g}, {$b};" . PHP_EOL;
    foreach ($opacities as $key => $opacity) {
        $css .= "    --primary-rgba-{$key}: rgba({$r}, {$g}, {$b}, {$opacity});" . PHP_EOL;
    }
    $css .= "}";

    wp_add_inline_style('paws-and-care-style', $css);
}
add_action('wp_enqueue_scripts', 'paws_and_care_dynamic_css_variables', 20);

/**
 * Output dynamic CSS variables in the Block Editor.
 */
function paws_and_care_editor_dynamic_css_variables() {
    $theme_color = get_theme_mod('paws_and_care_theme_color', '#ff8c42');
    $hex = str_replace('#', '', $theme_color);

    if (strlen($hex) == 3) {
        $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
        $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
        $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
    } else {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    }

    $opacities = array(
        '80' => 0.8,
        '40' => 0.4,
        '30' => 0.3,
        '25' => 0.25,
        '20' => 0.2,
        '15' => 0.15,
        '10' => 0.1,
        '08' => 0.08,
        '06' => 0.06,
        '05' => 0.05,
        '03' => 0.03,
    );

    $css = ":root {" . PHP_EOL;
    $css .= "    --primary-color: {$theme_color};" . PHP_EOL;
    $css .= "    --primary-rgb: {$r}, {$g}, {$b};" . PHP_EOL;
    foreach ($opacities as $key => $opacity) {
        $css .= "    --primary-rgba-{$key}: rgba({$r}, {$g}, {$b}, {$opacity});" . PHP_EOL;
    }
    $css .= "}";

    wp_add_inline_style('wp-block-library', $css);
}
add_action('enqueue_block_editor_assets', 'paws_and_care_editor_dynamic_css_variables');
