<?php
namespace Advanced_Themer_Bricks;
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class AT__Global_Colors{

    public static function force_default_color_scheme(){
        global $brxc_acf_fields;

        if( !AT__Helpers::is_global_colors_category_activated() || !isset($brxc_acf_fields['force_default_color_scheme'])) return;

        wp_add_inline_script('brxc-darkmode-local-storage', "const BRXC_FORCE_DEFAULT_SCHEME_COLOR = '" . $brxc_acf_fields['force_default_color_scheme'] . "';", 'before');

    }

    private static function add_prefix($name, $is_framework, $palette_prefix){

        if(!$palette_prefix || str_starts_with($name, $palette_prefix) || $is_framework) return $name;

        return $palette_prefix . $name;
    }

    public static function is_framework($id){
        return str_starts_with($id, 'acss');
    }

    public static function get_color_name($color, $prefix = '') {
        if (!empty($color['name'])) return $color['name'];
        if (empty($color['raw'])) return '';
        $name = preg_replace('/^var\(--/', '', $color['raw']);
        $name = preg_replace('/\)$/', '', $name);
        if ($prefix && strpos($name, $prefix) === 0) {
            $name = substr($name, strlen($prefix));
        }
        return $name;
    }

    private static function append_hsl_vars($color_value, $css_var_name){
        $hsl = '';
        if (preg_match('/hsla\(([^,]+),([^,]+%),([^,]+%)/', $color_value, $matches)) {
            $hsl .= '--' . $css_var_name . '-h:' . esc_attr($matches[1]) . ';';
            $hsl .= '--' . $css_var_name . '-s:' . esc_attr($matches[2]) . ';';
            $hsl .= '--' . $css_var_name . '-l:' . esc_attr($matches[3]) . ';';
        }
        return $hsl;
    }

    public static function load_converted_colors_variables_on_frontend(){

        $palette_arr = get_option('bricks_color_palette', [] );

        if( !is_array($palette_arr) || empty($palette_arr) ) {
            return false;
        }

        $light = '';
        $dark = '';
        $property = '';

        foreach ($palette_arr as &$palette) {

            // Override palette settings
            $palette = apply_filters('at/color_palettes/override_palette_settings', $palette);

            if (isset($palette['status']) && $palette['status'] === 'disabled'){
                continue;
            }

            $palette_prefix = $palette['prefix'] ?? false;

            if (isset($palette['colors']) && $palette['colors'] && is_array($palette['colors'])) {
                foreach ($palette['colors'] as $color) {
                    if (!isset($color['id'])) continue;
                    $color_name = self::get_color_name($color, $palette_prefix);
                    if (empty($color_name)) continue;
                    $is_framework = self::is_framework($color['id']);
                    $name = preg_replace('/[^a-zA-Z0-9_-]+/', '-', strtolower(trim($color_name)));
                    $css_var_name = esc_attr(self::add_prefix($name, $is_framework, $palette_prefix));

                    if ( isset($color['raw'], $color['rawValue'], $color['rawValue']['light']) && !isset($color['isVariableOnly']) ) {

                        // @property
                        if (isset($color['colorProperty']) && $color['colorProperty'] === true) {
                            $property .= wp_specialchars_decode("@property --" . $css_var_name . "{syntax: '&lt;color&gt;';initial-value: " . esc_attr($color['rawValue']['light']) . ";inherits: true;}");
                        }

                        // Root Color
                        $light .= '--' . $css_var_name . ':' . esc_attr($color['rawValue']['light']) . ';';
                        // HSL Values
                        if (isset($color['shadeChildren'])) {
                            $light .= self::append_hsl_vars($color['rawValue']['light'], $css_var_name);
                        }

                    }
                    if ( isset($color['raw'], $color['rawValue'], $color['rawValue']['dark']) ) {
                        $dark .= '--' . $css_var_name . ':' . esc_attr($color['rawValue']['dark']) . ';';

                        // HSL Values
                        if (isset($color['shadeChildren'])) {
                            $dark .= self::append_hsl_vars($color['rawValue']['dark'], $css_var_name);
                        }

                    }
                }
            }
        }

        return [$light, $dark, $property];
    }

    public static function theme_support_load_gutenberg_colors() {

        global $brxc_acf_fields;

        if ( !AT__Helpers::is_value($brxc_acf_fields, 'replace_gutenberg_palettes') ){
            return;
        }

        $palette_arr = get_option('bricks_color_palette', [] );

        if( !AT__Helpers::is_array($palette_arr) ) {
            return;
        }

        $gutenberg_colors = [];

        foreach ($palette_arr as $palette) {

            // Override palette settings
            $palette = apply_filters('at/color_palettes/override_palette_settings', $palette);

            if (isset($palette['status']) && $palette['status'] === 'disabled'){
                continue;
            }

            $palette_prefix = $palette['prefix'] ?? false;

            if (AT__Helpers::is_array($palette, 'colors')) {
                foreach ($palette['colors'] as $color) {
                    if (!isset($color['id'])) continue;
                    $color_name = self::get_color_name($color, $palette_prefix);
                    if (empty($color_name)) continue;
                    $final_color = '';
                    $is_framework = self::is_framework($color['id']);
                    $name = preg_replace('/[^a-zA-Z0-9_-]+/', '-', strtolower(trim($color_name)));

                    foreach(['hex', 'rgb','hsl','raw'] as $format){
                        if( isset($color[$format] )){
                            $final_color = $color[$format];
                        }
                    }
                    if (isset($color['rawValue'], $color['rawValue']['light']) ){
                        $final_color = 'var(--' . esc_attr(self::add_prefix($name, $is_framework, $palette_prefix)) . ')';
                    }
                    $gutenberg_colors[] = [
                        'name' => self::add_prefix($name, $is_framework, $palette_prefix),
                        'slug' => $name,
                        'color' => $final_color,
                    ];
                }
            }
        }

        add_theme_support('editor-color-palette', $gutenberg_colors);

    }
}
