<?php
/*---------------------------------
Add a pingback url auto-discovery header for single posts, pages, or attachments.
------------------------------------*/
if (!function_exists("rad_pingback_header")) {
    function rad_pingback_header()
    {
        if (is_singular() && pings_open()) {
            echo "<link rel=\"pingback\" href=\"", esc_url(get_bloginfo("pingback_url")), "\">";
        }
    }
}
add_action("wp_head", "rad_pingback_header");

/*---------------------------------
Site Icon backward compatibility ( WP < 4.3 or in case of no icon selection )
------------------------------------*/
if (!function_exists("rad_wp_site_icon")) {
    function rad_wp_site_icon()
    {

        if (!(function_exists("has_site_icon") && has_site_icon())) {
            $favicon = RAD_THEME_IMAGES_URI . "/favicon.png";

            if (rad_get_option("favicon") != "") {
                // option in WP < 4.3
                $favicon = rad_get_image_url(rad_e_option("favicon"), "full");
            }
            echo "<link rel=\"shortcut icon\" href=\"" . esc_url($favicon) . "\" />";
        }
    }
}
add_filter("wp_head", "rad_wp_site_icon");

/*---------------------------------
Gathering In-line styles of pages of main-page + adding them to main-page
------------------------------------*/
if (!function_exists("rad_addVCCustomCss")) {
    function rad_addVCCustomCss()
    {

        $shortcodes_custom_css = "";

        if (function_exists("is_shop")) {
            $shortcodes_custom_css = get_post_meta(wc_get_page_id("shop"), "_wpb_shortcodes_custom_css", true);
            if (is_shop() && $shortcodes_custom_css != "") {
                echo "<style type=\"text/css\">" . $shortcodes_custom_css . "</style>";
            }
        }
    }
}

add_action("wp_head", "rad_addVCCustomCss", 1000);

/*---------------------------------
Customizing wp_title
------------------------------------*/

if (!function_exists("rad_filter_wp_title")) {

    function rad_filter_wp_title($title, $separator)
    {

        if (is_feed()) {
            return $title;
        }

        global $paged, $page;

        if (is_search()) {

            $title = sprintf(esc_html__("Search results for %s", "aventa"), "\"" . get_search_query() . "\"");

            if ($paged >= 2) {
                $title .= " $separator " . sprintf(esc_html__("Page %s", "aventa"), $paged);
            }

            $title .= " $separator " . get_bloginfo("name", "display");

            return $title;

        }

        return $title;

    }
}

add_filter("wp_title", "rad_filter_wp_title", 10, 2);
/*---------------------------------
Vertical menu - left And Right position
------------------------------------*/

if (!function_exists("rad_body_classes")) {

    function rad_body_classes($classes)
    {

        $classes[] = "rad-body";

        // check topbar is Enable Or not
        $topbar = rad_get_option("topbar_display");
        if ($topbar == "1" && !(is_page_template("maintenance.php") || is_page_template("blank.php"))) {
            $classes[] = "topbar-active";
        }

        //check if page has extra class name or not
        $extra_class = rad_get_meta("extra_class");
        if ($extra_class) {
            $classes[] = $extra_class;
        }

        if (!has_nav_menu("hamburger-main-nav") && !has_nav_menu("primary-nav") && !has_nav_menu("mobile-nav")) {
            $classes[] = "no-mobile-menu";
        }

        $page_beins_with = rad_header_status();
        $slider_type     = rad_get_meta("slider-type");
        $slider_width    = rad_get_meta("slider-width");

        if ($page_beins_with == "top-space" || ($slider_type == "builtin-slider" && $slider_width == "boxed")) {
            $classes[] = "rda-top-space";
        }

        return $classes;
    }

}

add_filter("body_class", "rad_body_classes", 1, 1);

/*---------------------------------
Remove the excerpt "more"
------------------------------------*/
if (!function_exists("rad_new_excerpt_more")) {
    function rad_new_excerpt_more($more)
    {
        return "...";
    }
}

add_filter("excerpt_more", "rad_new_excerpt_more");

/*---------------------------------
Add support for Vertical Featured Images.
------------------------------------*/
if (!function_exists("rad_thumbnail_vertical_check")) {
    function rad_thumbnail_vertical_check($html, $post_id, $post_thumbnail_id, $size, $attr)
    {
        $image_data = wp_get_attachment_image_src($post_thumbnail_id, $size);
        if (!isset($image_data[1]) || !isset($image_data[2])) {
            return $html;
        }

        $width  = $image_data[1];
        $height = $image_data[2];
        if ($height > $width) {
            $html = str_replace("attachment-", "vertical-image attachment-", $html);
        }
        return $html;
    }
}

if (!function_exists("rad_thumbnail_vertical_check_filter")) {
    function rad_thumbnail_vertical_check_filter()
    {
        add_filter("post_thumbnail_html", "rad_thumbnail_vertical_check", 10, 5);
    }
}
rad_thumbnail_vertical_check_filter();

/*-----------------------------------------------------------------*/
// allowed skype protocol
/*-----------------------------------------------------------------*/
if (!function_exists("rad_ss_allow_skype_protocol")) {
    function rad_ss_allow_skype_protocol($protocols)
    {
        $protocols[] = "skype";
        return $protocols;
    }
}

add_filter("kses_allowed_protocols", "rad_ss_allow_skype_protocol");

/*-----------------------------------------------------------------*/
// image fallback - placeholder img when there is a missing img
/*-----------------------------------------------------------------*/
if (!function_exists("rad_image_fallback")) {
    function rad_image_fallback($image, $attachment_id, $size, $icon)
    {
        if ($image == "" & $attachment_id != "") {
            $placeholder_img = RAD_THEME_ASSETS_URI . "/img/placeholder.jpg";

            $placehoder = array($placeholder_img, "720", "1280", false);

            return $placehoder;
        }
        return $image;
    }
}

add_filter("wp_get_attachment_image_src", "rad_image_fallback", 100, 4);

/*-----------------------------------------------------------------*/
// wrap all sidebars
/*-----------------------------------------------------------------*/
if (!function_exists("rad_widget_sidebar")) {
    function rad_widget_sidebar($index)
    {
        if (!is_admin()) {
            echo "<div class=\"sidebar widget-area\">";
        }
    }
}

if (!function_exists("rad_widget_sidebar_end")) {
    function rad_widget_sidebar_end($index)
    {
        if (!is_admin() && $index != "sidebar-store") {
            // sidebar-store is sidebar of dokan plugin (Due to adding widgets witout dynamic_sidebar when sidebar is empty in dokan! the closing tag in "sidebar-store" addded by "dokan_sidebar_store_after" action  )
            echo "</div>";
        }
    }
}

if (!function_exists("rad_widget_sidebar_action")) {
    function rad_widget_sidebar_action()
    {
        add_action("dynamic_sidebar_before", "rad_widget_sidebar", 10);
        add_action("dynamic_sidebar_after", "rad_widget_sidebar_end", 10);
    }
}
rad_widget_sidebar_action();

/*-----------------------------------------------------------------*/
// Ajaxed Search
/*-----------------------------------------------------------------*/
if (!function_exists("rad_ajax_search")) {
    function rad_ajax_search()
    {

        /**
        check how we load products output in shortcodes.
        Check can we have set s and sku in args at a same time?
        check query!
         */
        global $post;
        $search_post_type = rad_get_option("search_post_type");

        if (!$search_post_type) {
            $search_post_type = "product";
        }
        $s = trim($_GET["s"]);

        $args = array("s" => $s, "post_type" => $search_post_type, "posts_per_page" => 20, "no_found_rows" => 1);

        //category
        if ($search_post_type == "product" && isset($_GET["cat"]) && $_GET["cat"] != "all" && $_GET["cat"] != "") {
            $args["category_name"] = trim($_GET["cat"]);
        }

        $posts = get_posts($args);

        $products_Sku     = array();
        $AllSearchResults = null;

        if ($search_post_type == "product") {
            $args_sku = array(
                "post_type"        => "product",
                "posts_per_page"   => 20,
                "meta_query"       => array(
                    array(
                        "key"     => "_sku",
                        "value"   => $s,
                        "compare" => "like",
                    ),
                ),
                "suppress_filters" => 0,
            );
            $products_sku = get_posts($args_sku);

            $AllSearchResults = array_merge($posts, $products_sku);
        } else {
            $AllSearchResults = $posts;
        }

        if (count($AllSearchResults) > 0) {
            $results = array();
            if ($search_post_type == "product") {
                foreach ($AllSearchResults as $post):
                    setup_postdata($post);
                    $product   = wc_get_product(get_the_ID());
                    $results[] = sprintf('<div class="search-item"><a href="%s">%s<span class="search-item-title">%s<span class="p-price">%s</span></span></a></div>', get_permalink(), ((has_post_thumbnail()) ? woocommerce_get_product_thumbnail() : ''), $product->get_title(), $product->get_price_html());
                endforeach;
            } else {
                foreach ($AllSearchResults as $post):
                    setup_postdata($post);
                    $results[] = sprintf('<div class="search-item"><a href="%s"><div class="imagewrap"><img src="%s"></div><span class="search-item-title">%s</span></a></div>', get_permalink(), get_the_post_thumbnail_url(), get_the_title());
                endforeach;
            }
            echo implode($results);
        } else {
            echo "<div class=\"no-result\">" . esc_html__("Nothing Found For :", "aventa") . " " . $s . "</div>";
        }
        die();
    }
}

add_action("wp_ajax_rad_ajax_search_action", "rad_ajax_search");
add_action("wp_ajax_nopriv_rad_ajax_search_action", "rad_ajax_search");
add_action("wc_ajax_rad_ajax_search_action", "rad_ajax_search");

/*-----------------------------------------------------------------*/
//                         Popup Newsletter
/*-----------------------------------------------------------------*/
if (!function_exists("rad_newsletter_popup")) {
    function rad_newsletter_popup()
    {
        get_template_part("templates/core/page/popup");
    }
}

if (!function_exists("rad_popup_newsletter_action")) {
    function rad_popup_newsletter_action()
    {
        if (rad_get_option("popup-newsletter") != 0) {
            add_action("wp_footer", "rad_newsletter_popup", 10);
        }
    }
}

rad_popup_newsletter_action();

/*-----------------------------------------------------------------*/
//                   Maintenance mode
/*-----------------------------------------------------------------*/

if (!function_exists("rad_maintenance_page")) {
    function rad_maintenance_page()
    {
        global $pagenow;
        if (!rad_get_option("maintenance_mode") || rad_get_option("maintenance_mode") == "0") {
            return;
        }

        $page_id = rad_get_option("maintenance_page");

        if (!$page_id) {
            return;
        }

        if ($pagenow !== "wp-login.php" && !current_user_can("manage_options") && !is_admin()) {
            wp_redirect(get_permalink($page_id));
            exit();
        }

    }
}
add_action("get_header", "rad_maintenance_page");

/*-----------------------------------------------------------------*/
// Cookies Law info
/*-----------------------------------------------------------------*/
if (!function_exists("rad_cookies_popup")) {

    function rad_cookies_popup()
    {

        if (rad_get_option("cookies_info") == "0") {
            return;
        }

        $policy_page_id = rad_get_option("cookies_policy_page");

        ?>
            <div id="rad-cookies-wrap">
                <div class="rad-cookies">
                    <div class="rad-txt">
                        <?php echo rad_get_option("cookies_text_message") ?>
                    </div>
                    <a href="#" class="rad-accept"><?php esc_html_e("Accept", "aventa");?></a>
                    <?php if ($policy_page_id) {?>
                         <a href="<?php echo get_page_link($policy_page_id); ?>" class="rad-read-more underline-style" target="_blank"><?php esc_html_e("More info", "aventa");?></a>
                    <?php }?>
                </div>
            </div>
        <?php

    }
}

add_action("wp_footer", "rad_cookies_popup", 300);

/*-----------------------------------------------------------------*/
// Rad size chart wrapper
/*-----------------------------------------------------------------*/
if (class_exists("YITH_WCPSC_Frontend")) {

    if (!function_exists("rad_size_chart")) {

        function rad_size_chart()
        {

            if (function_exists("is_product") && is_product()) {
                echo "<div class=\"size-chart-aside toggle-aside bg\">
                        <div class=\"size-chart-wrapper\"></div>
                    </div>";
            }

        }
    }

    add_action("rad_before_header_close", "rad_size_chart");

}

/**************************************************
increase quality of WordPress thumbnails images.
 **************************************************/
if (!function_exists("rad_thumbnail_quality")) {
    function rad_thumbnail_quality($quality)
    {
        return 100;
    }
}

add_filter("jpeg_quality", "rad_thumbnail_quality");
add_filter("wp_editor_set_quality", "rad_thumbnail_quality");

/**************************************************
Custom Excerpt for posts + no format box
 **************************************************/
if (!function_exists("rad_default_hidden_meta_boxes")) {
    function rad_default_hidden_meta_boxes($hidden, $screen)
    {
        // Grab the current post type
        $post_type = $screen->post_type;
        // If we are on a post...
        if ($post_type == "post") {
            // Define which meta boxes we wish to hide
            $hidden = array(
                "trackbacksdiv",
                "slugdiv",
                "revisionsdiv",
                "postcustom",
                "commentstatusdiv",
                "authordiv",
            );
            // Pass our new defaults onto WordPress
            return $hidden;
        }
        // If we are not on a 'post', pass the
        // original defaults, as defined by WordPress
        return $hidden;
    }
}

if (!function_exists("rad_default_hidden_meta_boxes_action")) {
    function rad_default_hidden_meta_boxes_action()
    {
        add_action("default_hidden_meta_boxes", "rad_default_hidden_meta_boxes", 10, 2);
    }
}
rad_default_hidden_meta_boxes_action();

/**************************************************
Modal box
 **************************************************/
if (!function_exists("rad_modals")) {
    function rad_modals()
    {

        $quick_view = rad_get_option("shop-enable-quickview");
        if ($quick_view == "1") {
            wp_enqueue_script("wc-add-to-cart-variation");
        }

        echo "<div id=\"modalbox\">
            <span id=\"modal-bg\"></span>
            <div class=\"modal-wrap\">
                <span class=\"wc-loading\"></span>
                <a href=\"#\" class=\"aside-close\"></a>
                <div id=\"modal-content\"></div>
            </div>
        </div>";
    }
}

add_action("wp_footer", "rad_modals");