<?php
// Exit if accessed directly
if (!defined("ABSPATH")) {
    exit;
}

require RAD_THEME_ADMIN . "/demos/demo-importer.php";

class Rad_Importer
{

    private $demo_names = array("demo1", "demo2", "demo3", "demo4", "demo5", "demo6", "demo7", "demo8");
    private $demo_types = array("vc", "el");
    private $demo_type  = "";
    private $demos      = array();
    private $theme_data = array();
    private $mc4wp_ids  = array();
    private $demo_name  = "";

    public function __construct()
    {

        $this->importer_setting();
        // Initialize the menu
        add_action("admin_enqueue_scripts", array($this, "init_scripts"), 200);
        add_action("admin_init", array($this, "init_scripts"), 200);
        add_action("admin_init", array($this, "init_resetting_permalinks"), 200);

    } // end constructor

    public function init_resetting_permalinks ()
    {
        if (delete_transient('rad_flush_rules'))
        {
            $this->reset_permalinks();
        } 

    }

    public function importer_setting()
    {

        $this->demos = array(
            "demo1" => array(
                "title"       => "Demo 1",
                "description" => "Demo 1",
                "link"        => "http://rado-studio.com/aventa-demo1",
            ),
            "demo2" => array(
                "title"       => "Demo 2",
                "description" => "Demo 2",
                "link"        => "http://rado-studio.com/aventa-demo2",
            ),
            "demo3" => array(
                "title"       => "Demo 3",
                "description" => "Demo 3",
                "link"        => "http://rado-studio.com/aventa-demo3",
            ),
            "demo4" => array(
                "title"       => "Demo 4",
                "description" => "Demo 4",
                "link"        => "http://rado-studio.com/aventa-demo4",
            ),
            "demo5" => array(
                "title"       => "Demo 5",
                "description" => "Demo 5",
                "link"        => "http://rado-studio.com/aventa-demo5",
            ),
            "demo6" => array(
                "title"       => "Demo 6",
                "description" => "Demo 6",
                "link"        => "http://rado-studio.com/aventa-demo6",
            ),
            "demo7" => array(
                "title"       => "Demo 7",
                "description" => "Demo 7",
                "link"        => "http://rado-studio.com/aventa-demo7",
            ),
            "demo8" => array(
                "title"       => "Demo 8",
                "description" => "Demo 8",
                "link"        => "http://rado-studio.com/aventa-demo8",
            ),
        );
    }

    public function init_scripts()
    {

        wp_enqueue_style("wp-color-picker");
        wp_enqueue_script("wp-color-picker");
        wp_register_script("rad-colorpicker-alpha", RAD_THEME_INC_URI . "/admin/assets/js/wp-color-picker-alpha.js", array("wp-color-picker"), "1.2.2");
        $color_picker_strings = array(
            "clear"            => esc_html__("Clear", "aventa"),
            "clearAriaLabel"   => esc_html__("Clear color", "aventa"),
            "defaultString"    => esc_html__("Default", "aventa"),
            "defaultAriaLabel" => esc_html__("Select default color", "aventa"),
            "pick"             => esc_html__("Select Color", "aventa"),
            "defaultLabel"     => esc_html__("Color value", "aventa"),
        );
        wp_localize_script("rad-colorpicker-alpha", "wpColorPickerL10n", $color_picker_strings);
        wp_enqueue_script("rad-colorpicker-alpha");
        wp_enqueue_style("rad-admin-style", RAD_THEME_INC_URI . "/admin/assets/css/style.css", false, "1.0.0", "screen");
        wp_enqueue_script("rad-admin-script", RAD_THEME_INC_URI . "/admin/assets/js/admin.js", array("jquery"), "1.0.0", true);

        $font_items = rad_get_fonts_collection("js");

        wp_localize_script("rad-admin-script", "RADData", array(
            "carousel_gallery_new_item" => "Item",
            "testimonial_new_item"      => "Testimonial",
            "fonts_collection"          => $font_items,
        ));
    }

    /**
     * Added to http_request_timeout filter to force timeout at 200 seconds during import
     * @return int 500
     */
    public function bump_request_timeout($val)
    {
        return 500;
    }

    public function importer_end()
    {
        ?>
        <div id="rad-importer-box">
            <div class="rad-importer-header">
                <div class="logo">
                    <?php echo "<img src=\"" . RAD_THEME_INC_URI . "/admin/assets/img/logo.jpg" . "\">"; ?>
                    <span class="version"><?php echo esc_html(RAD_THEME_VERSION); ?></span>
                </div>
            </div>

            <div class="box-title" style="text-align: center;">
                <img width="50%" src="<?php echo RAD_THEME_INC_URI . "/admin/assets/img/import.png"; ?>">
            </div>
            <br>
            <br>
        <?php
        /* Start the process of importing */
        ob_start();

        echo "<ul class=\"rad-importing\">";
        wp_ob_end_flush_all();
        flush();
        echo "<li class=\"rad-importing-finished\"><span class=\"rad-done\"><strong>" . esc_html__("Finished! Enjoy aventa", "aventa") . "</strong></li>";
        ?>
        </ul>
        </div>
        <?php
    }

    public function importer_start()
    {
        add_filter("http_request_timeout", array($this, "bump_request_timeout"));
        ?>
        <div id="rad-importer-box">
            <div class="rad-importer-header">
                <div class="logo">
                    <?php echo "<img src=\"" . RAD_THEME_INC_URI . "/admin/assets/img/logo.jpg" . "\">"; ?>
                    <span class="version"><?php echo esc_html(RAD_THEME_VERSION); ?></span>
                </div>
            </div>
            <div class="box-title">
                <h2><?php esc_html_e("Importing", "aventa");?> </h2>
                <p><strong class="importer-caution"><span class="dashicons dashicons-info-outline"></span> <?php esc_html_e("Notice! Do not close the browser during importing process", "aventa");?></strong></p>
            </div>
        <?php
        $this->demo_name = "";
        $this->demo_type = "";

        if (!defined("WP_LOAD_IMPORTERS")) {
            define("WP_LOAD_IMPORTERS", true);
        }

        if (isset($_POST)) {
            $demo_name       = sanitize_file_name($_POST["demo_name"]);
            $this->demo_name = $demo_name;
            $this->demo_type = $_POST["demo_type"];

        }

        if ($demo_name == "" || !in_array($demo_name, $this->demo_names) || !in_array($this->demo_type, $this->demo_types)) {
            echo "<strong>" . esc_html__("Sorry, there has been an error!", "aventa") . "</strong>";
            echo "<p>" . esc_html__("The demo does not exists on the package!", "aventa") . "</p>";
            return;

        }

        // Get the xml file from directory
        $import_xml_filepath  = RAD_THEME_INC . "/admin/demos/" . $demo_name . "/" . $demo_name . "-" . $this->demo_type . ".xml";
        $import_json_filepath = RAD_THEME_INC . "/admin/demos/" . $demo_name . "/" . $demo_name . ".json";

        if (!is_file($import_xml_filepath) || !is_file($import_json_filepath)) {
            echo "<strong>" . esc_html__("Sorry, there has been an error!", "aventa") . "</strong>";
            echo "<p>" . esc_html__("The demo File does not exist on your server!", "aventa") . "</p>";
            return;
        }

        //Read theme options
        global $wp_filesystem;
        // Initialize the WP filesystem, no more using 'file-put-contents' function
        if (empty($wp_filesystem)) {
            WP_Filesystem();
        }

        if (is_file($import_json_filepath)) {
            $theme_options_json = $wp_filesystem->get_contents($import_json_filepath);
            $this->theme_data   = json_decode($theme_options_json, true);
        } else {
            echo "<p>" . esc_html__("The demo options has an error!", "aventa") . "</p>";
            return;
        }

        //check the required plugins
        $errors = array();
        if (!class_exists("Aventa_core")) {
            $errors[] = "Aventa Core";
        }

        if (!class_exists("Rad_Import")) {
            $errors[] = "Wordpress Importer";
        }

        if (isset($this->theme_data["plugins"])) {
            $required_plugins = explode(",", $this->theme_data["plugins"]);

            foreach ($required_plugins as $plugin) {
                if ($plugin == "woocommerce" && !class_exists("woocommerce")) {
                    $errors[] = "Woocommerce";
                } elseif ($plugin == "revslider" && !class_exists("RevSliderSliderImport")) {
                    $errors[] = "Revolution Slider";
                } elseif ($plugin == "cf7") {
                    if(!class_exists("WPCF7"))
                    {
                        $errors[] = "Contact form 7";
                    }
                    
                    if($this->demo_type == "el" && !defined("HTCONTACTFORM_PL_URL")) {
                        $errors[] = "Contact Form 7 Widget For Elementor Page Builder";
                    }

                } elseif ($plugin == "mc4wp" && !class_exists("MC4WP_MailChimp")) {
                    $errors[] = "MC4WP (MailChimp for WP)";
                }
                elseif ($plugin == "instagram" && !class_exists("SB_Instagram_Feed")) {
                    $errors[] = "Smash Balloon Social photo Feed";
                }
            }

            if ($this->demo_type == "el" && !rad_is_elementor_active()) {
                $errors[] = "Elementor";

            } 
            if ($this->demo_type == "vc" && !class_exists("WPBakeryVisualComposerAbstract")) {
                $errors[] = "WPBakery Page builder";
            }
        }

        if (count($errors) > 0) {
            echo "<p><strong class=\"importer-caution\"><span class=\"dashicons dashicons-info-outline\"></span> " . esc_html__("Install and activate all the following plugins before importing the demo. Install and Activate them through \"Install plugins\" page and import this demo again.", "aventa") . "</strong></p>";

            echo "<ol>";
            foreach ($errors as $error) {
                echo "<li>" . $error . "</li>";
            }
            echo "</ol>";
            return;
        }

        /* Start the process of importing */
        ob_start();

        echo "<ul class=\"rad-importing\">";
        wp_ob_end_flush_all();
        flush();

        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step1", "aventa") . "</strong>" . esc_html__(" : Prepare Importing", "aventa");

        wp_ob_end_flush_all();
        flush();
        $this->rename_pages();
        echo "<br><span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step2", "aventa") . "</strong>" . esc_html__(" : Importing Pages,post,products,menu", "aventa");
        echo "<br>";

        wp_ob_end_flush_all();
        flush();
        $this->importData($import_xml_filepath);
        echo "<br><span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        //Import revolution slider
        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step3", "aventa") . "</strong>" . esc_html__(" : Importing Revolution slider", "aventa");
        wp_ob_end_flush_all();
        flush();
        $this->importRevSlider($demo_name);
        echo "<span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        //Set Reading Options
        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step4", "aventa") . "</strong>" . esc_html__(" : Configure WP ", "aventa");
        wp_ob_end_flush_all();
        flush();
        $this->setReadingOptions();
        echo "<span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        //Change shrotcodes options
        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step5", "aventa") . "</strong>" . esc_html__(" : Processing Shortcodes", "aventa");
        wp_ob_end_flush_all();
        flush();
        $this->processShortcodes();
        echo "<span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        //Update theme options
        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step6", "aventa") . "</strong>" . esc_html__(" : Importing Theme options", "aventa");
        wp_ob_end_flush_all();
        flush();
        $this->setThemeOptions();
        echo "<span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        //change some widget options + replace images with placeholders in widgets
        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step7", "aventa") . "</strong>" . esc_html__(" : Processing Widgets", "aventa");
        wp_ob_end_flush_all();
        flush();
        $this->processWidgets();
        echo "<span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        //Set Primary Navigation
        echo "<li><span class=\"rad-loader\"></span><strong>" . esc_html__("Step8", "aventa") . "</strong>" . esc_html__(" : Processing Menus", "aventa");
        wp_ob_end_flush_all();
        flush();
        $this->setNavigationMenu();
        echo "<span class=\"rad-done\"></span></li>";
        wp_ob_end_flush_all();
        flush();

        $this->refresh_wc();

        set_transient('rad_flush_rules',1);

        echo "<form style=\"text-align: center;\" action=\"" . admin_url("admin.php?page=aventa_demo_importer&amp;step=9") . "\" method=\"post\">";
        echo wp_nonce_field("demo-importer");
        echo "<input type=\"submit\" name=\"submit\" id=\"submit\" class=\"button button-primary\" value=\"" . esc_html__("Save", "aventa") . "\">";
        echo "</form>";

        wp_ob_end_flush_all();
        flush();

        ?>
        </div>
        <?php
    }

    public function importData($import_xml_filepath)
    {
        if (class_exists("Rad_Import")) {
            $rad_Import = new Rad_Import();

            $rad_Import->fetch_attachments = false;

            $rad_Import->import($import_xml_filepath);

        }
    }

    public function setThemeOptions()
    {

        $media_url = RAD_THEME_ASSETS_URI . "/img/placeholder.jpg";
        foreach ($this->theme_data["options"] as $key => $value) {
            $option_values = maybe_unserialize($value);

            if ($key == RAD_OPTIONS_KEY) {
                $options = array();
                foreach ($option_values as $optionkey => $option_value) {
                    if (($optionkey == "footer-newsletter" || $optionkey == "popup-nl-shortcode") && count($this->mc4wp_ids) > 0) {
                        if (strpos($option_value, "[mc4wp_form") > 0) {
                            $option_value = "[mc4wp_form id=\"" . $this->mc4wp_ids[0] . "\"]";
                        }
                    }

                    $option_value        = str_replace("RAD_DEMO_IMAGE", $media_url, $option_value);
                    $options[$optionkey] = $option_value;
                }

                update_option(RAD_OPTIONS_KEY, $options);
            } else {
                $option_values = stripslashes_deep($option_values);
                update_option($key, $option_values);
            }
        }

    }

    private function reset_permalinks()
    {
        global $wp_rewrite;

        //Write the rule
        $wp_rewrite->set_permalink_structure("/%postname%/");

        //Set the option
        update_option("rewrite_rules", false);

        //Flush the rules and tell it to write htaccess
        $wp_rewrite->flush_rules(true);

        flush_rewrite_rules();
    }

    public function processShortcodes()
    {

        $all_categories_ids = array();
        $all_product_ids    = array();
        $cf7_form_id        = -1;
        $newsleter_form_id  = -1;
        $shop_url           = urlencode(get_permalink(wc_get_page_id("shop")));

        //prepare information for category shortcodes
        $args = array(
            "taxonomy"     => "product_cat",
            "orderby"      => "name",
            "show_count"   => 0,
            "pad_counts"   => 0,
            "hierarchical" => 1,
            "title_li"     => "",
            "hide_empty"   => 0,
        );
        $all_categories = get_categories($args);

        foreach ($all_categories as $cat) {
            if ($cat->category_parent == 0) {
                $all_categories_ids[] = $cat->term_id;
            }
        }

        //Get all product ids
        $args = array(
            "fields"      => "ids",
            "post_type"   => array("product"),
            "post_status" => "publish",
        );
        $all_product_ids = get_posts($args);

        //prepare information for contact-form-7 shortcode
        $args = array(
            "numberposts" => -1,
            "post_type"   => "wpcf7_contact_form",
            "post_status" => "publish",
        );
        $cf7_forms = get_posts($args);
        foreach ($cf7_forms as $form) {
            $cf7_form_id = $form->ID;
        }

        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",
                )
            );
            foreach ($forms as $form) {
                $newsleter_form_id = $form->ID;
                $this->mc4wp_ids[] = $form->ID;
            }
        }

        $args = array(
            "sort_order"   => "asc",
            "sort_column"  => "post_title",
            "hierarchical" => 1,
            "exclude"      => "",
            "include"      => "",
            "meta_key"     => "",
            "meta_value"   => "",
            "authors"      => "",
            "child_of"     => 0,
            "parent"       => -1,
            "exclude_tree" => "",
            "number"       => "",
            "offset"       => 0,
            "post_type"    => "page",
            "post_status"  => "publish",
        );
        $pages = get_pages($args);

        $attach_id = -1;
        $attach_url = "";
        $attach_url_len = 0;
        //Process direct image url
        $media             = RAD_THEME_ASSETS_URI . "/img/placeholder.jpg";
        $special_media_url = RAD_THEME_INC_URI . "/admin/demos/" . $this->demo_name . "/special";

        if($this->demo_type == 'el')//Elementor
        {
            $attach_id      = media_sideload_image( $media,null,"placeholder","id");
            $attach_url  = wp_get_attachment_url( $attach_id );
            $attach_url_len = strlen($attach_url);
        }

        foreach ($pages as $page) {
            if ($page->post_content != "") {
                $postContent = $page->post_content;
                $elementor_data = "";

                if($this->demo_type == 'el')//Elementor
                {
                    $elementor_data = get_post_meta( $page->ID, "_elementor_data", true );
                }
                //Process WC categories shortcode
                $occurence_number = substr_count($postContent, "RAD_DEMO_WC_CAT_ID");
                $index            = 0;
                for ($i = 0; $i < $occurence_number; $i++) {
                    if ($index >= count($all_categories_ids)) {
                        $index = 0;
                    }

                    $postContent = preg_replace("/RAD_DEMO_WC_CAT_ID/", $all_categories_ids[$index], $postContent, 1);
                    if($this->demo_type == 'el')//Elementor
                    {
                        $elementor_data = preg_replace("/RAD_DEMO_WC_CAT_ID/", $all_categories_ids[$index], $elementor_data, 1);
                    }

                    $index++;
                }

                //Process WC products shortcode
                $occurence_number = substr_count($postContent, "RAD_DEMO_WC_PRODUCT_ID");
                $index            = 0;
                for ($i = 0; $i < $occurence_number; $i++) {
                    if ($index >= count($all_product_ids)) {
                        $index = 0;
                    }

                    $postContent = preg_replace("/RAD_DEMO_WC_PRODUCT_ID/", $all_product_ids[$index], $postContent, 1);
                    if($this->demo_type == 'el')//Elementor
                    {
                        $elementor_data = preg_replace("/RAD_DEMO_WC_PRODUCT_ID/", $all_product_ids[$index], $elementor_data, 1);
                    }

                    $index++;
                }

                $postContent       = preg_replace("/RAD_DEMO_SPECIAL_IMAGE1/", $special_media_url . "1.png", $postContent);
                $postContent       = preg_replace("/RAD_DEMO_SPECIAL_IMAGE2/", $special_media_url . "2.png", $postContent);
                $postContent       = preg_replace("/RAD_DEMO_SPECIAL_IMAGE3/", $special_media_url . "3.png", $postContent);
                $postContent       = preg_replace("/RAD_DEMO_SPECIAL_IMAGE4/", $special_media_url . "4.png", $postContent);
                $postContent       = preg_replace("/RAD_DEMO_IMAGE/", $media, $postContent);

                //Process contact form shortcodes
                if ($cf7_form_id != -1) {
                    $postContent = preg_replace("/RAD_DEMO_CF7_ID/", $cf7_form_id, $postContent);
                    if($this->demo_type == 'el')//Elementor
                    {
                        $elementor_data = preg_replace("/RAD_DEMO_CF7_ID/", $cf7_form_id, $elementor_data);
                    }
                }

                //process newsletter shortcode
                if ($newsleter_form_id != -1) {
                    $postContent = preg_replace("/RAD_DEMO_NEWSLETTER_ID/", $newsleter_form_id, $postContent);
                    if($this->demo_type == 'el')//Elementor
                    {
                        $elementor_data = preg_replace("/RAD_DEMO_NEWSLETTER_ID/", $newsleter_form_id, $elementor_data);
                    }
                }

                $new_post = array(
                    "ID"           => $page->ID,
                    "post_type"    => "page",
                    "post_content" => $postContent,
                );

                


                if($this->demo_type == 'el')//Elementor
                {
                    $elementor_data = preg_replace("/RAD_DEMO_ID_IMAGE/", $attach_id, $elementor_data);
                    $elementor_data = preg_replace("/RAD_DEMO_IMAGE/", $attach_url, $elementor_data);
                    $elementor_data = wp_slash($elementor_data);// Double scaping to prevent from destroying data
                    update_post_meta($page->ID, "_elementor_data",$elementor_data);

                    $elementor_page_settings = maybe_serialize(get_post_meta( $page->ID, "_elementor_page_settings", true ));
                    $elementor_page_settings = preg_replace("/s:([1-9][0-9]*):\"RAD_DEMO_IMAGE\"/", "s:" . $attach_url_len . ':"'. $attach_url . '"', $elementor_page_settings);
                    $elementor_page_settings = maybe_unserialize($elementor_page_settings);
                    update_post_meta($page->ID, "_elementor_page_settings",$elementor_page_settings);

                }

                wp_update_post($new_post);
            }
        }
    }

    public function importRevSlider($demo_name)
    {
        // Get the xml file from directory
        $import_path       = RAD_THEME_INC . "/admin/demos/" . $demo_name . "/";
        $import_rev_slider = $import_path . "revslider.zip";

        # Import revolution Slider
        if ((file_exists($import_rev_slider))) {
            if (is_file($import_rev_slider)) {
                if (class_exists("RevSliderSliderImport")) {
                    $slider   = new RevSliderSliderImport();
                    $response = $slider->import_slider(true, $import_rev_slider);
                }
            }
        } else {
            echo ": <strong>" . esc_html__("This demo does not have any Revolution slider", "aventa") . "</strong>";
        }
    }

    public function setNavigationMenu()
    {

        $locations     = get_registered_nav_menus();
        $new_locations = array();
        $menus         = wp_get_nav_menus();

        for ($i = 0; $i < count($menus); $i++) {
            if ($menus[$i]->slug == "footer-nav1") {
                if (isset($locations["footer-nav1"])) {
                    $new_locations["footer-nav1"] = (int) ($menus[$i]->term_id);
                }
            } elseif ($menus[$i]->slug == "footer-nav2") {
                if (isset($locations["footer-nav2"])) {
                    $new_locations["footer-nav2"] = (int) ($menus[$i]->term_id);
                }
            } elseif ($menus[$i]->slug == "primary-nav") {
                if (isset($locations["primary-nav"])) {
                    $new_locations["primary-nav"] = (int) ($menus[$i]->term_id);
                }
            } elseif ($menus[$i]->slug == "mobile-nav") {
                if (isset($locations["mobile-nav"])) {
                    $new_locations["mobile-nav"] = (int) ($menus[$i]->term_id);
                }
            } elseif ($menus[$i]->slug == "hamburger-main-nav") {
                if (isset($locations["hamburger-main-nav"])) {
                    $new_locations["hamburger-main-nav"] = (int) ($menus[$i]->term_id);
                }
            } elseif ($menus[$i]->slug == "hamburger-second-nav") {
                if (isset($locations["hamburger-second-nav"])) {
                    $new_locations["hamburger-second-nav"] = (int) ($menus[$i]->term_id);
                }
            }
        }
        set_theme_mod("nav_menu_locations", $new_locations);

    }

    public function processWidgets()
    {
        $widget_menus = get_option("widget_nav_menu");

        $args = array(
            "slug" => "widget-menu",
        );
        $menu = wp_get_nav_menus($args);

        if ($widget_menus !== false && count($menu) > 0) {

            foreach ($widget_menus as $key => $widget_menu) {

                // The option already exists, so we just update it.
                if (isset($widget_menu["nav_menu"])) {
                    $widget_menu["nav_menu"] = (int) ($menu[0]->term_id);
                    $widget_menus[$key]      = $widget_menu;
                }

            }

        }
        update_option("widget_nav_menu", $widget_menus);

        //Use placeholder images in text widgets
        $text_widgets = get_option("widget_text");
        $media        = RAD_THEME_ASSETS_URI . "/img/placeholder.jpg";
        if (is_array($text_widgets)) {
            foreach ($text_widgets as $key => $text_widget) {

                if (isset($text_widget["text"])) {
                    $text_widget["text"] = str_replace("RAD_DEMO_IMAGE", $media, $text_widget["text"]);
                    $text_widgets[$key]  = $text_widget;
                }

            }
        }

        update_option("widget_text", $text_widgets);

        //Use placeholder images in  custom html widget
        $custom_html_widgets = get_option("widget_custom_html");
        $media               = RAD_THEME_ASSETS_URI . "/img/placeholder.jpg";
        if (is_array($custom_html_widgets)) {
            foreach ($custom_html_widgets as $key => $custom_html_widget) {

                if (isset($custom_html_widget["content"])) {
                    $custom_html_widget["content"] = str_replace("RAD_DEMO_IMAGE", $media, $custom_html_widget["content"]);
                    $custom_html_widgets[$key]     = $custom_html_widget;
                }

            }
        }

        update_option("widget_custom_html", $custom_html_widgets);

        //Use placeholder images in media widgets
        $media_image_widgets = get_option("widget_media_image");
        if (is_array($media_image_widgets)) {
            foreach ($media_image_widgets as $key => $media_image_widget) {

                if (isset($media_image_widget["url"])) {
                    $media_image_widget["url"] = str_replace("RAD_DEMO_IMAGE", $media, $media_image_widget["url"]);
                    $media_image_widgets[$key] = $media_image_widget;
                }

            }
        }

        update_option("widget_media_image", $media_image_widgets);

        //Use placeholder images in video widgets
        $rad_video_widgets = get_option("widget_rad_video");
        if (is_array($rad_video_widgets)) {
            foreach ($rad_video_widgets as $key => $video_widget) {

                if (isset($video_widget["video_poster_image"])) {
                    $video_widget["video_poster_image"] = str_replace("RAD_DEMO_IMAGE", $media, $video_widget["video_poster_image"]);
                    $video_widget[$key]                 = $video_widget;
                }

                if (isset($video_widget["video_background_image"])) {
                    $video_widget["video_background_image"] = str_replace("RAD_DEMO_IMAGE", $media, $video_widget["video_background_image"]);
                    $rad_video_widgets[$key]                = $video_widget;
                }

            }
        }

        update_option("widget_rad_video", $rad_video_widgets);

        //Use placeholder images in woocommerce_layered_nav widgets
        $layered_nav__widgets = get_option("widget_woocommerce_layered_nav");
        $random_image         = RAD_THEME_ASSETS_URI . "/img/placeholder.jpg";
        if (is_array($layered_nav__widgets)) {
            foreach ($layered_nav__widgets as $key => $layered_nav__widget) {

                if (isset($layered_nav__widget["values"])) {
                    foreach ($layered_nav__widget["values"] as $val_key => $val_val) {

                        $layered_nav__widget["values"][$val_key] = str_replace("RAD_DEMO_IMAGE", $random_image, $layered_nav__widget["values"][$val_key]);

                    }

                    $layered_nav__widgets[$key] = $layered_nav__widget;
                }

            }
        }

        update_option("widget_woocommerce_layered_nav", $layered_nav__widgets);

    }

    public function rename_pages()
    {
        $shop_page = get_page_by_title("Shop");
        if (is_array($shop_page)) {
            $shop_page = $shop_page[0];
        }

        $new_post = array(
            "ID"         => $shop_page->ID,
            "post_title" => $shop_page->post_title . "_renamed",
        );

        wp_update_post($new_post);
        wp_reset_postdata();
    }

    public function setReadingOptions()
    {

        //Front page displays : A static page
        update_option("show_on_front", "page");

        //Get ID of pages
        $home_page = get_page_by_title("Home");
        if (is_array($home_page)) {
            $home_page = $home_page[0];
        }
        wp_reset_postdata();

        $blog_page = get_page_by_title("Blog");
        if (is_array($blog_page)) {
            $blog_page = $blog_page[0];
        }
        wp_reset_postdata();

        $shop_page = get_page_by_title("Shop");
        if (is_array($shop_page)) {
            $shop_page = $shop_page[0];
        }
        wp_reset_postdata();

        $cart_page = get_page_by_title("Cart");
        if (is_array($cart_page)) {
            $cart_page = $cart_page[0];
        }
        wp_reset_postdata();

        $checkout_page = get_page_by_title("Checkout");
        if (is_array($checkout_page)) {
            $checkout_page = $checkout_page[0];
        }
        wp_reset_postdata();

        $account_page = get_page_by_title("My Account");
        if (is_array($account_page)) {
            $account_page = $account_page[0];
        }
        wp_reset_postdata();

        if ($home_page) {
            $page_on_front = $home_page->ID;
        }

        //check if page_on_front is shop or blog
        if (isset($this->theme_data["frontpage_options"])) {

            if ($this->theme_data["frontpage_options"]["front_page"] == "shop") {
                $page_on_front = $shop_page->ID;
            } elseif ($this->theme_data["frontpage_options"]["front_page"] == "blog") {
                $page_on_front = $blog_page->ID;
            } else {
                $page_on_front = $home_page->ID;
            }
        }

        if (isset($page_on_front)) {
            update_option("page_on_front", $page_on_front);
        }

        if (isset($blog_page)) {
            update_option("page_for_posts", $blog_page->ID);
        }

        if (isset($shop_page)) {
            update_option("woocommerce_shop_page_id", $shop_page->ID);
        }

        if (isset($cart_page)) {
            update_option("woocommerce_cart_page_id", $cart_page->ID);
        }

        if (isset($checkout_page)) {
            update_option("woocommerce_checkout_page_id", $checkout_page->ID);
        }

        if (isset($account_page)) {
            update_option("woocommerce_myaccount_page_id", $account_page->ID);
        }
    }

    public function dispatch()
    {
        $step = empty($_GET["step"]) ? 0 : (int) $_GET["step"];

        switch ($step) {
            case 0:
                $this->importer_page();
                break;
            case 1:
                check_admin_referer("demo-importer");
                $this->importer_ready();
                break;
            case 2:
                check_admin_referer("demo-importer");
                $this->importer_start();
                break;
            case 9:
                check_admin_referer("demo-importer");
                $this->importer_end();
                break;
        }
    }

    public function importer_ready()
    {
        ?>
        <div id="rad-importer-box">
            <div class="rad-importer-header">
                <div class="logo">
                    <?php echo "<img src=\"" . RAD_THEME_INC_URI . "/admin/assets/img/logo.jpg" . "\">"; ?>
                    <span class="version"><?php echo esc_html(RAD_THEME_VERSION); ?></span>
                </div>
            </div>

            <div class="box-title" style="text-align: center;">
                <img width="50%" src="<?php echo RAD_THEME_INC_URI . "/admin/assets/img/import.png"; ?>">
            </div>
            <br>
            <br>
            <form style="text-align: center;" action="<?php echo admin_url("admin.php?page=aventa_demo_importer&amp;step=2"); ?>" method="post">
                <?php wp_nonce_field("demo-importer");?>
                <input type="hidden" id="demo_name" name="demo_name" value="<?php echo esc_attr($_POST["demo_name"]); ?>">
                <input type="radio" name="demo_type" value="vc"><?php echo esc_html__("WPBakery Version", "aventa") ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="radio" name="demo_type" value="el"><?php echo esc_html__("Elementor Version", "aventa") ?><br><br>
                <input type="submit" name="submit" id="submit" class="button button-primary" value="<?php echo esc_html__("Start Importing", "aventa") ?>">
            </form>
        </div>
    <?php
    }

    public function importer_page()
    {
        ?>
        <div id="rad-importer-box">
            <div class="rad-importer-header">
                <div class="logo">
                    <?php echo "<img src=\"" . RAD_THEME_INC_URI . "/admin/assets/img/logo.jpg" . "\">"; ?>
                    <span class="version"><?php echo esc_html(RAD_THEME_VERSION); ?></span>
                </div>
            </div>
            <div class="box-title">
                <h2><?php esc_html_e("Demo Importer", "aventa");?> </h2>
            </div>
            <form action="<?php echo admin_url("admin.php?page=aventa_demo_importer&amp;step=1"); ?>" method="post">
                <?php wp_nonce_field("demo-importer");?>
                <input type="hidden" id="demo_name" name="demo_name" value="demo1">
            <!-- Display demos -->
            <div id="demo-container">
                <?php
        foreach ($this->demos as $demo => $options) {
            echo "<div class=\"demo\">
                    <img src=\"" . RAD_THEME_INC_URI . "/admin/demos/" . $demo . "/thumb.jpg\" />
                    <div class=\"description\">
                        <h3 class=\"demo-name\">" . $options["title"] . "</h3>
                        <p>" . $options["description"] . "</p>
                        <a target=\"_blank\" href=\"#\" class=\"button import\" data-demo=\"" . $demo . "\">" . esc_html__("Import", "aventa") . "</a>
                        <a target=\"_blank\" href=\"" . $options["link"] . "\" class=\"button\">" . esc_html__("Preview", "aventa") . "</a>
                    </div>
                </div>";
        }

        ?>
                </div>
            </form>
        </div>

     <?php

    }

    public function refresh_wc()
    {
        if (class_exists("woocommerce")) {
            // reset transients for products
            if (function_exists("wc_delete_product_transients")) {
                wc_delete_product_transients();
            } else {
                global $woocommerce;
                $woocommerce->clear_product_transients();
            }

            if (!wc_update_product_lookup_tables_is_running()) {
                wc_update_product_lookup_tables();
            }

        }
    }

}

// instantiate class
$GLOBALS["rad_Importer"] = new rad_Importer();

?>