<?php

namespace EstatebudConnect\Core;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Configs\Icons;
use EstatebudConnect\Configs\App;
use EstatebudConnect\Services\Estatebud;
use EstatebudConnect\Models\Settings;
use EstatebudConnect\Core\Cache;
use EstatebudConnect\Utilities\Helper;
use EstatebudConnect\Utilities\Color;

class Strings
{
    private static $data = [];
    private static $config_initialized = false;
    private static $config_output = false;

    public static function init_defaults($handle = 'frontend')
    {
        if (self::$config_initialized) {
            if (!self::$config_output) {
                self::complete($handle);
                self::$config_output = true;
            }
            return;
        }

        $settings_data = Settings::instance()->get_data();
        $whois = Estatebud::instance()->cache(Cache::TTL_1H)->whois();

        $captcha_provider = $settings_data['captcha_provider'] ?? '';
        $captcha_site_key = $settings_data['captcha_site_key'] ?? '';
        $edge_style = $settings_data['edge_style'] ?? '';
        $field_style = $settings_data['field_style'] ?? '';
        $button_style = $settings_data['button_style'] ?? '';
        $branding_color = $settings_data['branding_color'] ?? '';
        $icon_style = $settings_data['icon_style'] ?? '';
        $icon_type = $settings_data['icon_type'] ?? '';
        $ip_lookup = $settings_data['ip_lookup'] ?? '';
        $country = $whois['country'] ?? '';

        $user_session = Helper::get_user_session();

        $currency = $user_session['currency'] ?? $whois['currency'];
        $currency_data = Helper::get_currency_data($whois['currency'], $currency);

        $color = new Color($branding_color);

        self::append('admin_url', admin_url('admin-ajax.php'));
        self::append('locale', Helper::get_locale());
        self::append('nonce', wp_create_nonce('estatebud-nonce'));
        self::append('country', $country);
        self::append('plugin_url', Helper::get_url(''));

        self::append('settings', [
            'captcha_provider' => $captcha_provider,
            'captcha_site_key' => $captcha_site_key,
            'edge_style' => $edge_style,
            'field_style' => $field_style,
            'button_style' => $button_style,
            'branding_color' => $branding_color,
            'branding_color_hover' => '#' . $color->darken(),
            'ip_lookup' => $ip_lookup,
        ]);

        self::append('icons', [
            'plus' => wp_kses(Icons::get_svg_icon('plus', $icon_type, Icons::STYLE_REGULAR, 14, 14), Icons::get_kses_ruleset()),
            'minus' => wp_kses(Icons::get_svg_icon('minus', $icon_type, Icons::STYLE_REGULAR, 14, 14), Icons::get_kses_ruleset()),
            'check' => wp_kses(Icons::get_svg_icon('check', $icon_type, $icon_style, 14, 14), Icons::get_kses_ruleset()),
            'copy' => wp_kses(Icons::get_svg_icon('copy', $icon_type, Icons::STYLE_SOLID, 16, 19, '#6b6b6b'), Icons::get_kses_ruleset()),
            'map_marker' => wp_kses(Icons::get_svg_icon('map-marker', $icon_type, Icons::STYLE_SOLID, 36, 49.5), Icons::get_kses_ruleset()),
            'heart' => wp_kses(Icons::get_svg_icon('heart', $icon_type, Icons::STYLE_SOLID, 24, 24, '#F43F5E'), Icons::get_kses_ruleset()),
            'heart_crack' => wp_kses(Icons::get_svg_icon('heart-crack', $icon_type, Icons::STYLE_SOLID, 24, 24, '#F43F5E'), Icons::get_kses_ruleset()),
            'heart_outline' => wp_kses(Icons::get_svg_icon('heart', $icon_type, Icons::STYLE_REGULAR, 24, 24, '#FFFFFF'), Icons::get_kses_ruleset()),
            'play' => wp_kses(Icons::get_svg_icon('play', $icon_type, Icons::STYLE_SOLID, 24, 24, '#FFFFFF'), Icons::get_kses_ruleset()),
            'street_view' => wp_kses(Icons::get_svg_icon('street-view', $icon_type, Icons::STYLE_SOLID, 24, 24, '#FFFFFF'), Icons::get_kses_ruleset()),
            'angle_left' => wp_kses(Icons::get_svg_icon('angle-left', $icon_type, Icons::STYLE_SOLID, 19, 30, '#FFFFFF'), Icons::get_kses_ruleset()),
            'angle_right' => wp_kses(Icons::get_svg_icon('angle-right', $icon_type, Icons::STYLE_SOLID, 19, 30, '#FFFFFF'), Icons::get_kses_ruleset()),
        ]);

        self::append('currency', [
            'default' => $currency_data['base_currency'],
            'current' => $currency_data['exchange_rates'],
        ]);

        $area_options = Estatebud::instance()->cache(Cache::TTL_5M)->get_property_areas();
        
        self::append('areas', $area_options);
        self::$config_initialized = true;

        if (!self::$config_output) {
            self::complete($handle);
            self::$config_output = true;
        }
    }

    public static function append($key, $value, $shortcode_id = null)
    {
        $class_parts = explode('\\', debug_backtrace()[1]['class']);
        $class_name = end($class_parts);

        if ($shortcode_id) {
            self::$data[$class_name][$shortcode_id][$key] = self::merge_if_array(
                self::$data[$class_name][$shortcode_id][$key] ?? null,
                $value,
            );
        } else {
            self::$data[$class_name][$key] = self::merge_if_array(self::$data[$class_name][$key] ?? null, $value);
        }
    }

    public static function delete($key, $shortcode_id = null)
    {
        $class_parts = explode('\\', debug_backtrace()[1]['class']);
        $class_name = end($class_parts);

        if ($shortcode_id) {
            unset(self::$data[$class_name][$shortcode_id][$key]);
        } else {
            unset(self::$data[$class_name][$key]);
        }
    }

    public static function complete($handle, $shortcode_id = null)
    {
        $class_parts = explode('\\', debug_backtrace()[1]['class']);
        $class_name = end($class_parts);

        if ($shortcode_id) {
            self::inject_script($class_name, self::$data[$class_name][$shortcode_id] ?? [], $handle, $shortcode_id);
        } else {
            self::inject_script($class_name, self::$data[$class_name] ?? [], $handle);
        }
    }

    public static function destroy($class_name, $shortcode_id = null)
    {
        if ($shortcode_id) {
            unset(self::$data[$class_name][$shortcode_id]);
        } else {
            unset(self::$data[$class_name]);
        }
    }

    private static function merge_if_array($current, $new)
    {
        if (is_array($current) && is_array($new)) {
            return array_merge($current, $new);
        }
        return $new;
    }

    private static function inject_script($class_name, $data, $handle, $shortcode_id = null)
    {
        if (!empty($data)) {
            $class_name = str_replace('_', '', $class_name);

            if ($class_name == 'Strings') {
                $class_name = 'Config';
            }

            if ($class_name === 'Config' && !$shortcode_id && self::$config_output) {
                return;
            }

            $script = esc_js("window.Estatebud" . $class_name);

            if ($shortcode_id) {
                $script .= "_" . $shortcode_id;
            }

            $script .= " = ";
            $script .= wp_json_encode($data);
            $script .= ";";

            wp_add_inline_script(App::SLUG . '-' . $handle, $script, 'before');

            if ($shortcode_id) {
                self::destroy($class_name, $shortcode_id);
            } elseif ($class_name !== 'Config') {
                self::destroy($class_name);
            }
        }
    }
}
