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

    // Function to install and activate plugins
    function carpenter_workshop_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'
            ),
        );

        // Include required files for plugin installation
        if (!function_exists('plugins_api')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
        }
        if (!function_exists('activate_plugin')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin.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());
                    continue;
                }
            }

            // If the plugin folder exists but the plugin 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());
                }
            }
        }

        // 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
    carpenter_workshop_import_demo_content();
    
    // ------- Create Nav Menu --------
$carpenter_workshop_menuname = 'Main Menus';
$carpenter_workshop_bpmenulocation = 'primary-menu';
$carpenter_workshop_menu_exists = wp_get_nav_menu_object($carpenter_workshop_menuname);

if (!$carpenter_workshop_menu_exists) {
    $carpenter_workshop_menu_id = wp_create_nav_menu($carpenter_workshop_menuname);

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

    // Assign Home Page Template
    add_post_meta($carpenter_workshop_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', $carpenter_workshop_home_id);
    update_option('show_on_front', 'page');

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

    // Create About Us Page with Dummy Content
    $carpenter_workshop_about_title = 'About Us';
    $carpenter_workshop_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.';
    $carpenter_workshop_about = array(
        'post_type' => 'page',
        'post_title' => $carpenter_workshop_about_title,
        'post_content' => $carpenter_workshop_about_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'about-us'
    );
    $carpenter_workshop_about_id = wp_insert_post($carpenter_workshop_about);

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

    // Create Services Page with Dummy Content
    $carpenter_workshop_services_title = 'Services';
    $carpenter_workshop_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.';
    $carpenter_workshop_services = array(
        'post_type' => 'page',
        'post_title' => $carpenter_workshop_services_title,
        'post_content' => $carpenter_workshop_services_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'services'
    );
    $carpenter_workshop_services_id = wp_insert_post($carpenter_workshop_services);

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

    // Create Pages Page with Dummy Content
    $carpenter_workshop_pages_title = 'Pages';
    $carpenter_workshop_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>';
    $carpenter_workshop_pages = array(
        'post_type' => 'page',
        'post_title' => $carpenter_workshop_pages_title,
        'post_content' => $carpenter_workshop_pages_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'pages'
    );
    $carpenter_workshop_pages_id = wp_insert_post($carpenter_workshop_pages);

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

    // Create Contact Page with Dummy Content
    $carpenter_workshop_contact_title = 'Contact';
    $carpenter_workshop_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.';
    $carpenter_workshop_contact = array(
        'post_type' => 'page',
        'post_title' => $carpenter_workshop_contact_title,
        'post_content' => $carpenter_workshop_contact_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'contact'
    );
    $carpenter_workshop_contact_id = wp_insert_post($carpenter_workshop_contact);

    // Add Contact Page to Menu
    wp_update_nav_menu_item($carpenter_workshop_menu_id, 0, array(
        'menu-item-title' => __('Contact', 'carpenter-workshop'),
        'menu-item-classes' => 'contact',
        'menu-item-url' => home_url('/contact/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $carpenter_workshop_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($carpenter_workshop_bpmenulocation)) {
        $locations = get_theme_mod('nav_menu_locations'); // Use 'nav_menu_locations' to get locations array
        if (empty($locations)) {
            $locations = array();
        }
        $locations[$carpenter_workshop_bpmenulocation] = $carpenter_workshop_menu_id;
        set_theme_mod('nav_menu_locations', $locations);
    }
}

        //---Header--//
        set_theme_mod('carpenter_workshop_header_search_notification_icon_url', '#');

        // Set theme mods for the slider section
        set_theme_mod('carpenter_workshop_slider_arrows', true);
        set_theme_mod('carpenter_workshop_slider_short_heading', 'Best Furniture For Your Castle....');
        set_theme_mod('carpenter_workshop_main_product_slider_category_setting', 'productcategory');

        // Define product category name and titles
        $carpenter_workshop_category_name = 'productcategory';
        $carpenter_workshop_titles = array(
            'New Furniture Collection Trends in 2020',
            'Elegant Wooden Furniture for Your Living Room',
            'Modern Style Furniture Sets on Sale',
            'Handcrafted Wooden Chairs & Tables'
        );

        // Create or retrieve the product category
        $carpenter_workshop_term = term_exists($carpenter_workshop_category_name, 'product_cat');
        if ($carpenter_workshop_term === 0 || $carpenter_workshop_term === null) {
            $carpenter_workshop_term = wp_insert_term($carpenter_workshop_category_name, 'product_cat');
        }

        if (is_wp_error($carpenter_workshop_term)) {
            error_log('Error creating category: ' . $carpenter_workshop_term->get_error_message());
            return;
        }

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

        // Loop to create 4 products
        foreach ($carpenter_workshop_titles as $carpenter_workshop_title) {

            // Create product post object
            $carpenter_workshop_my_post = array(
                'post_title'   => wp_strip_all_tags($carpenter_workshop_title),
                'post_content' => 'This is a demo product created for the slider section.',
                'post_status'  => 'publish',
                'post_type'    => 'product',
            );

            // Insert the product into the database
            $carpenter_workshop_post_id = wp_insert_post($carpenter_workshop_my_post);

            if (is_wp_error($carpenter_workshop_post_id)) {
                error_log('Error creating product: ' . $carpenter_workshop_post_id->get_error_message());
                continue;
            }

            // Assign category to the product
            wp_set_object_terms($carpenter_workshop_post_id, (int)$carpenter_workshop_term_id, 'product_cat');

            // Set product type to 'simple'
            wp_set_object_terms($carpenter_workshop_post_id, 'simple', 'product_type');

            // Set product meta (price, sale price, stock, visibility)
            update_post_meta($carpenter_workshop_post_id, '_regular_price', '120');
            update_post_meta($carpenter_workshop_post_id, '_sale_price', '80');
            update_post_meta($carpenter_workshop_post_id, '_price', '80');
            update_post_meta($carpenter_workshop_post_id, '_stock_status', 'instock');
            update_post_meta($carpenter_workshop_post_id, '_visibility', 'visible');

            // Set featured image
            $carpenter_workshop_image_url = get_template_directory_uri() . '/assets/images/slider-img.png';
            $carpenter_workshop_image_id = media_sideload_image($carpenter_workshop_image_url, $carpenter_workshop_post_id, null, 'id');

            if (is_wp_error($carpenter_workshop_image_id)) {
                error_log('Error downloading image: ' . $carpenter_workshop_image_id->get_error_message());
                continue;
            }

            set_post_thumbnail($carpenter_workshop_post_id, $carpenter_workshop_image_id);
        }


        // Enable product section and set demo category
        set_theme_mod('carpenter_workshop_show_hide_product_section', true);
        set_theme_mod('carpenter_workshop_recent_product_category', 'productcategory1');

        // Define categories and product titles per category
        $carpenter_workshop_category_names = array('productcategory1');
        $carpenter_workshop_title_array = array(
            'productcategory1' => array("Chair", "Table", "Bed", "Kitchen", "Sofa"),
        );

        foreach ($carpenter_workshop_category_names as $category_name) {
            // Check if category exists
            $term = term_exists($category_name, 'product_cat');
            if ($term === 0 || $term === null) {
                $term = wp_insert_term($category_name, 'product_cat');
            }

            if (is_wp_error($term)) {
                error_log('Error creating category: ' . $term->get_error_message());
                continue;
            }

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

            // Titles for this category
            $product_titles = isset($carpenter_workshop_title_array[$category_name]) ? $carpenter_workshop_title_array[$category_name] : [];

            foreach ($product_titles as $index => $title) {
                $post_id = wp_insert_post(array(
                    'post_title'   => wp_strip_all_tags($title),
                    'post_status'  => 'publish',
                    'post_type'    => 'product',
                    'post_content' => 'This is a demo product under ' . $category_name . '.',
                ));

                if (is_wp_error($post_id)) {
                    error_log('Error creating product: ' . $post_id->get_error_message());
                    continue;
                }

                // Assign category
                wp_set_object_terms($post_id, (int)$term_id, 'product_cat');

                // Set product type
                wp_set_object_terms($post_id, 'simple', 'product_type');

                // Add WooCommerce price meta
                update_post_meta($post_id, '_regular_price', '120');
                update_post_meta($post_id, '_sale_price', '80');
                update_post_meta($post_id, '_price', '80');
                update_post_meta($post_id, '_stock_status', 'instock');
                update_post_meta($post_id, '_visibility', 'visible'); // for older WooCommerce

                // Set product image
                $image_url = get_template_directory_uri() . '/assets/images/product-img' . ($index + 1) . '.png';
                $image_id = media_sideload_image($image_url, $post_id, null, 'id');

                if (is_wp_error($image_id)) {
                    error_log('Image error: ' . $image_id->get_error_message());
                    continue;
                }

                set_post_thumbnail($post_id, $image_id);
            }
        }


    }
?>