<?php

/*---------------------------------
Return theme option
------------------------------------*/
if (!function_exists("rad_get_option")) {
    function rad_get_option($key)
    {
        $options = get_option(RAD_OPTIONS_KEY);
        if (!isset($options[$key])) {
            return "";
        }

        $value = $options[$key];
        $value = apply_filters("rad_get_option_filter", $value, $key);

        return stripslashes($value);
    }
}

if (!function_exists("rad_e_option")) {
    function rad_e_option($option)
    {
        echo rad_get_option($option);
    }
}

/*---------------------------------
Check whether default values of shortcode changed or not
------------------------------------*/
if (!function_exists("rad_get_logo")) {
    function rad_get_logo(&$main_logo, &$second_logo)
    {

        if (function_exists("the_custom_logo")) {
            // WP version > 4.5 : use WP customizer
            $custom_logo_id = get_theme_mod("custom_logo");
            $main_logo      = wp_get_attachment_image_url($custom_logo_id, "full");
            $second_logo    = get_theme_mod("rad_second_logo");
        } else // A fallback for WP version < 4.5 : use Aventa settings
        {
            $main_logo   = rad_get_image_url(rad_get_option("main-logo-img"), "full");
            $second_logo = rad_get_image_url(rad_get_option("second-logo-img"), "full");
        }

        if ($main_logo == "") {
            $main_logo = RAD_THEME_ASSETS_URI . "/img/main-logo.png";
        }

        if ($second_logo == "") {
            $second_logo = RAD_THEME_ASSETS_URI . "/img/second-logo.png";
        }
    }
}


/*---------------------------------
Check whether default values of shortcode changed or not
------------------------------------*/
if (!function_exists("rad_has_custom_style")) {
    function rad_has_custom_style($defaults, $atts)
    {
        foreach ($defaults as $key => $value) {
            if (isset($atts[$key]) && $value != $atts[$key]) {
                return true;
            }

        }

        return false;
    }
}

/*---------------------------------
Get custom styles
------------------------------------*/
if (!function_exists("rad_get_styles")) {
    function rad_get_styles($font, $color, $size, $background_color = "")
    {
        $style = "";

        if ($font != "") {
            $style .= rad_get_font_options($font, "name");
            $style .= rad_get_font_options($font, "weight");
        }

        if ($size != "") {
            $style .= "font-size:" . str_replace("px", "", $size) . "px;";
        }

        if ($color != "") {
            $style .= "color:" . $color . ";";
        }

        if ($background_color != "") {
            $style .= "background-color:" . $background_color . ";";
        }

        return $style;
    }
}

/*---------------------------------
Check whether default values of shortcode changed or not
------------------------------------*/
if (!function_exists("rad_make_vc_url")) {
    function rad_make_vc_url($url, $title = "", $class = "", $style = "")
    {
        $output     = "";
        $class_attr = ($class != "") ? " class=\"" . $class . "\"" : "";
        $style_attr = ($style != "") ? " style=\"" . $style . "\"" : "";

        if ($url != "" && function_exists("vc_build_link")) {
            $link = vc_build_link($url);
            if ($link["url"] != "") {

                $title  = ($title != "") ? $title : $link["title"];
                $output = "<a href=\"" . esc_url($link["url"]) . "\"";
                $output .= ($link["target"] != "") ? " target=\"" . esc_attr($link["target"]) . "\"" : "";
                $output .= " title=\"" . esc_attr($link["title"]) . "\"" . $class_attr . $style_attr . ">" . esc_html($link["title"]) . "</a>";
            }
        }

        return $output;
    }
}

/*-----------------------------------------------------------------------------------*/
/*  Get allowed tags
/*-----------------------------------------------------------------------------------*/
if (!function_exists("rad_get_allowed_tags")) {

    function rad_get_allowed_tags()
    {
        return array(
            "strong" => array(),
            "br"     => array(),
            "sup"    => array(),
            "em"     => array(),
            "span"   => array(),
            "u"      => array(),
            "a"      => array(
                "href"  => array(),
                "title" => array(),
            ),
        );
    }
}

/*-----------------------------------------------------------------------------------*/
/*  Shortcode helpers
/*-----------------------------------------------------------------------------------*/

//Generate ID for shortcode elements
if (!function_exists("rad_element_id")) {

    function rad_element_id($key)
    {
        $globalKey = "rad_$key";

        if (array_key_exists($globalKey, $GLOBALS)) {
            $GLOBALS[$globalKey]++;
        } else {
            $GLOBALS[$globalKey] = 1;
        }

        $id = $GLOBALS[$globalKey];
        return $key . "_" . $id;
    }
}

/*---------------------------------
get page meta
------------------------------------*/
if( !function_exists("rad_legacy_names"))
{
    //due to some bugs in defining conditions in eleemntor settings, 
    function rad_legacy_names ($key)
    {
        $special_names = array (
            //page
            "page-header-custom",
            "page-header-mode",
            "title-bar",
            "title-text",
            "page-header-bg",
            "page-header-bg-image",
            "page-header-text-color",
            "slider-type",
            "slide-mode",
            "slider-width",
            "builtin-slider-cat",
            "slider-pagination-type",
            "slider-pagination-style",
            "rev-slider",
            "menu-initial-state-logo",
            "initial-menu-background-color",
            "initial-menu-text-color",
            "initial-menu-border-color",
            "initial-shop-cart-text-color",
            "menu-second-state-logo",
            "menu-background-color",
            "menu-text-color",
            "menu-border-color",
            "menu-border-color",
            "shop-cart-text-color",
            //post
            "video-type",
            "video-id",
            "audio-url",
            "video-type",
            //product
            "product-social-share",
            "product-social-share",

        );

        if(in_array($key, $special_names))
        {
            return str_replace("-","_",$key);
        }
        
        return $key;
    }
}
if (!function_exists("rad_get_meta")) {

    function rad_get_meta($key = "", $single = true, $id = null)
    {
        $pid = null;

        $essential_defaults = array(
            //page
            "page-header-mode"        => "1",
            "page-header-bg"          => "rgba(255,255,255,0)",
            "title-bar"               => "2",
            "page-header-text-color"  => "rgba(0,0,0,1)",
            "sidebar"                 => "no-sidebar",
            "slider-type"             => "none",
            "slider-with"             => "fullscreen-edge",
            "slide-mode"              => "fade",
            //product
            "video_type"              => "none",
            "video_play_button_color" => "light",
            "product-social-share"    => 1,
            //slider
            "button-text-color"       => "#ffffff",
            "button-text-hover-color" => "#222222",
            "button-background-color" => "#ffffff",
            "style"                   => "side",
            "title-font"              => "theme_default_bold",
            "subtitle1-font"          => "theme_default",
            "subtitle2-font"          => "theme_default",
            //blog
            "video-type"              => "vimeo",
        );

        if (in_the_loop()) {
            $pid = get_the_ID();
        } else {
            $pid = get_queried_object_id();
            //Special cases
            if (is_home() && !is_front_page()) {
                $pid = get_option("page_for_posts");
            }

            if (function_exists("is_shop") && is_shop()) {
                $pid = wc_get_page_id("shop");
            }

            if ( get_query_var( 'is_auction_archive', false ) === 'true' ) { // WooCommerce Auction plugin
                $pid = wc_get_page_id( 'auction' );
            }
        }

        if ($id != null) {
            $pid = $id;
        }

        if ($pid == null) {
            return "";
        }

        $value = "";
        if ( rad_is_elementor_active() && Elementor\Plugin::instance()->db->is_built_with_elementor( $pid ) ){
            $key = rad_legacy_names($key);
            $type = "page";

            // Get the page settings manager
            $page_settings_manager = \Elementor\Core\Settings\Manager::get_settings_managers( $type );

            // Get the settings model for current post
            $page_settings_model = $page_settings_manager->get_model( $pid );
            
            // Retrieve the color we added before
            $value = $page_settings_model->get_settings( $key );
            
        }
        else
        {
            if ($key == "") {
                $value = get_post_meta($pid, $key, false); //return all post metas
            }  else {

                $value = get_post_meta($pid, $key, $single);
                if ($single == true && $value == "" && isset($essential_defaults[$key])) {
                    $value = $essential_defaults[$key]; //return default value for essential keys
                }
            }
        }

        $value = apply_filters("rad_get_post_meta_filter", $value, $key);
        return $value;
    }
}

/*---------------------------------
Get title of page inside its loop
------------------------------------*/
if (!function_exists("rad_get_the_title")) {

    function rad_get_the_title()
    {
        $pid = null;

        if (in_the_loop() || is_single() || (is_page() && !is_home())) {
            $pid = get_the_ID();
        }

        //Special case for blog page
        if (is_home() && !is_front_page()) {
            $pid = get_option("page_for_posts");
        }

        if (function_exists("is_shop")) {
            if (is_shop()) {

                $pid = wc_get_page_id("shop");
            }
        }

        if (null == $pid) {
            return "";
        }

        return get_the_title($pid); //return all post metas
    }
}

/*---------------------------------
Gets array value with specified key, if the key does not exist  default value is returned
------------------------------------*/
if (!function_exists("rad_array_value")) {
    function rad_array_value($key, $arr, $default = "")
    {
        return array_key_exists($key, $arr) ? $arr[$key] : $default;
    }
}

/*---------------------------------
Deletes attachment by given url
------------------------------------*/
if (!function_exists("rad_delete_attachment")) {
    function rad_delete_attachment($url)
    {
        global $wpdb;
        $prefix = $wpdb->prefix;

        // We need to get the image meta ID.
        $results = $wpdb->get_results($wpdb->prepare("SELECT ID FROM " . $prefix . "posts where guid = %s AND post_type = 'attachment'", $url));

        // And delete it
        foreach ($results as $row) {
            wp_delete_attachment($row->ID);
        }
    }
}

/*---------------------------------
String functions
------------------------------------*/
function rad_ends_with($string, $test)
{
    $strlen  = strlen($string);
    $testlen = strlen($test);
    if ($testlen > $strlen) {
        return false;
    }

    return substr_compare($string, $test, -$testlen) === 0;
}

function rad_replace_last_occurrence($haystack, $needle, $replacement)
{
    $last = strrpos($haystack, $needle);

    if ($last === false) {
        return $haystack;
    }

    return substr_replace($haystack, $replacement, $last, strlen($needle));
}

function rad_remove_last_occurrence($haystack, $needle)
{
    return rad_replace_last_occurrence($haystack, $needle, "");
}

//Simple path combining function
function rad_path_combine($path1, $path2)
{
    $dirSep = "/"; //It should be DIRECTORY_SEPARATOR constant but does not work with URIs in WordPress
    $e1     = $path1[strlen($path1) - 1];
    $b2     = $path2[0];

    //Convert
    if ($e1 === "\\") {
        $e1 = $dirSep;
    }

    if ($b2 === "\\") {
        $b2 = $dirSep;
    }

    //Both paths has no separator chars
    if ($e1 !== $dirSep && $b2 !== $dirSep) {
        $value = $path1 . $dirSep . $path2;
    }
    //One path has directory separator and the other doesn't
    elseif (($e1 === $dirSep && $b2 !== $dirSep) ||
        ($e1 !== $dirSep && $b2 === $dirSep)
    ) {
        $value = $path1 . $path2;
    }
    //Else both path has directory separator
    else {
        $value = $path1 . substr($path2, 1);
    }

    $args = func_get_args();

    if (count($args) < 3) {
        return $value;
    }

    $newArgs = array_merge(array($value), array_slice($args, 2));

    return call_user_func_array(" rad_path_combine", $newArgs);
}

function rad_add_image_size_retina($name, $width = 0, $height = 0, $crop = false)
{
    add_image_size($name, $width, $height, $crop);

    if (rad_get_option("retina_ready") != "0") {
        //Check Retina Ready option is enable or not!
        add_image_size("$name@2x", $width * 2, $height * 2, $crop);
    }

}

/*-----------------------------------------------------------------*/
//                  CHECK WC
/*-----------------------------------------------------------------*/

if (!function_exists("rad_is_wc_active")) {
    function rad_is_wc_active()
    {
        return class_exists("woocommerce");
    }
}

/*-----------------------------------------------------------------*/
/* Calculate image height
/*-----------------------------------------------------------------*/

if (!function_exists("rad_get_height_percentage")) {
    function rad_get_height_percentage($image, $width = 1, $height = 1)
    {
        if ($image != "") {
            $re = "/width=\"(\\d+)\".*height=\"(\\d+)\"/";

            preg_match($re, $image, $matches);
            if (isset($matches[1]) && isset($matches[2])) {
                $height = $matches[2];
                $width  = $matches[1];
            } else {
                return 100;
            }

        }

        if ($width == 0) {
            return 100;
        }

        return ($height / $width) * 100;
    }
}

if (!function_exists("rad_get_image_width")) {
    function rad_get_image_width($image)
    {
        if ($image != "") {
            $regex = "/width=\"(\\d+)\"/";

            preg_match($regex, $image, $matches);
            if (isset($matches[1])) {
                $width = $matches[1];
            } else {
                $width = 0;
            }

        }

        if ($width == 0) {
            return 100;
        }

        return $width;
    }
}

/*---------------------------------
Revolution slider
------------------------------------*/
if (!function_exists("rad_get_revolution_slider_slides")) {
    function rad_get_revolution_slider_slides()
    {

        if (class_exists("RevSlider")) {

            // Get WPDB Object
            global $wpdb;

            // Table name
            $prefix = $wpdb->prefix;

            // Get sliders
            $sliders = $wpdb->get_results("SELECT * FROM " . $prefix . "revslider_sliders" . "
                                                ORDER BY id ASC LIMIT 100");
            $items = array("no-slider" => esc_html__('No slider', "aventa"));

            // Iterate over the sliders
            foreach ($sliders as $key => $item) {
                $items[$item->alias] = $item->title;
            }
            return $items;
        }

    }
}

/*---------------------------------
Downloads data from given URL
------------------------------------*/
if (!function_exists("rad_get_url_content")) {
    function rad_get_url_content($url, $proxy = "")
    {
        $args = array(
            "headers"   => array(),
            "body"      => null,
            "sslverify" => true,
        );

        $response = wp_remote_get($url, array(
            "timeout" => 45,
        )
        );

        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            $ret           = array("error" => $error_message, "errorno" => "");
        } else {
            $ret = $response["body"];
        }

        return $ret;
    }
}

/*---------------------------------
Get Audio URL from SoundCloud
------------------------------------*/
if (!function_exists("rad_extract_audio_info")) {
    function rad_extract_audio_info($string)
    {
        //check for soundcloud url
        if (preg_match('/https?:\/\/(?:www\.)?soundcloud\.com\/[^&\n\s"<>]+\/[^&\n\s"<>]+\/?/i', $string, $matches)) {
            return array("type" => "soundcloud", "url" => $matches[0]);
        }

        return null;
    }
}

if (!function_exists("rad_get_video_meta")) {
    function rad_get_video_meta(array &$video)
    {
        if ($video["type"] != "youtube" && $video["type"] != "vimeo") {
            return null;
        }

        $ret = rad_get_url_content($video["url"]/*, 127.0.0.1:8080'*/);

        if (is_array($ret)) {
            return "Server Error: " . $ret["error"] . " \nError No: " . $ret["errorno"];
        }

        if (trim($ret) == "") {
            return "Error: got empty response from youtube";
        }

        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($ret);
        libxml_clear_errors();
        $metas       = $dom->getElementsByTagName("meta");
        $video_width = $video_height = "";

        foreach ($metas as $meta) {
            if ($meta->getAttribute("property") == "og:video:width") {
                $video_width = $meta->getAttribute("content");
            } elseif ($meta->getAttribute("property") == "og:video:height") {
                $video_height = $meta->getAttribute("content");
            }
        }

        if ($video_width != "" && $video_height != "") {
            $video["width"]  = $video_width;
            $video["height"] = $video_height;
        }

        return null;
    }
}

if (!function_exists("rad_soundcloud_get_embed")) {
    function rad_soundcloud_get_embed($url)
    {
        $json = rad_get_url_content("http://soundcloud.com/oembed?format=json&url=$url"/*, '127.0.0.1:86'*/);

        if (is_array($json)) {
            return "Server Error: " . $json["error"] . " \nError No: " . $json["errorno"];
        }

        if (trim($json) == "") {
            return "Error: got empty response from soundcloud";
        }

        //Convert the response string to PHP object
        $data = json_decode($json);

        if (null == $data) {
            return "Cant decode the soundcloud response \nData: $json";
        }

        //TODO: add additional error checks

        return $data->html;
    }
}

/*---------------------------------
Get video URL from known sources such as YouTube and vimeo
------------------------------------*/
if (!function_exists("rad_extract_video_info")) {
    function rad_extract_video_info($string)
    {
        //check for YouTube video URL
        if (preg_match('/https?:\/\/(?:www\.)?youtube\.com\/watch\?v=[^&\n\s"<>]+/i', $string, $matches)) {
            $url = parse_url($matches[0]);
            parse_str($url["query"], $queryParams);

            return array("type" => "youtube", "url" => $matches[0], "id" => $queryParams["v"]);
        }
        //Vimeo
        else if (preg_match("/https?:\/\/(?:www\.)?vimeo\.com\/\d+/i", $string, $matches)) {
            $url = parse_url($matches[0]);

            return array("type" => "vimeo", "url" => $matches[0], "id" => ltrim($url["path"], "/"));
        }

        return null;
    }
}

/*---------------------------------
retrieves the attachment ID from the file URL
------------------------------------*/
if (!function_exists("rad_get_image_id")) {
    function rad_get_image_id($image_url)
    {
        global $wpdb;
        $prefix = $wpdb->prefix;

        // generate Full size Image URL by removing image size info
        $original_image_url = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $image_url);

        if ($original_image_url == "") {
            $original_image_url = $image_url;
        }

        $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM " . $prefix . "posts" . " WHERE guid='%s';", $original_image_url));

        if (count($attachment)) {
            return $attachment[0];
        } else {
            return -1;
        }

    }
}

/*---------------------------------
Create title based on type
------------------------------------*/
if (!function_exists("rad_make_title")) {

    function rad_make_title($type, $title, $class, $style = "", $attr = "", $has_closing = true)
    {
        $valid_tags = array("h1", "h2", "h3", "h4", "h5", "h6");
        if (!in_array($type, $valid_tags)) {
            $type = "h3";
        }

        if ($title == "") {
            return "";
        }

        if ($style != "") {
            $style = " style=\"" . esc_attr($style) . "\"";
        }

        if ($class != "") {
            $class = " class=\"" . esc_attr($class) . "\"";
        }

        if ($attr != "") {
            $attr = " " . $attr;
        }

        $html = "<" . $type . $class . $style . $attr . ">" . wp_kses($title, rad_get_allowed_tags());
        if ($has_closing) {
            $html .= "</" . $type . ">";
        }

        return $html;
    }
}

/*---------------------------------
Create text
------------------------------------*/
if (!function_exists("rad_make_text")) {

    function rad_make_text($type, $text, $class = "", $style = "", $has_closing = true)
    {
        if ($text == "") {
            return "";
        }

        if ($type != "p") {
            $type == "span";
        }

        if ($style != "") {
            $style = " style=\"" . esc_attr($style) . "\"";
        }

        if ($class != "") {
            $class = " class=\"" . esc_attr($class) . "\"";
        }

        $html = "<" . $type . $style . $class . ">" . $text;
        if ($has_closing) {
            $html .= '</' . $type . '>';
        }
        return $html;
    }
}

/*---------------------------------
Create text
------------------------------------*/
if (!function_exists("rad_make_container")) {

    function rad_make_container($type, $text = "", $id = "", $class = "", $style = "", $attr = "", $has_closing = true)
    {

        if ($id != "") {
            $id = " id=\"" . esc_attr($id) . "\"";
        }

        if ($type == "") {
            $type == "span";
        }

        if ($style != "") {
            $style = " style=\"" . esc_attr($style) . "\"";
        }

        if ($class != "") {
            $class = " class=\"" . esc_attr($class) . "\"";
        }

        if ($attr != "") {
            $attr = " " . $attr;
        }

        $html = "<" . $type . $id . $class . $style . $attr . ">" . $text;
        if ($has_closing) {
            $html .= "</" . $type . ">";
        }

        return $html;
    }
}
/*---------------------------------
Create Animation attributes
------------------------------------*/
if (!function_exists("rad_make_anim_attributes")) {

    function rad_make_anim_attributes($animation, $delay, $output_array = false)
    {
        if ($animation == "" || !is_numeric($delay)) {
            if ($output_array) {
                return array();
            }
            return "";
        }

        if ($output_array) {
            return array(
                "data-animation" => esc_attr($animation),
                "data-delay"     => esc_attr($delay),
            );
        }
        return "data-animation=\"" . esc_attr($animation) . "\" data-delay=\"" . esc_attr($delay) . "\"";
    }
}

/*---------------------------------
Create Social icons
------------------------------------*/
if (!function_exists("rad_social_icons")) {
    function rad_social_icons($id, $socials, $classes, $type)
    {
        $output = "";

        if ($socials == null) //use theme settings
        {
            $socials = array(
                "facebook"    => array(
                    "name" => "facebook-f",
                    "url"  => rad_get_option("social_facebook_url"),
                ),
                "twitter"     => array(
                    "name" => "twitter",
                    "url"  => rad_get_option("social_twitter_url"),
                ),
                "vimeo"       => array(
                    "name" => "vimeo-v",
                    "url"  => rad_get_option("social_vimeo_url"),
                ),
                "youTube"     => array(
                    "name" => "youtube",
                    "url"  => rad_get_option("social_youtube_url"),
                ),
                "google+"     => array(
                    "name" => "google-plus-g",
                    "url"  => rad_get_option("social_googleplus_url"),
                ),
                "dribbble"    => array(
                    "name" => "dribbble",
                    "url"  => rad_get_option("social_dribbble_url"),
                ),
                "tumblr"      => array(
                    "name" => "tumblr",
                    "url"  => rad_get_option("social_tumblr_url"),
                ),
                "linkedin"    => array(
                    "name" => "linkedin-in",
                    "url"  => rad_get_option("social_linkedin_url"),
                ),
                "flickr"      => array(
                    "name" => "flickr",
                    "url"  => rad_get_option("social_flickr_url"),
                ),
                "github"      => array(
                    "name" => "github-g",
                    "url"  => rad_get_option("social_github_url"),
                ),
                "last.fm"     => array(
                    "name" => "lastfm",
                    "url"  => rad_get_option("social_lastfm_url"),
                ),
                "paypal"      => array(
                    "name" => "paypal",
                    "url"  => rad_get_option("social_paypal_url"),
                ),
                "rss"         => array(
                    "name" => "rss",
                    "url"  => rad_get_option("social_rss_url"),
                ),
                "skype"       => array(
                    "name" => "skype",
                    "url"  => rad_get_option("social_skype_url"),
                ),
                "wordPress"   => array(
                    "name" => "wordpress",
                    "url"  => rad_get_option("social_wordpress_url"),
                ),
                "yahoo"       => array(
                    "name" => "yahoo",
                    "url"  => rad_get_option("social_yahoo_url"),
                ),
                "deviantArt"  => array(
                    "name" => "deviantart",
                    "url"  => rad_get_option("social_deviantart_url"),
                ),
                "steam"       => array(
                    "name" => "steam-symbol",
                    "url"  => rad_get_option("social_steam_url"),
                ),
                "reddit"      => array(
                    "name" => "reddit-alien",
                    "url"  => rad_get_option("social_reddit_url"),
                ),
                "stumbleUpon" => array(
                    "name" => "stumbleupon",
                    "url"  => rad_get_option("social_stumbleupon_url"),
                ),
                "pinterest"   => array(
                    "name" => "pinterest-p",
                    "url"  => rad_get_option("social_pinterest_url"),
                ),
                "xing"        => array(
                    "name" => "xing",
                    "url"  => rad_get_option("social_xing_url"),
                ),
                "blogger"     => array(
                    "name" => "blogger-b",
                    "url"  => rad_get_option("social_blogger_url"),
                ),
                "soundCloud"  => array(
                    "name" => "soundcloud",
                    "url"  => rad_get_option("social_soundcloud_url"),
                ),
                "delicious"   => array(
                    "name" => "delicious",
                    "url"  => rad_get_option("social_delicious_url"),
                ),
                "foursquare"  => array(
                    "name" => "foursquare",
                    "url"  => rad_get_option("social_foursquare_url"),
                ),
                "instagram"   => array(
                    "name" => "instagram",
                    "url"  => rad_get_option("social_instagram_url"),
                ),
                "behance"     => array(
                    "name" => "behance",
                    "url"  => rad_get_option("social_behance_url"),
                ),
                "custom1"     => array(
                    "name"  => rad_get_option("social_custom1_title"),
                    "url"   => rad_get_option("social_custom1_url"),
                    "image" => wp_get_attachment_url(
                        rad_get_option("social_custom1_image")
                    ),
                ),
                "custom2"     => array(
                    "name"  => rad_get_option("social_custom2_title"),
                    "url"   => rad_get_option("social_custom2_url"),
                    "image" => wp_get_attachment_url(
                        rad_get_option("social_custom2_image")
                    ),
                ),
                "custom3"     => array(
                    "name"  => rad_get_option("social_custom3_title"),
                    "url"   => rad_get_option("social_custom3_url"),
                    "image" => wp_get_attachment_url(
                        rad_get_option("social_custom3_image")
                    ),
                ),
            );

            if (rad_get_option("rss") != "1") {
                unset($socials["rss"]);
            }
        }

        foreach ($socials as $key => $social) {
            $name       = $social["name"];
            $label      = $key;
            $url        = $social["url"];
            $image      = isset($social["image"]) ? $social["image"] : "";
            $elem_class = "";
            if ($type == "text") {
                $elem_class = "underline-style ";
            }

            if ($url != "") {
                $output .= "<a class=\"" . $elem_class . $name . "-icon\" href=\"" . esc_url($url) . "\" target=\"_blank\">";
                if ($type == "icon") {
                    if ($image != "") {
                        $output .= "<img src=\"" . esc_url($image) . "\" title=\"" . $name . "\">";
                    } else {
                        if ($name == "mail") {
                            $output .= rad_Icon_Manager::get_icon("envelope", "solid");
                        }
                        if ($name == "rss") {
                            $output .= rad_Icon_Manager::get_icon("rss", "solid");
                        } else {
                            $output .= rad_Icon_Manager::get_icon($name, "brand");
                        }

                    }

                }
                $output .= $label;
                $output .= "</a>";
            }
        }

        if ($output == "") {
            return;
        }

        $classes = implode(" ", array_filter($classes));
        $classes .= " " . $type . "-type";

        return "<span id=\"" . esc_attr($id) . "\" class=\"" . esc_attr($classes) . "\">" . $output . "</span>";
    }
}

/*---------------------------------
Get font options
------------------------------------*/
if (!function_exists("rad_get_font_options")) {

    function rad_get_font_options($item, $type = "name")
    {
        if ($item == "theme_default" || $item == "theme_default_medium" || $item == "theme_default_bold") {
            if ($type == "name") {
                return "";
            } elseif ($type == "weight") {
                if ($item == "theme_default") {
                    return "font-weight:normal;";
                } elseif ($item == "theme_default_medium") {
                    return "font-weight:500;";
                } elseif ($item == "theme_default_bold") {
                    return "font-weight:bold;";
                }
            }
        }

        $font_array = explode(":", $item);
        if (count($font_array) == 2) {
            if ($type == "name") {
                return "font-family:\"" . trim($font_array[0]) . "\";";
            } else {
                return rad_get_font_variant_attribute(trim($font_array[1]));
            }

        } elseif (count($font_array) == 3) {
            if ($type == "name") {
                return "font-family:\"" . trim($font_array[1]) . "\";";
            } else {
                return rad_get_font_variant_attribute(trim($font_array[2]));
            }

        }

        return "";
    }
}

/*---------------------------------
Get image
------------------------------------*/
if (!function_exists("rad_get_image")) {

    function rad_get_image($id, $class , $title , $size, $width, $height, $crop, $lazy = false)
    {
        $image      = "";
        $attributes = array();
        if ($class != "") {
            $attributes["class"] = $class;
        }

        if ($title != "") {
            $attributes["alt"] = $title;
        }

        if (is_numeric($id)) {
            if ($size == "custom") {
                if ($width != "" && $height != "") {
                    //resize the image
                    $image_link       = wp_get_attachment_url($id);
                    $img_url          = "";
                    $image_attributes = aq_resize($image_link, $width, $height, $crop, false, false);

                    if ($image_attributes[0]) {
                        $img_url = $image_attributes[0];
                    } else {
                        $img_url = $image_link;
                    }

                    if ($lazy) {
                        $image = "<img src=\"" . esc_url($img_url) . "\" width=\"" . esc_attr($image_attributes[1]) . "\" height=\"" . esc_attr($image_attributes[2]) . "\"";
                    }

                    if ($class != "") {
                        $image .= " class=\"" . esc_attr($class) . "\"";
                    }

                    if ($title != "") {
                        $image .= " alt=\"" . esc_attr($title) . "\"";
                    }

                    $image .= "/>";

                } else {
                    $image = wp_get_attachment_image($id, "full", false, $attributes);
                }

            } else {
                $image = wp_get_attachment_image($id, $size, false, $attributes);
            }

            if ($lazy) {
                $image = str_replace("src=", "src=\"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\" data-src=", $image);
            }

            return $image;
        }

        return "";
    }
}

/*---------------------------------
Get image URL
------------------------------------*/
if (!function_exists("rad_get_image_url")) {

    function rad_get_image_url($id, $size, $width = "", $height = "", $crop = false)
    {
        $image_url = "";

        if (is_numeric($id)) {
            if ($size == "custom") {
                if ($width != "" && $height != "") {
                    //resize the image
                    $image_link       = wp_get_attachment_url($id);
                    $image_attributes = aq_resize($image_link, $width, $height, $crop, false, false);

                    if ($image_attributes[0]) {
                        $img_url = $image_attributes[0];
                    } else {
                        $img_url = $image_link;
                    }
                } else {
                    $img_url = wp_get_attachment_image_url($id, "full", false);
                }

            } else {
                $img_url = wp_get_attachment_image_url($id, $size, false);
            }

            return esc_url($img_url);
        }
        elseif(is_array($id)) // ex: return values from Elementor settings
        {
            if(isset($id["url"]) ) {
                if($size == "full")
                {
                    $img_url = esc_url($id["url"]);
                }
                elseif($size == "custom")
                {
                    if ($width != "" && $height != "") {
                        //resize the image
                        $image_link       = wp_get_attachment_url($id);
                        $image_attributes = aq_resize($image_link, $width, $height, $crop, false, false);

                        if ($image_attributes[0]) {
                            $img_url = $image_attributes[0];
                        } else {
                        $img_url = $image_link;
                        }
                    } else {
                        $img_url = esc_url($id["url"]);
                    }
                }
                else
                {
                    $img_url = wp_get_attachment_image_url($id['id'], $size, false);
                }
                
            }

            return esc_url($img_url);
        }

        return "";
    }
}

/*-----------------------------------
Get attribute of font based on variant
------------------------------------*/
if (!function_exists("rad_get_font_variant_attribute")) {
    function rad_get_font_variant_attribute($variant)
    {
        if (is_numeric($variant)) {
            return "font-weight:" . $variant . ";";
        } elseif ($variant == "regular") {
            return "font-weight:normal;";
        } elseif ($variant == "italic") {
            return "font-style:italic;";
        } elseif (strpos($variant, "italic") !== false) {
            return "font-style:italic;font-weight:" . str_replace("italic", "", $variant) . ";";
        }

        return "";
    }
}

/*-----------------------------------
Make URL of fonts
------------------------------------*/
if (!function_exists("rad_make_google_font_url")) {
    function rad_make_google_font_url($fonts = array())
    {
        $RequestedFonts = array();
        $fontReq        = "//fonts.googleapis.com/css?family=";

        foreach ($fonts as $font => $variants) {
            //Repplace space in font name with plus character
            $query = preg_replace("/ /", "+", $font);

            if (is_array($variants) && count($variants)) {
                $query .= ":" . implode(",", $variants);
            } else {
                $query .= ":" . $variants;
            }

            $RequestedFonts[] = $query;
        }

        //Load default or user selected google fonts
        $fontReq .= implode("|", $RequestedFonts);

        if (count($RequestedFonts) > 0) {
            return $fontReq;
        }

        return "";
    }
}

/*-----------------------------------
Make URL of fonts
------------------------------------*/
if (!function_exists("rad_get_fonts_collection")) {
    function rad_get_fonts_collection($mode = "js")
    {

        $fonts_collection = json_decode(rad_get_option("fonts-collection"), true);

        if ($mode == "js") {
            $font_items = array(
                "theme_default"        => "regular",
                "theme_default_medium" => "500",
                "theme_default_bold"   => "700",
            );

            if (is_array($fonts_collection)) {
                foreach ($fonts_collection as $font) {
                    $weights = explode(",", $font["weights"]);
                    foreach ($weights as $weight) {
                        $font_items[$font["font"]] = $weight;
                    }
                }
            }

            $fonts = array();
            if (is_array($font_items)) {
                foreach ($font_items as $font => $variant) {
                    $fonts[] = array(
                        "text"      => $font . "(" . $variant . ")",
                        "value"     => $font . ":" . $variant,
                        "textStyle" => "font-family:" . $font . ";" . rad_get_font_variant_attribute($variant),
                    );
                }
            }

            return json_encode($fonts);
        } elseif ($mode == "wpbakery") {
            $fonts = array(
                "Theme default( google : DM Sans : regular )" => "theme_default",
                "Theme default( google : DM Sans : 500 )"     => "theme_default_medium",
                "Theme default( google : DM Sans : 700 )"     => "theme_default_bold",
            );

            if (is_array($fonts_collection)) {
                foreach ($fonts_collection as $font) {
                    $weights = explode(",", $font["weights"]);
                    foreach ($weights as $weight) {
                        $key         = $font["font"] . " : " . $weight;
                        $val         = $font["font"] . ":" . $weight;
                        $fonts[$key] = $val;
                    }
                }
            }

            return $fonts;
        } elseif ($mode == "settings") {
            $fonts = array(
                "theme_default" => "Theme defaults ( google : DM Sans : regular )",
                "Theme default( google : DM Sans : 500 )"     => "theme_default_medium",
                "Theme default( google : DM Sans : 700 )"     => "theme_default_bold",
            );

            if (is_array($fonts_collection)) {
                foreach ($fonts_collection as $font) {
                    $weights = explode(",", $font["weights"]);
                    foreach ($weights as $weight) {
                        $key_val         = $font["source"] . " : " . $font["font"] . " : " . $weight;
                        $fonts[$key_val] = $key_val;
                    }
                }
            }

            return $fonts;
        }

    }
}

/*-----------------------------------
 is wpbakery frontend editor?
------------------------------------*/

function rad_is_wpbakery_frontend_editor() {
    return function_exists( 'vc_is_inline' ) && vc_is_inline() ? true : false;
}

/*-----------------------------------
 Is Elementor plugin active?
------------------------------------*/

function rad_is_elementor_active() {
    return ( did_action( 'elementor/loaded' ) ) ? true : false;
}

/*-----------------------------------------------------------------------------------*/
// Get MC4WP forms
/*-----------------------------------------------------------------------------------*/
if ( !function_exists( "rad_get_MC4WP_forms" ) ) {
    function rad_get_MC4WP_forms()
    {
        if (class_exists("MC4WP_MailChimp")) {
        // If the plugin is installed and activated

            $forms = mc4wp_get_forms(
                array(
                    "posts_per_page" => 1,
                    "orderby"        => "ID",
                    "order"          => "ASC",
                )
            );
            $lists = array();
            foreach ($forms as $form) {
                $lists["" . $form->name] = $form->ID;
            }

            return $lists;

        }

        return array();
    }
}

/*-----------------------------------------------------------------------------------*/
// Print element styles?
/*-----------------------------------------------------------------------------------*/
if ( !function_exists( "print_element_style" ) ) {
    function print_element_style()
    {
        global $post;
        $current_id = $post->ID;

        if ( rad_is_elementor_active() && Elementor\Plugin::instance()->db->is_built_with_elementor( $current_id ) ){
            return true;
        }
        else
        {   
            if(is_admin())
            {
                return true;
            }
        }
        
        return false;
    }
}
