<div class="theme-offer">
   <?php
         // Check if the demo import has been completed
         $classic_bakery_demo_import_completed = get_option('classic_bakery_demo_import_completed', false);

         // If the demo import is completed, display the "View Site" button
         if ($classic_bakery_demo_import_completed) {
             echo '<br>';
             echo '<div class="success">Demo Import Successful</div>';
             echo '<br>';
             echo '<hr>';
             echo '<br>';
             echo '<span>' . esc_html__( 'You can now visit your site or customize it further.', 'classic-bakery' ) . '</span>';
             echo '<br>';
             echo '<br>';
             echo '<br>';
             echo '<div class="view-site-btn">';
             echo '<a href="' . esc_url(home_url()) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">View Site</a>';
             echo '<a href="' . esc_url( admin_url('customize.php') ) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">Customize Demo Content</a>';
             echo '</div>';
         }
    if ( isset( $_POST['submit'] ) ) {
        echo '<div class="plugin-notice">';
            // Check if woocommerce is installed and activated
            if (!is_plugin_active('woocommerce/woocommerce.php')) {
                // Install the plugin if it doesn't exist
                $classic_bakery_plugin_slug = 'woocommerce';
                $classic_bakery_plugin_file = 'woocommerce/woocommerce.php';

                // Check if plugin is installed
                $classic_bakery_installed_plugins = get_plugins();
                if (!isset($classic_bakery_installed_plugins[$classic_bakery_plugin_file])) {
                    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');

                    // Install the plugin
                    $classic_bakery_upgrader = new Plugin_Upgrader();
                    $classic_bakery_upgrader->install('https://downloads.wordpress.org/plugin/woocommerce.latest-stable.zip');
                }
                // Activate the plugin
                activate_plugin($classic_bakery_plugin_file);
            }

            // Check if Classic Blog Grid plugin is installed
            if (!is_plugin_active('classic-blog-grid/classic-blog-grid.php')) {
                // Plugin slug and file path for Classic Blog Grid
                $classic_bakery_plugin_slug = 'classic-blog-grid';
                $classic_bakery_plugin_file = 'classic-blog-grid/classic-blog-grid.php';
            
                // Check if Classic Blog Grid is installed and activated
                if ( ! is_plugin_active( $classic_bakery_plugin_file ) ) {
            
                    // Check if Classic Blog Grid is installed
                    $classic_bakery_installed_plugins = get_plugins();
                    if ( ! isset( $classic_bakery_installed_plugins[ $classic_bakery_plugin_file ] ) ) {
            
                        // Include necessary files to install plugins
                        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' );
            
                        // Download and install Classic Blog Grid
                        $classic_bakery_upgrader = new Plugin_Upgrader();
                        $classic_bakery_upgrader->install( 'https://downloads.wordpress.org/plugin/classic-blog-grid.latest-stable.zip' );
                    }
            
                    // Activate the Classic Blog Grid plugin after installation (if needed)
                    activate_plugin( $classic_bakery_plugin_file );
                }
            }
        echo '</div>';

        // ------- Create Main Menu --------
        $classic_bakery_menuname = 'Primary Menu';
        $classic_bakery_bpmenulocation = 'primary';
        $classic_bakery_menu_exists = wp_get_nav_menu_object( $classic_bakery_menuname );
    
        if ( !$classic_bakery_menu_exists ) {
            $classic_bakery_menu_id = wp_create_nav_menu( $classic_bakery_menuname );

            // Create Home Page
            $classic_bakery_home_title = 'Home';
            $classic_bakery_home = array(
                'post_type'    => 'page',
                'post_title'   => $classic_bakery_home_title,
                'post_content' => '',
                'post_status'  => 'publish',
                'post_author'  => 1,
                'post_slug'    => 'home'
            );
            $classic_bakery_home_id = wp_insert_post($classic_bakery_home);
            // Assign Home Page Template
            add_post_meta($classic_bakery_home_id, '_wp_page_template', '/template-home-page.php');
            // Update options to set Home Page as the front page
            update_option('page_on_front', $classic_bakery_home_id);
            update_option('show_on_front', 'page');
            // Add Home Page to Menu
            wp_update_nav_menu_item($classic_bakery_menu_id, 0, array(
                'menu-item-title' => __('Home', 'classic-bakery'),
                'menu-item-classes' => 'home',
                'menu-item-url' => home_url('/'),
                'menu-item-status' => 'publish',
                'menu-item-object-id' => $classic_bakery_home_id,
                'menu-item-object' => 'page',
                'menu-item-type' => 'post_type'
            ));

            // Create a new Page 
            $classic_bakery_pages_title = 'Pages';
            $classic_bakery_pages_content = '<p>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.</p>';
            $classic_bakery_pages = array(
                'post_type'    => 'page',
                'post_title'   => $classic_bakery_pages_title,
                'post_content' => $classic_bakery_pages_content,
                'post_status'  => 'publish',
                'post_author'  => 1,
                'post_slug'    => 'pages'
            );
            $classic_bakery_pages_id = wp_insert_post($classic_bakery_pages);
            // Add Pages Page to Menu
            wp_update_nav_menu_item($classic_bakery_menu_id, 0, array(
                'menu-item-title' => __('Pages', 'classic-bakery'),
                'menu-item-classes' => 'pages',
                'menu-item-url' => home_url('/pages/'),
                'menu-item-status' => 'publish',
                'menu-item-object-id' => $classic_bakery_pages_id,
                'menu-item-object' => 'page',
                'menu-item-type' => 'post_type'
            ));

            // Create About Us Page 
            $classic_bakery_about_title = 'About Us';
            $classic_bakery_about_content = '<p>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.</p>';
            $classic_bakery_about = array(
                'post_type'    => 'page',
                'post_title'   => $classic_bakery_about_title,
                'post_content' => $classic_bakery_about_content,
                'post_status'  => 'publish',
                'post_author'  => 1,
                'post_slug'    => 'about-us'
            );
            $classic_bakery_about_id = wp_insert_post($classic_bakery_about);
            // Add About Us Page to Menu
            wp_update_nav_menu_item($classic_bakery_menu_id, 0, array(
                'menu-item-title' => __('About Us', 'classic-bakery'),
                'menu-item-classes' => 'about-us',
                'menu-item-url' => home_url('/about-us/'),
                'menu-item-status' => 'publish',
                'menu-item-object-id' => $classic_bakery_about_id,
                'menu-item-object' => 'page',
                'menu-item-type' => 'post_type'
            ));

            // Assign the menu to the primary location if not already set
            if ( ! has_nav_menu( $classic_bakery_bpmenulocation ) ) {
                $classic_bakery_locations = get_theme_mod( 'nav_menu_locations' );
                if ( empty( $classic_bakery_locations ) ) {
                    $classic_bakery_locations = array();
                }
                $classic_bakery_locations[ $classic_bakery_bpmenulocation ] = $classic_bakery_menu_id;
                set_theme_mod( 'nav_menu_locations', $classic_bakery_locations );
            }
        }

        //Header Section
        set_theme_mod( 'classic_bakery_shop_text', 'Shop'); 
        set_theme_mod( 'classic_bakery_shop_link', '#'); 
        set_theme_mod( 'classic_bakery_the_custom_logo', esc_url( get_template_directory_uri().'/images/Logo.png'));

        //Social Media Section
        set_theme_mod( 'classic_bakery_fb_link', '#'); 
        set_theme_mod( 'classic_bakery_twitt_link', '#');
        set_theme_mod( 'classic_bakery_insta_link', '#');

        //Slider Section
        set_theme_mod( 'classic_bakery_hide_categorysec', true); 
        set_theme_mod( 'classic_bakery_button_text', 'Shop'); 
        set_theme_mod( 'classic_bakery_button_link_slider', '#');
        
        // Create the 'Bakery' category and retrieve its ID
        $classic_bakery_slider_category_id = wp_create_category('Bakery');
        
        // Set the category in theme mods for the slider section
        if (!is_wp_error($classic_bakery_slider_category_id)) {
            set_theme_mod('classic_bakery_slidersection', $classic_bakery_slider_category_id); // Update with correct category ID
        }

        $classic_bakery_titles = array(
            'Best Pastry In Town One',
            'Best Pastry In Town Two',
            'Best Pastry In Town Three'
        );        
        $classic_bakery_content = 'Los Angeles, California.';
        // Create three demo posts and assign them to the 'Bakery' category
        for ($classic_bakery_i = 0; $classic_bakery_i <= 2; $classic_bakery_i++) {
            set_theme_mod('classic_bakery_title' . ($classic_bakery_i + 1), $classic_bakery_titles[$classic_bakery_i]);
    
            // Prepare the post object
            $classic_bakery_my_post = array(
                'post_title'    => wp_strip_all_tags($classic_bakery_titles[$classic_bakery_i]),
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => array($classic_bakery_slider_category_id),
            );
    
            // Insert the post into the database
            $classic_bakery_post_id = wp_insert_post($classic_bakery_my_post);
    
            // If the post was successfully created, set the featured image
            if (!is_wp_error($classic_bakery_post_id)) {
                $classic_bakery_image_url = get_template_directory_uri() . '/images/slider' . ($classic_bakery_i + 1) . '.png';
                $classic_bakery_image_id = media_sideload_image($classic_bakery_image_url, $classic_bakery_post_id, null, 'id');
                if (!is_wp_error($classic_bakery_image_id)) {
                    set_post_thumbnail($classic_bakery_post_id, $classic_bakery_image_id);
                } else {
                    error_log('Failed to set post thumbnail for post ID: ' . $classic_bakery_post_id);
                }
            } else {
                error_log('Failed to create post: ' . print_r($classic_bakery_post_id, true));
            }
        }

        // Category Section
        set_theme_mod( 'classic_bakery_procat_show', true); 
        $classic_bakery_category_data = [
            'Donuts' => get_template_directory_uri() . '/images/products/product1.png',
            'Cup Cake' => get_template_directory_uri() . '/images/products/product2.png',
            'Beverages' => get_template_directory_uri() . '/images/products/product3.png',
        ];

        // Default image for the "Uncategorized" category
        $default_uncategorized_image = get_template_directory_uri() . '/images/products/default-uncategorized.png';

        foreach ($classic_bakery_category_data as $classic_bakery_category_name => $classic_bakery_image_url) {
            // Check if the category exists
            $classic_bakery_product_category = get_term_by('name', $classic_bakery_category_name, 'product_cat');

            if (!$classic_bakery_product_category) {
                // Create category
                $classic_bakery_product_category_id = wp_insert_term($classic_bakery_category_name, 'product_cat');
                
                if (is_wp_error($classic_bakery_product_category_id)) {
                    error_log('Error creating category: ' . $classic_bakery_product_category_id->get_error_message());
                    continue;
                }
                $classic_bakery_product_category_id = $classic_bakery_product_category_id['term_id'];
            } else {
                $classic_bakery_product_category_id = $classic_bakery_product_category->term_id;
            }

            if (!get_term_meta($classic_bakery_product_category_id, 'thumbnail_id', true)) {
                $classic_bakery_category_image_response = wp_remote_get($classic_bakery_image_url);
                if (!is_wp_error($classic_bakery_category_image_response)) {
                    $classic_bakery_category_image_data = wp_remote_retrieve_body($classic_bakery_category_image_response);
                    if (!empty($classic_bakery_category_image_data)) {
                        $upload_dir = wp_upload_dir();
                        $image_path = $upload_dir['path'] . '/' . sanitize_title($classic_bakery_category_name) . '.png';

                        global $wp_filesystem;
                        WP_Filesystem();
                        if ($wp_filesystem->put_contents($image_path, $classic_bakery_category_image_data)) {
                            $image_type = wp_check_filetype($image_path, null);
                            $attachment = [
                                'post_mime_type' => $image_type['type'],
                                'post_title'     => sanitize_file_name($image_path),
                                'post_content'   => '',
                                'post_status'    => 'inherit',
                            ];
                            
                            $attach_id = wp_insert_attachment($attachment, $image_path);
                            require_once(ABSPATH . 'wp-admin/includes/image.php');
                            $attach_data = wp_generate_attachment_metadata($attach_id, $image_path);
                            wp_update_attachment_metadata($attach_id, $attach_data);

                            // Assign image to category
                            update_term_meta($classic_bakery_product_category_id, 'thumbnail_id', $attach_id);
                        }
                    }
                }
            }

            for ($classic_bakery_i = 1; $classic_bakery_i <= 3; $classic_bakery_i++) {
                $classic_bakery_product_title = $classic_bakery_category_name . ' Product ' . $classic_bakery_i;
                $classic_bakery_product_image_url = get_template_directory_uri() . '/images/products/product' . $classic_bakery_i . '.png';

                $classic_bakery_product_data = [
                    'post_title'   => $classic_bakery_product_title,
                    'post_content' => 'Description for ' . $classic_bakery_product_title,
                    'post_status'  => 'publish',
                    'post_type'    => 'product',
                ];

                $classic_bakery_product_id = wp_insert_post($classic_bakery_product_data);

                if (!is_wp_error($classic_bakery_product_id)) {
                    // Assign category to product
                    wp_set_object_terms($classic_bakery_product_id, [$classic_bakery_product_category_id], 'product_cat');

                    update_post_meta($classic_bakery_product_id, '_price', '9.99');
                    update_post_meta($classic_bakery_product_id, '_regular_price', '9.99');

                    update_post_meta($classic_bakery_product_id, '_stock_status', 'instock');
                    update_post_meta($classic_bakery_product_id, '_manage_stock', 'no');

                    wp_set_object_terms($classic_bakery_product_id, 'simple', 'product_type');

                    // Add product image
                    $classic_bakery_product_image_response = wp_remote_get($classic_bakery_product_image_url);
                    if (!is_wp_error($classic_bakery_product_image_response)) {
                        $classic_bakery_product_image_data = wp_remote_retrieve_body($classic_bakery_product_image_response);
                        if (!empty($classic_bakery_product_image_data)) {
                            $classic_bakery_product_image_name = sanitize_title($classic_bakery_product_title) . '.png';
                            $classic_bakery_product_upload_dir = wp_upload_dir();
                            $classic_bakery_product_file_path = $classic_bakery_product_upload_dir['path'] . '/' . $classic_bakery_product_image_name;

                            global $wp_filesystem;
                            WP_Filesystem();
                            if ($wp_filesystem->put_contents($classic_bakery_product_file_path, $classic_bakery_product_image_data)) {
                                $classic_bakery_product_wp_filetype = wp_check_filetype($classic_bakery_product_image_name, null);
                                $classic_bakery_product_attachment = [
                                    'post_mime_type' => $classic_bakery_product_wp_filetype['type'],
                                    'post_title'     => sanitize_file_name($classic_bakery_product_image_name),
                                    'post_content'   => '',
                                    'post_status'    => 'inherit',
                                ];

                                $classic_bakery_product_attach_id = wp_insert_attachment($classic_bakery_product_attachment, $classic_bakery_product_file_path);
                                $classic_bakery_product_attach_data = wp_generate_attachment_metadata($classic_bakery_product_attach_id, $classic_bakery_product_file_path);
                                wp_update_attachment_metadata($classic_bakery_product_attach_id, $classic_bakery_product_attach_data);

                                set_post_thumbnail($classic_bakery_product_id, $classic_bakery_product_attach_id);
                            }
                        }
                    }
                }
            }
        }

        // Show success message and the "View Site" button
        update_option('classic_bakery_demo_import_completed', true);
        echo '<br>';
        echo '<div class="success">Demo Import Successful</div>';
        echo '<br>';
        echo '<hr>';
        echo '<br>';
        echo '<span>' . esc_html__( 'You can now visit your site or customize it further.', 'classic-bakery' ) . '</span>';
        echo '<br>';
    }
     ?>
    <ul>
        <li>
        <?php 
        // Check if the form is submitted
        if ( !isset( $_POST['submit'] ) ) : ?>
            <!-- Show demo importer form only if it's not submitted -->
            <?php if (!get_option('classic_bakery_demo_import_completed')) : ?>
                <span><?php echo esc_html( 'Click on the below content to get demo content installed.', 'classic-bakery' ); ?></span>
                <br><br>
                <hr><br>
                <b class="note"><?php echo esc_html('Note :', 'classic-bakery' ); ?></b><br><br>
                <small><b><?php echo esc_html('Please take a backup if your website is already live with data. This importer will overwrite existing data.', 'classic-bakery' ); ?></b></small><br><br>
                <form id="demo-importer-form" action="" method="POST" onsubmit="return runDemoImport();">
                    <input type="submit" name="submit" value="<?php echo esc_attr('Run Importer','classic-bakery'); ?>" class="button button-primary button-large">
                </form>
                <script type="text/javascript">
                    function runDemoImport() {
                        if (confirm('Do you really want to do this?')) {
                            document.getElementById('demo-import-loader').style.display = 'block';
                            return true;
                        }
                        return false;
                    }
                </script>
             <?php endif; ?>
         <?php 
        endif; 

        // Show "View Site" button after form submission
        if ( isset( $_POST['submit'] ) ) {
        echo '<div class="view-site-btn">';
        echo '<a href="' . esc_url(home_url()) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">View Site</a>';
        echo '<a href="' . esc_url( admin_url('customize.php') ) . '" class="button button-primary button-large" style="margin-top: 10px;" target="_blank">Customize Demo Content</a>';
        echo '</div>';
        }
        ?>
        </li>
    </ul>
 </div>