<?php 
if (isset($_GET['import-demo']) && $_GET['import-demo'] == true) {

    // Function to install and activate plugins
    function appliances_store_import_demo_content() {

        // Display the preloader only for plugin installation
        echo '<div id="plugin-loader" style="display: flex; align-items: center; justify-content: center; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999;">
                <img src="' . esc_url(get_template_directory_uri()) . '/assets/images/loader.png" alt="Loading..." width="60" height="60" />
              </div>';
              
        // Define the plugins you want to install and activate
        $plugins = array(
            array(
                'slug' => 'woocommerce',
                'file' => 'woocommerce/woocommerce.php',
                'url'  => 'https://downloads.wordpress.org/plugin/woocommerce.latest-stable.zip'
            ),
             array(
                'slug' => 'yith-woocommerce-wishlist',
                'file' => 'yith-woocommerce-wishlist/init.php',
                'url'  => 'https://downloads.wordpress.org/plugin/yith-woocommerce-wishlist.latest-stable.zip'
            ),
            array(
                'slug' => 'currency-switcher-woocommerce',
                'file' => 'currency-switcher-woocommerce/currency-switcher-woocommerce.php',
                'url'  => 'https://downloads.wordpress.org/plugin/currency-switcher-woocommerce.latest-stable.zip'
            ),
            array(
                'slug' => 'gtranslate',
                'file' => 'gtranslate/gtranslate.php',
                'url'  => 'https://downloads.wordpress.org/plugin/gtranslate.latest-stable.zip' // Correct GTranslate URL
            ),
            array(
                'slug' => 'advanced-appointment-booking-scheduling',
                'file' => 'advanced-appointment-booking-scheduling/advanced-appointment-booking.php',
                'url'  => 'https://downloads.wordpress.org/plugin/advanced-appointment-booking-scheduling.zip'
            ),
        );

        // Include required files for plugin installation
        include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
        include_once(ABSPATH . 'wp-admin/includes/file.php');
        include_once(ABSPATH . 'wp-admin/includes/misc.php');
        include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');

        // Loop through each plugin
        foreach ($plugins as $plugin) {
            $plugin_file = WP_PLUGIN_DIR . '/' . $plugin['file'];

            // Check if the plugin is installed
            if (!file_exists($plugin_file)) {
                // If the plugin is not installed, download and install it
                $upgrader = new Plugin_Upgrader();
                $result = $upgrader->install($plugin['url']);

                // Check for installation errors
                if (is_wp_error($result)) {
                    error_log('Plugin installation failed: ' . $plugin['slug'] . ' - ' . $result->get_error_message());
                    echo 'Error installing plugin: ' . esc_html($plugin['slug']) . ' - ' . esc_html($result->get_error_message());
                    continue;
                }
            }

            // If the plugin exists but is not active, activate it
            if (file_exists($plugin_file) && !is_plugin_active($plugin['file'])) {
                $result = activate_plugin($plugin['file']);

                // Check for activation errors
                if (is_wp_error($result)) {
                    error_log('Plugin activation failed: ' . $plugin['slug'] . ' - ' . $result->get_error_message());
                    echo 'Error activating plugin: ' . esc_html($plugin['slug']) . ' - ' . esc_html($result->get_error_message());
                }
            }
        }

        // Hide the preloader after the process is complete
        echo '<script type="text/javascript">
                document.getElementById("plugin-loader").style.display = "none";
              </script>';

        // Add filter to skip WooCommerce setup wizard after activation
        add_filter('woocommerce_prevent_automatic_wizard_redirect', '__return_true');
    }

    // Call the import function
    appliances_store_import_demo_content();

    // ------- Create Nav Menu --------
$appliances_store_menuname = 'Main Menus';
$appliances_store_bpmenulocation = 'primary-menu';
$appliances_store_menu_exists = wp_get_nav_menu_object($appliances_store_menuname);

if (!$appliances_store_menu_exists) {
    $appliances_store_menu_id = wp_create_nav_menu($appliances_store_menuname);

    // Create Home Page
    $appliances_store_home_title = 'Home';
    $appliances_store_home = array(
        'post_type' => 'page',
        'post_title' => $appliances_store_home_title,
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'home'
    );
    $appliances_store_home_id = wp_insert_post($appliances_store_home);

    // Assign Home Page Template
    add_post_meta($appliances_store_home_id, '_wp_page_template', 'page-template/front-page.php');

    // Update options to set Home Page as the front page
    update_option('page_on_front', $appliances_store_home_id);
    update_option('show_on_front', 'page');

    // Add Home Page to Menu
    wp_update_nav_menu_item($appliances_store_menu_id, 0, array(
        'menu-item-title' => __('Home', 'appliances-store'),
        'menu-item-classes' => 'home',
        'menu-item-url' => home_url('/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $appliances_store_home_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create About Us Page with Dummy Content
    $appliances_store_about_title = 'About Us';
    $appliances_store_about_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam...<br>

             Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br> 

                There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text.<br> 

                All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.';
    $appliances_store_about = array(
        'post_type' => 'page',
        'post_title' => $appliances_store_about_title,
        'post_content' => $appliances_store_about_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'about-us'
    );
    $appliances_store_about_id = wp_insert_post($appliances_store_about);

    // Add About Us Page to Menu
    wp_update_nav_menu_item($appliances_store_menu_id, 0, array(
        'menu-item-title' => __('About Us', 'appliances-store'),
        'menu-item-classes' => 'about-us',
        'menu-item-url' => home_url('/about-us/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $appliances_store_about_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Services Page with Dummy Content
    $appliances_store_services_title = 'Services';
    $appliances_store_services_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam...<br>

             Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br> 

                There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text.<br> 

                All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.';
    $appliances_store_services = array(
        'post_type' => 'page',
        'post_title' => $appliances_store_services_title,
        'post_content' => $appliances_store_services_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'services'
    );
    $appliances_store_services_id = wp_insert_post($appliances_store_services);

    // Add Services Page to Menu
    wp_update_nav_menu_item($appliances_store_menu_id, 0, array(
        'menu-item-title' => __('Services', 'appliances-store'),
        'menu-item-classes' => 'services',
        'menu-item-url' => home_url('/services/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $appliances_store_services_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Pages Page with Dummy Content
    $appliances_store_pages_title = 'Pages';
    $appliances_store_pages_content = '<h2>Our Pages</h2>
    <p>Explore all the pages we have on our website. Find information about our services, company, and more.</p>';
    $appliances_store_pages = array(
        'post_type' => 'page',
        'post_title' => $appliances_store_pages_title,
        'post_content' => $appliances_store_pages_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'pages'
    );
    $appliances_store_pages_id = wp_insert_post($appliances_store_pages);

    // Add Pages Page to Menu
    wp_update_nav_menu_item($appliances_store_menu_id, 0, array(
        'menu-item-title' => __('Pages', 'appliances-store'),
        'menu-item-classes' => 'pages',
        'menu-item-url' => home_url('/pages/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $appliances_store_pages_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Contact Page with Dummy Content
    $appliances_store_contact_title = 'Contact';
    $appliances_store_contact_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam...<br>

             Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br> 

                There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which dont look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isnt anything embarrassing hidden in the middle of text.<br> 

                All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.';
    $appliances_store_contact = array(
        'post_type' => 'page',
        'post_title' => $appliances_store_contact_title,
        'post_content' => $appliances_store_contact_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'contact'
    );
    $appliances_store_contact_id = wp_insert_post($appliances_store_contact);

    // Add Contact Page to Menu
    wp_update_nav_menu_item($appliances_store_menu_id, 0, array(
        'menu-item-title' => __('Contact', 'appliances-store'),
        'menu-item-classes' => 'contact',
        'menu-item-url' => home_url('/contact/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $appliances_store_contact_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Set the menu location if it's not already set
    if (!has_nav_menu($appliances_store_bpmenulocation)) {
        $locations = get_theme_mod('nav_menu_locations'); // Use 'nav_menu_locations' to get locations array
        if (empty($locations)) {
            $locations = array();
        }
        $locations[$appliances_store_bpmenulocation] = $appliances_store_menu_id;
        set_theme_mod('nav_menu_locations', $locations);
    }
}

        //---Header--//
        set_theme_mod('appliances_store_track_order_button_sec', 'Tracking Order');
        set_theme_mod('appliances_store_track_order_link_sec', '#');
        set_theme_mod('appliances_store_header_call_text', '24/7 Support');
        set_theme_mod('appliances_store_header_call_no', '+112233445566');

        // slider Section
        set_theme_mod('appliances_store_slider_short_heading', 'Upcoming Offer 30% Off');

        set_theme_mod('appliances_store_product_clock_timer_end', 'March 30 2026 11:00:00');

        // Create About page and set the featured image
        $appliances_store_abt_title = 'Upcoming Best Offers Electronics Store';
        $appliances_store_abt_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

        $my_post = array(
            'post_title'    => wp_strip_all_tags($appliances_store_abt_title),
            'post_content'  => $appliances_store_abt_content,
            'post_status'   => 'publish',
            'post_type'     => 'page',
        );

        // Insert the post into the database
        $post_id = wp_insert_post($my_post);

        if ($post_id) {
            // Set the theme mod for the About page
            set_theme_mod('appliances_store_slider_page', $post_id);

            // Sideload image and set as the featured image
            $image_url = get_template_directory_uri() . '/assets/images/slider-img.png';
            $image_id = media_sideload_image($image_url, $post_id, null, 'id');

            if (!is_wp_error($image_id)) {
                set_post_thumbnail($post_id, $image_id);
            }
        }

        // top banner
        set_theme_mod('appliances_store_discount_sale_img1',  get_template_directory_uri().'/assets/images/banner1.png' );
        set_theme_mod('appliances_store_product_sale_discount_title1', 'DU-1181N sewing machine');
        set_theme_mod('appliances_store_product_btn_text1', 'Go Shop');
        set_theme_mod('appliances_store_product_btn_link1', '#');
        set_theme_mod('appliances_store_product_sale_discount', '15%');

        // banner 1
        set_theme_mod('appliances_store_product_banner_one',  get_template_directory_uri().'/assets/images/banner1.png' );
        set_theme_mod('appliances_store_product_banner_one_title1', 'Hand tool Circular saw Power tool');
        set_theme_mod('appliances_store_product_banner_one_btn_text1', 'Go Shop');
        set_theme_mod('appliances_store_product_banner_one_btn_link1', '#');

        // banner 2
        set_theme_mod('appliances_store_product_banner_two',  get_template_directory_uri().'/assets/images/banner2.png' );
        set_theme_mod('appliances_store_product_banner_two_title1', 'Mixer Juicer Havells Home appliance');
        set_theme_mod('appliances_store_banner_sec_discount', '15%');

        // banner 3
        set_theme_mod('appliances_store_product_banner_three', get_template_directory_uri().'/assets/images/banner3.png' );
        set_theme_mod('appliances_store_product_banner_three_title1', 'DU-1181N sewing machine');
        set_theme_mod('appliances_store_product_banner_three_btn_text1', 'Go Shop');
        set_theme_mod('appliances_store_product_banner_three_btn_link1', '#');

        // Main product category sec

        // Single Product
        $appliances_store_title = "Lorem ipsum dolor sit";
        // Check if a product with this title already exists using WP_Query
        $args = array(
            'post_type'      => 'product',
            'title'          => $appliances_store_title,
            'posts_per_page' => 1
        );
        $existing_product_query = new WP_Query($args);

        if ($existing_product_query->have_posts()) {
            $existing_product_query->the_post();
            $appliances_store_post_id = get_the_ID();
            wp_reset_postdata();
        } else {
            // Create a new product
            $appliances_store_my_post = array(
                'post_title'    => wp_strip_all_tags($appliances_store_title),
                'post_status'   => 'publish',
                'post_type'     => 'product',
                'post_content'  => 'This is a sample product description.',
            );

            // Insert the product into the database
            $appliances_store_post_id = wp_insert_post($appliances_store_my_post);

            if (is_wp_error($appliances_store_post_id)) {
                error_log('Error creating product: ' . $appliances_store_post_id->get_error_message());
                return; // Stop execution if product creation fails
            }

            // Set product type as "simple"
            wp_set_object_terms($appliances_store_post_id, 'simple', 'product_type');

            // Set product metadata
            update_post_meta($appliances_store_post_id, '_regular_price', '140'); // Regular price
            update_post_meta($appliances_store_post_id, '_sale_price', '139'); // Sale price
            update_post_meta($appliances_store_post_id, '_price', '139'); // Final price shown

            // Handle featured image
            $appliances_store_image_url = get_template_directory_uri() . '/assets/images/single-product.png';
            $appliances_store_image_id = media_sideload_image($appliances_store_image_url, $appliances_store_post_id, null, 'id');

            if (!is_wp_error($appliances_store_image_id)) {
                set_post_thumbnail($appliances_store_post_id, $appliances_store_image_id);
            } else {
                error_log('Error downloading image: ' . $appliances_store_image_id->get_error_message());
            }
        }

        // Store product ID in theme settings
        set_theme_mod('appliances_store_shop_slider_product', $appliances_store_post_id);

        // Display "Add to Cart" button (for use in a template file)
        echo '<a href="' . esc_url(wc_get_checkout_url() . '?add-to-cart=' . $appliances_store_post_id) . '" class="button add-to-cart">'
            . esc_html__('Add to Cart', 'appliances-store') . '</a>';

        // main Shop Category Section
        set_theme_mod('appliances_store_projetcs_main_heading', 'Our Categories');
        set_theme_mod('appliances_store_projetcs_number', '6');
        set_theme_mod('appliances_store_services_icon1', 'fas fa-mobile-alt');
        set_theme_mod('appliances_store_services_icon2', 'far fa-camera');
        set_theme_mod('appliances_store_services_icon3', 'fas fa-plug');
        set_theme_mod('appliances_store_services_icon4', 'fas fa-volume-up');
        set_theme_mod('appliances_store_services_icon5', 'fas fa-headphones');
        set_theme_mod('appliances_store_services_icon6', 'far fa-camera');

        $appliances_store_tab_text_array = array(
            "Smart Phone", "Cameras", "Accessories", 
            "Speakers", "Headphones", "Cameras"
        );
        $appliances_store_category_names = array(
            "productcat1", "productcat2", "productcat3", 
            "productcat4", "productcat5", "productcat6"
        );
        $appliances_store_title_array = array_fill(0, 6, array(
            "Lorem ipsum dolor sit amet", "Lorem ipsum dolor sit amet", "Lorem ipsum dolor sit amet"
        ));

        for ($appliances_store_tab_index = 1; $appliances_store_tab_index <= 6; $appliances_store_tab_index++) {
            // Set theme mod for each tab text
            $theme_mod_key = 'appliances_store_projetcs_text' . $appliances_store_tab_index;
            $theme_mod_value = $appliances_store_tab_text_array[$appliances_store_tab_index - 1];
            set_theme_mod($theme_mod_key, $theme_mod_value);

            // Set the category for this tab
            $current_category = $appliances_store_category_names[$appliances_store_tab_index - 1];
            set_theme_mod('appliances_store_projetcs_category' . $appliances_store_tab_index, $current_category);

            // Create or retrieve the post category term ID
            $appliances_store_term = term_exists($current_category, 'product_cat');
            
            // If the term doesn't exist, create it
            if (!$appliances_store_term) {
                $appliances_store_term = wp_insert_term($current_category, 'product_cat');
            }

            if (is_wp_error($appliances_store_term)) {
                error_log('Error creating category: ' . $appliances_store_term->get_error_message());
                continue; // Skip to the next iteration if category creation fails
            }

            $term_id = is_array($appliances_store_term) ? $appliances_store_term['term_id'] : $appliances_store_term;

            for ($appliances_store_i = 0; $appliances_store_i < 3; $appliances_store_i++) {
                // Create post content (product title)
                $appliances_store_title = $appliances_store_title_array[$appliances_store_tab_index - 1][$appliances_store_i];

                // Create post object
                $appliances_store_my_post = array(
                    'post_title'    => wp_strip_all_tags($appliances_store_title),
                    'post_status'   => 'publish',
                    'post_type'     => 'product', // Ensure this is set to 'product' post type
                );

                // Insert the post into the database
                $appliances_store_post_id = wp_insert_post($appliances_store_my_post);

                if (is_wp_error($appliances_store_post_id)) {
                    error_log('Error creating post: ' . $appliances_store_post_id->get_error_message());
                    continue; // Skip to the next post if creation fails
                }

                // Assign the category to the post
                wp_set_object_terms($appliances_store_post_id, $term_id, 'product_cat');

                // Add product meta (price, etc.)
                update_post_meta($appliances_store_post_id, '_regular_price', '140'); // Regular price
                update_post_meta($appliances_store_post_id, '_sale_price', '139'); // Sale price
                update_post_meta($appliances_store_post_id, '_price', '139'); // Final price shown

                // Handle the featured image using media_sideload_image
                $appliances_store_image_url = get_template_directory_uri() . '/assets/images/product-img' . ($appliances_store_i + 1) . '.png';
                $appliances_store_image_id = media_sideload_image($appliances_store_image_url, $appliances_store_post_id, null, 'id');

                if (is_wp_error($appliances_store_image_id)) {
                    error_log('Error downloading image: ' . $appliances_store_image_id->get_error_message());
                    continue; // Skip to the next post if image download fails
                }

                // Assign the featured image to the post
                set_post_thumbnail($appliances_store_post_id, $appliances_store_image_id);
            }
        }

    }
?>