<?php

defined('ABSPATH') or exit('Hey, what are you doing here? You silly human!');

if (! function_exists('dusky_get_settings')) {

    /**
     * Get setting database option
     *
     * @param string $key Option key name.
     * @param mixed  $default Default value to return.
     * @return mixed
     */
    function dusky_get_settings($key = '', $default = '')
    {
        $settings_name = 'dusky_settings';

        $settings = get_option($settings_name, []);

        if ($key === 'state') {
            return $settings;
        }

        if (! isset($settings["input"]) && ! isset($settings["checkbox"])) {
            return $default;
        }

        if (! is_array($settings["checkbox"]) && ! is_array($settings["input"])) {
            return $default;
        }

        $merge_settings = array_merge($settings["input"], $settings["checkbox"]);

        if (dusky_fs()->is_free_plan()) {

            switch ($merge_settings['toggleStyle']) {
                case '1':
                    $merge_settings['toggleStyle'] = '1';
                    break;
                case '2':
                    $merge_settings['toggleStyle'] = '2';
                    break;
                case '3':
                    $merge_settings['toggleStyle'] = '3';
                    break;
                default:
                    $merge_settings['toggleStyle'] = '1';
            }

            $merge_settings['ColorSepia'] = '10';
            $merge_settings['ColorGrayscale'] = '0';
            $merge_settings['ColorContrast'] = '90';
            $merge_settings['ColorBrightness'] = '100';
            $merge_settings['darkModeUserRoles'] = ['administrator'];
            $merge_settings['imgLowBrightnessInput'] = '90';
            $merge_settings['customBGColor'] = '#1B2430';
            $merge_settings['customTextColor'] = '#162447';
            $merge_settings['isDarkModeUserRoles'] = false;
            $merge_settings['urlParameter'] = false;
            $merge_settings['imgLowBrightness'] = false;
            $merge_settings['imgDarkenBG'] = false;
        }

        if (! $key) {
            return $merge_settings;
        }

        return $merge_settings[$key] ?? $default;
    }
}

if (! function_exists('dusky_get_admin_settings')) {
    function dusky_get_admin_settings($user_id = 0, $key = '', $default = '')
    {
        $settings_name = 'dusky_admin_settings';
        if (empty($user_id)) {
            $user_id = get_current_user_id();
        }
        $settings = get_user_meta($user_id, $settings_name, true);

        if (isset($settings['adminDarkMode'])) {
            $settings = $settings['adminDarkMode'];
        } else {
            return;
        }

        if (! $user_id) {
            return;
        }
        if (dusky_fs()->is_free_plan()) {
            switch ($settings['toggleStyle']) {
                case '1':
                    $settings['toggleStyle'] = '1';
                    break;
                case '2':
                    $settings['toggleStyle'] = '2';
                    break;
                case '3':
                    $settings['toggleStyle'] = '3';
                    break;
                default:
                    $settings['toggleStyle'] = '1';
            }
        }

        if (empty($key)) {
            return $settings;
        }

        if (isset($key) && isset($settings[$key])) {
            return $settings[$key];
        }

        return $default;
    }
}

if (! function_exists('dusky_get_user_roles')) {
    function dusky_get_user_roles()
    {
        $roles = wp_roles()->roles;
        $user_roles = [];

        if (isset($roles) && is_array($roles)) {
            foreach ($roles as $key => $value) {
                array_push($user_roles, [
                    'label' => $value['name'],
                    'value' => $key,
                ]);
            }
        }

        return $user_roles;
    }
}

if (! function_exists('dusky_get_active_role')) {
    function dusky_get_active_role()
    {
        $active_roles = (array) dusky_get_settings('darkModeUserRoles');

        $current_role = array_filter($active_roles, function ($item) {
            return current_user_can($item);
        });

        if (! empty($current_role) && is_array($current_role) && array_values($current_role)[0]) {
            return array_values($current_role)[0];
        }

        return false;
    }
}

if (! function_exists('dusky_get_user_ip')) {
    function dusky_get_user_ip()
    {
        $ip_keys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR',
        ];

        $ip = '';

        foreach ($ip_keys as $key) {
            if (! empty($_SERVER[$key])) {
                // HTTP_X_FORWARDED_FOR can return a comma-separated list of IPs. Take the first one.
                $ips = explode(',', sanitize_text_field(wp_unslash($_SERVER[$key])));
                foreach ($ips as $ip_address) {
                    $ip_address = sanitize_text_field(trim($ip_address));

                    if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        $ip = $ip_address;
                        break 2;
                    }
                }
            }
        }

        return apply_filters('dusky_get_user_ip', $ip);
    }

}

if (! function_exists('dusky_get_user_timezone')) {
    function dusky_get_user_timezone($ip = '')
    {
        if (empty($ip)) {
            $ip = dusky_get_user_ip();
        }
        $response = wp_remote_get("http://ip-api.com/json/{$ip}");

        if (is_array($response) && ! is_wp_error($response)) {
            $body = isset($response['body']) ? wp_json_decode($response['body'], true) : ['timezone' => 'Asia/Dhaka'];

            if (isset($body['timezone']) && ! empty($body['timezone'])) {
                return $body['timezone'];
            }
        }

        return 'Asia/Dhaka';
    }
}

if (! function_exists('dusky_get_mode')) {
    function dusky_get_mode()
    {
        if (dusky_get_settings('urlParameter', false)) {
            $dusky_mode = sanitize_text_field(wp_unslash(get_query_var('dusky-mode') ?? ''));
            if ($dusky_mode === 'dark') {
                return 'dark';
            } elseif ($dusky_mode === 'light') {
                return 'light';
            } elseif ($dusky_mode === 'auto') {
                return 'auto';
            }
        }

        $mode = 'light';

        if (current_user_can('manage_options') && $adminMode = dusky_get_admin_settings(false, 'adminMode', false)) {

            $mode = $adminMode;
        } else {
            $is_default_mode = dusky_get_settings('defaultDarkMode', false);
            $is_auto = dusky_get_settings('autoOsMatch', true);

            if ($is_default_mode) {
                $mode = 'dark';
            } elseif ($is_auto) {
                $mode = 'auto';
            }
        }

        $timeBasedDark = dusky_get_settings('timeBasedDark', false);
        if ($timeBasedDark) {

            $tz = dusky_get_user_timezone();
            $timestamp = time();
            $date = new DateTime("now", new DateTimeZone($tz));
            $date->setTimestamp($timestamp);
            $current_time = $date->format('Y-m-d G:i');
            $current_date = $date->format('Y-m-d');

            $now = strtotime($current_time);
            $startDarkTimer = strtotime($current_date . ' ' . dusky_get_settings('startDarkTimer'));
            $endDarkTimer = strtotime($current_date . ' ' . dusky_get_settings('endDarkTimer'));

            if ($endDarkTimer <= $startDarkTimer) {
                if ($now <= $endDarkTimer) {
                    $startDarkTimer = intval($startDarkTimer) - DAY_IN_SECONDS;
                } else {
                    $endDarkTimer = intval($endDarkTimer) + DAY_IN_SECONDS;
                }
            }

            $mode = ($startDarkTimer <= $now && $now <= $endDarkTimer) ? 'dark' : 'light';
        }

        if (isset($_COOKIE['dusky-front-mode'])) {
            $mode = sanitize_text_field(wp_unslash($_COOKIE['dusky-front-mode']));
        }

        return $mode;
    }
}

if (! function_exists('dusky_get_theme_settings')) {
    function dusky_get_theme_settings()
    {
        $settings = dusky_get_settings('state', []);

        $settings_input = isset($settings['input']) ? $settings['input'] : [];
        $settings_checkbox = isset($settings['checkbox']) ? $settings['checkbox'] : [];

        $settings_data = array_merge($settings_input, $settings_checkbox);

        $colorBrightness = isset($settings_data['ColorBrightness']) ? $settings_data['ColorBrightness'] : 100;
        $colorContrast = isset($settings_data['ColorContrast']) ? $settings_data['ColorContrast'] : 90;
        $colorGrayscale = isset($settings_data['ColorGrayscale']) ? $settings_data['ColorGrayscale'] : 0;
        $colorSepia = isset($settings_data['ColorSepia']) ? $settings_data['ColorSepia'] : 10;
        $presetTextColor = isset($settings_data['presetTextColor']) ? $settings_data['presetTextColor'] : '#ffffff';
        $presetBGColor = isset($settings_data['presetBGColor']) ? $settings_data['presetBGColor'] : '#000000';
        $colorMode = isset($settings_data['colorMode']) ? $settings_data['colorMode'] : 'auto';
        $customTextColor = isset($settings_data['customTextColor']) ? $settings_data['customTextColor'] : '#ffffff';
        $customBGColor = isset($settings_data['customBGColor']) ? $settings_data['customBGColor'] : '#000000';
        $changeFonts = isset($settings_data['changeFonts']) ? $settings_data['changeFonts'] : false;
        $textStroke = isset($settings_data['customTextStroke']) ? $settings_data['customTextStroke'] : 0;
        $fontFamily = isset($settings_data['fontFamily']) ? $settings_data['fontFamily'] : '';
        $isExcludeElements = isset($settings_data['isExcludeElements']) ? $settings_data['isExcludeElements'] : '';
        $imageReplacement = isset($settings_data['imageReplacement']) ? $settings_data['imageReplacement'] : '';

        $theme = [
            'mode'             => 1,
            'brightness'       => $colorBrightness,
            'contrast'         => $colorContrast,
            'grayscale'        => $colorGrayscale,
            'sepia'            => $colorSepia,
            'useFont'          => $changeFonts,
            'fontFamily'       => $fontFamily,
            'textStroke'       => $textStroke,
            'stylesheet'       => '',
            'selectionColor'   => 'auto',
            'lightColorScheme' => 'Default',
            'darkColorScheme'  => 'Default',
            'immediateModify'  => true,
            'excludes'         => ['.dusky-ignore'],
            'imageReplacement' => $imageReplacement,
        ];
        if ($colorMode === 'preset') {
            $theme['darkSchemeBackgroundColor'] = $presetBGColor;
            $theme['darkSchemeTextColor'] = $presetTextColor;
        } elseif ($colorMode === 'custom') {
            $theme['darkSchemeBackgroundColor'] = $customBGColor;
            $theme['darkSchemeTextColor'] = $customTextColor;
        }

        if ($isExcludeElements) {
            $excludeElements = isset($settings_data['excludeElements']) ? $settings_data['excludeElements'] : null;
            if (! empty($excludeElements)) {
                $theme['excludes'] = [ ...$theme['excludes'], ...$excludeElements];
                $theme['isExcludeElements'] = true;
            }
        }

        return $theme;
    }
}

if (! function_exists('dusky_get_current_user_id')) {
    function dusky_get_current_user_id()
    {
        if (! function_exists('wp_get_current_user')) {
            require_once ABSPATH . '/wp-includes/pluggable.php';
        }

        $user_id = get_current_user_id();

        if (empty($user_id)) {
            return false;
        }
        return $user_id;
    }
}

if (! function_exists('dusky_detect_devise')) {
    function dusky_detect_devise()
    {
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';

        if (preg_match('/iPad|Tablet|Nexus 7|Nexus 10|Kindle|PlayBook|SM-T|GT-P|SCH-I800|iPad;|iPad3|iPad4|iPad5|iPad6|iPad7|iPad8|iPad9|iPad10/i', $userAgent)) {
            return 'tablet';
        } elseif (preg_match('/Mobile|Android|iPhone|BlackBerry|Windows Phone/i', $userAgent)) {
            return 'mobile';
        } else {
            return 'desktop';
        }
    }
}

if (! function_exists('dusky_enable_devise')) {
    function dusky_enable_devise()
    {
        $activeDevicesDarkMode = dusky_get_settings('devicesDarkMode', ['desktop', 'tablet', 'mobile']);
        $currentDevise = dusky_detect_devise();

        if (! in_array($currentDevise, $activeDevicesDarkMode)) {
            return false;
        }

        return true;
    }
}
