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

        // If the demo import is completed, display the "View Site" button
        if ($real_fitness_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.', 'real-fitness' ) . '</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 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
                $real_fitness_plugin_slug = 'classic-blog-grid';
                $real_fitness_plugin_file = 'classic-blog-grid/classic-blog-grid.php';
            
                // Check if Classic Blog Grid is installed and activated
                if ( ! is_plugin_active( $real_fitness_plugin_file ) ) {
            
                    // Check if Classic Blog Grid is installed
                    $real_fitness_installed_plugins = get_plugins();
                    if ( ! isset( $real_fitness_installed_plugins[ $real_fitness_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
                        $real_fitness_upgrader = new Plugin_Upgrader();
                        $real_fitness_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( $real_fitness_plugin_file );
                }
            }
        echo '</div>';

        // ------- Create Main Menu --------
        $real_fitness_menuname = 'Primary Menu';
        $real_fitness_bpmenulocation = 'primary';
        $real_fitness_menu_exists = wp_get_nav_menu_object( $real_fitness_menuname );
    
        if ( !$real_fitness_menu_exists ) {
            $real_fitness_menu_id = wp_create_nav_menu( $real_fitness_menuname );

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

            // Create a new Page 
            $real_fitness_pages_title = 'Pages';
            $real_fitness_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>';
            $real_fitness_pages = array(
                'post_type'    => 'page',
                'post_title'   => $real_fitness_pages_title,
                'post_content' => $real_fitness_pages_content,
                'post_status'  => 'publish',
                'post_author'  => 1,
                'post_slug'    => 'pages'
            );
            $real_fitness_pages_id = wp_insert_post($real_fitness_pages);
            // Add Pages Page to Menu
            wp_update_nav_menu_item($real_fitness_menu_id, 0, array(
                'menu-item-title' => __('Pages', 'real-fitness'),
                'menu-item-classes' => 'pages',
                'menu-item-url' => home_url('/pages/'),
                'menu-item-status' => 'publish',
                'menu-item-object-id' => $real_fitness_pages_id,
                'menu-item-object' => 'page',
                'menu-item-type' => 'post_type'
            ));

            // Create About Us Page 
            $real_fitness_about_title = 'About Us';
            $real_fitness_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>';
            $real_fitness_about = array(
                'post_type'    => 'page',
                'post_title'   => $real_fitness_about_title,
                'post_content' => $real_fitness_about_content,
                'post_status'  => 'publish',
                'post_author'  => 1,
                'post_slug'    => 'about-us'
            );
            $real_fitness_about_id = wp_insert_post($real_fitness_about);
            // Add About Us Page to Menu
            wp_update_nav_menu_item($real_fitness_menu_id, 0, array(
                'menu-item-title' => __('About Us', 'real-fitness'),
                'menu-item-classes' => 'about-us',
                'menu-item-url' => home_url('/about-us/'),
                'menu-item-status' => 'publish',
                'menu-item-object-id' => $real_fitness_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( $real_fitness_bpmenulocation ) ) {
                $real_fitness_locations = get_theme_mod( 'nav_menu_locations' );
                if ( empty( $real_fitness_locations ) ) {
                    $real_fitness_locations = array();
                }
                $real_fitness_locations[ $real_fitness_bpmenulocation ] = $real_fitness_menu_id;
                set_theme_mod( 'nav_menu_locations', $real_fitness_locations );
            }
        }

        //Header Section 
        set_theme_mod( 'real_fitness_phone_number', '2786-30-64');
        set_theme_mod( 'real_fitness_email_address', 'fitness@yourdomain.com');
        set_theme_mod( 'real_fitness_open_time', '06.00AM - 07.00 PM Mon-Fri');
        set_theme_mod( 'real_fitness_the_custom_logo', esc_url( get_template_directory_uri().'/images/Logo.png'));

        //Slider Section
        set_theme_mod( 'real_fitness_heading', 'MAKE YOURSELF STRONGER THAN EXCUSES AND'); 
        set_theme_mod( 'real_fitness_button_text', 'GET STARTED'); 
        set_theme_mod( 'real_fitness_button_link_slider', '#');
        
        // Create the 'Fitness' category and retrieve its ID
        $real_fitness_slider_category_id = wp_create_category('Fitness');
        
        // Set the category in theme mods for the slider section
        if (!is_wp_error($real_fitness_slider_category_id)) {
            set_theme_mod('real_fitness_slidersection', $real_fitness_slider_category_id);
        }
        $real_fitness_titles = array(
            'MAKE YOURSELF PROUD',
            'PUSH HARDER THAN YESTERDAY',
            'STRONGER EVERY DAY'
        );
        
        // Create three demo posts and assign them to the 'Fitness' category
        for ($real_fitness_i = 0; $real_fitness_i <= 2; $real_fitness_i++) {
            // Store title in theme mod
            set_theme_mod('real_fitness_title' . ($real_fitness_i + 1), $real_fitness_titles[$real_fitness_i]);
        
            $real_fitness_content = 'Welcome to our fitness center. Check out special pricing plans and start training with us now.';
        
            // Prepare the post object
            $real_fitness_my_post = array(
                'post_title'    => wp_strip_all_tags($real_fitness_titles[$real_fitness_i]), // Fixed incorrect variable reference
                'post_content'  => $real_fitness_content,
                'post_status'   => 'publish',
                'post_type'     => 'post',
                'post_category' => array($real_fitness_slider_category_id), // Ensure this variable is properly set
            );
        
            // Insert the post into the database
            $real_fitness_post_id = wp_insert_post($real_fitness_my_post);
        
            // If the post was successfully created, set the featured image
            if (!is_wp_error($real_fitness_post_id)) {
                $real_fitness_image_url = get_template_directory_uri() . '/images/slider' . ($real_fitness_i + 1) . '.png';
        
                // Download and attach the image
                $real_fitness_image_id = media_sideload_image($real_fitness_image_url, $real_fitness_post_id, null, 'id');
        
                if (!is_wp_error($real_fitness_image_id) && $real_fitness_image_id) {
                    set_post_thumbnail($real_fitness_post_id, $real_fitness_image_id);
                } else {
                    error_log('Failed to set post thumbnail for post ID: ' . $real_fitness_post_id);
                }
            } else {
                error_log('Failed to create post: ' . print_r($real_fitness_post_id, true));
            }
        }        

       //Services Section
       set_theme_mod( 'real_fitness_main_title', 'OUR SERVICES');

        // Include WordPress Filesystem API
        require_once( ABSPATH . 'wp-admin/includes/file.php' );

        // Initialize the filesystem
        global $wp_filesystem;
        if (false === ($real_fitness_creds = request_filesystem_credentials('', '', false, false, null))) {
            return; // Exit if credentials are needed
        }

        if (!WP_Filesystem($real_fitness_creds)) {
            return; // Exit if filesystem could not be initialized
        }

        $real_fitness_services_category_id = wp_create_category('Challenges');
        set_theme_mod('real_fitness_services_cat', $real_fitness_services_category_id);
        $real_fitness_service_titles = array('NUTRITION CHALLENGES', 'BOOT CAMP', 'PERSONAL TRAINING');
        $real_fitness_service_contents = array('VERY POWERFUL FOOD MARKTING THAT PERTICULARLY IMPACTS.', 'A SHORT, INTENSIVE, AND RIGORUS COURSE OF TRAINING.', 'A PERSONAL TRAINER AN INDIVIDUAL WHO HAS EARNED A CERTIFICATION.');

        // Define the image URLs for each service
        $real_fitness_image_urls = array(
            esc_url(get_template_directory_uri() . '/images/fitness-services/fitness-service1.png'),
            esc_url(get_template_directory_uri() . '/images/fitness-services/fitness-service2.png'),
            esc_url(get_template_directory_uri() . '/images/fitness-services/fitness-service3.png'),
        );

        // Loop to create posts for each service
        for ($real_fitness_i = 0; $real_fitness_i < count($real_fitness_service_titles); $real_fitness_i++) {
                $real_fitness_title = $real_fitness_service_titles[$real_fitness_i];
                $real_fitness_content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
    
                // Create the post object
                $real_fitness_service_post = array(
                    'post_title'    => wp_strip_all_tags($real_fitness_title),
                    'post_content'  => $real_fitness_content,
                    'post_status'   => 'publish',
                    'post_type'     => 'post',
                    'post_category' => array($real_fitness_services_category_id),
                );
    
                // Insert the post into the database
                $real_fitness_service_id = wp_insert_post($real_fitness_service_post);
    
                // If the post was successfully created
                if ($real_fitness_service_id && !is_wp_error($real_fitness_service_id)) {
                    // Set the theme mod for selecting this post
                    set_theme_mod('real_fitness_select_post' . ($real_fitness_i + 1), $real_fitness_service_id);
    
                    // Fetch image data from the corresponding URL
                    $real_fitness_image_data = file_get_contents($real_fitness_image_urls[$real_fitness_i]);
    
                    if ($real_fitness_image_data !== false) {
                        // Prepare file information
                        $real_fitness_upload_dir = wp_upload_dir();
                        if (!file_exists($real_fitness_upload_dir['path'])) {
                            error_log("Upload directory does not exist: " . $real_fitness_upload_dir['path']);
                            continue; // Skip to the next service
                        }
    
                        // Use a consistent file name for the image
                        $real_fitness_image_name = 'fitness-service' . ($real_fitness_i + 1) . '.png'; 
                        $real_fitness_file = $real_fitness_upload_dir['path'] . '/' . $real_fitness_image_name;
    
                        // Use WordPress Filesystem API to write the image data
                        if (!$wp_filesystem->exists($real_fitness_file)) {
                            if ($wp_filesystem->put_contents($real_fitness_file, $real_fitness_image_data, FS_CHMOD_FILE) === false) {
                                error_log("Failed to write image to file: $real_fitness_file");
                                continue; // Skip to the next service
                            }
                        }
    
                        // Check the file type
                        $real_fitness_wp_filetype = wp_check_filetype($real_fitness_image_name, null);
                        if (!$real_fitness_wp_filetype['type']) {
                            error_log("Failed to determine MIME type for file: $real_fitness_image_name");
                            continue; // Skip to the next service
                        }
    
                        // Prepare attachment data
                        $real_fitness_attachment = array(
                            'post_mime_type' => $real_fitness_wp_filetype['type'],
                            'post_title'     => sanitize_file_name($real_fitness_image_name),
                            'post_content'   => '',
                            'post_status'    => 'inherit',
                        );
    
                        // Insert the attachment into the media library
                        $real_fitness_attach_id = wp_insert_attachment($real_fitness_attachment, $real_fitness_file, $real_fitness_service_id);
                        if (is_wp_error($real_fitness_attach_id)) {
                            error_log("Failed to insert attachment: " . $real_fitness_attach_id->get_error_message());
                            continue; // Skip to the next service
                        }
    
                        // Generate attachment metadata
                        $real_fitness_attach_data = wp_generate_attachment_metadata($real_fitness_attach_id, $real_fitness_file);
                        if (!$real_fitness_attach_data) {
                            error_log("Failed to generate attachment metadata for ID: $real_fitness_attach_id");
                            continue; // Skip to the next service
                        }
    
                        // Update attachment metadata
                        wp_update_attachment_metadata($real_fitness_attach_id, $real_fitness_attach_data);
    
                        // Set the attachment as the post's featured image
                        if (!set_post_thumbnail($real_fitness_service_id, $real_fitness_attach_id)) {
                            error_log("Failed to set featured image for post ID: $real_fitness_service_id");
                        } else {
                            error_log("Successfully set featured image for post ID: $real_fitness_service_id");
                        }
                    } else {
                        error_log("Failed to fetch image data from URL: " . $real_fitness_image_urls[$real_fitness_i]);
                    }
                } else {
                    error_log("Failed to create post: " . print_r($real_fitness_service_id, true));
                }
        }

        // Show success message and the "View Site" button
        update_option('real_fitness_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.', 'real-fitness' ) . '</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('real_fitness_demo_import_completed')) : ?>
                <span><?php echo esc_html( 'Click on the below content to get demo content installed.', 'real-fitness' ); ?></span>
                <br><br>
                <hr><br>
                <b class="note"><?php echo esc_html('Note :', 'real-fitness' ); ?></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.', 'real-fitness' ); ?></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','real-fitness'); ?>" 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>