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

        // If the demo import is completed, display the "View Site" button
        if ($sports_league_demo_import_completed) {
        echo '<p class="notice-text">' . esc_html__('Your demo import has been completed successfully.', 'sports-league') . '</p>';
        echo '<span><a href="' . esc_url(home_url()) . '" class="button button-primary site-btn" target="_blank">' . esc_html__('VIEW SITE', 'sports-league') . '</a></span>';
        }
		
        if (isset($_POST['submit'])) {

            //Check if WooCommerce is installed and activated
            if (!is_plugin_active('woocommerce/woocommerce.php')) {
                // Install the plugin if it doesn't exist
                $sports_league_plugin_slug = 'woocommerce';
                $sports_league_plugin_file = 'woocommerce/woocommerce.php';

                // Check if plugin is installed
                $sports_league_installed_plugins = get_plugins();
                if (!isset($sports_league_installed_plugins[$sports_league_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
                    $sports_league_upgrader = new Plugin_Upgrader();
                    $sports_league_upgrader->install('https://downloads.wordpress.org/plugin/woocommerce.latest-stable.zip');
                }
                // Activate the plugin
                activate_plugin($sports_league_plugin_file);
            }

            // ------- Create Nav Menu --------
            $sports_league_menuname = 'Main Menus';
            $sports_league_bpmenulocation = 'primary';
            $sports_league_menu_exists = wp_get_nav_menu_object($sports_league_menuname);

            if (!$sports_league_menu_exists) {
                $sports_league_menu_id = wp_create_nav_menu($sports_league_menuname);

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

                // Create About Us Page with Dummy Content
                $sports_league_about_title = 'About Us';
                $sports_league_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.';
                $sports_league_about = array(
                    'post_type' => 'page',
                    'post_title' => $sports_league_about_title,
                    'post_content' => $sports_league_about_content,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    'post_slug' => 'about-us'
                );
                $sports_league_about_id = wp_insert_post($sports_league_about);
                // Add About Us Page to Menu
                wp_update_nav_menu_item($sports_league_menu_id, 0, array(
                    'menu-item-title' => __('About Us', 'sports-league'),
                    'menu-item-classes' => 'about-us',
                    'menu-item-url' => home_url('/about-us/'),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $sports_league_about_id,
                    'menu-item-object' => 'page',
                    'menu-item-type' => 'post_type'
                ));

                 // Create Blog Page 
                $sports_league_blog_page_title = 'Blog';
                $sports_league_blog_page_query = new WP_Query(array(
                    'post_type'      => 'page',
                    'name'           => sanitize_title($sports_league_blog_page_title),
                    'post_status'    => 'publish',
                    'posts_per_page' => 1
                ));
                if (!$sports_league_blog_page_query->have_posts()) {
                    $sports_league_blog_page = array(
                    'post_type'   => 'page',
                    'post_title'  => $sports_league_blog_page_title,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    );
                    $sports_league_blog_page_id = wp_insert_post($sports_league_blog_page);
                    update_option('page_for_posts', $sports_league_blog_page_id);
                    wp_update_nav_menu_item($sports_league_menu_id, 0, array(
                    'menu-item-title'      => __('Blog', 'sports-league'),
                    'menu-item-url'        => get_permalink($sports_league_blog_page_id),
                    'menu-item-status'     => 'publish',
                    'menu-item-object-id'  => $sports_league_blog_page_id,
                    'menu-item-object'     => 'page',
                    'menu-item-type'       => 'post_type',
                   ));
                }

                // Create Pages Page with Dummy Content
                $sports_league_contact_title = 'Contact Us';
                $sports_league_contact_content = 'Explore all the contact we have on our website. Find information about our services, company, and more.
                 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 contactly with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<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.';
                $sports_league_contact = array(
                    'post_type' => 'page',
                    'post_title' => $sports_league_contact_title,
                    'post_content' => $sports_league_contact_content,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    'post_slug' => 'contact'
                );
                $sports_league_contact_id = wp_insert_post($sports_league_contact);
                // Add Pages Page to Menu
                wp_update_nav_menu_item($sports_league_menu_id, 0, array(
                    'menu-item-title' => __('Contact', 'sports-league'),
                    'menu-item-classes' => 'contact',
                    'menu-item-url' => home_url('/contact/'),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $sports_league_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($sports_league_bpmenulocation)) {
                    $sports_league_locations = get_theme_mod('nav_menu_locations'); // Use 'nav_menu_locations' to get locations array
                    if (empty($sports_league_locations)) {
                        $sports_league_locations = array();
                    }
                    $sports_league_locations[$sports_league_bpmenulocation] = $sports_league_menu_id;
                    set_theme_mod('nav_menu_locations', $sports_league_locations);
                }
            }

            //Header
            set_theme_mod('sports_league_get_tickets', 'GET TICKETS');
            set_theme_mod('sports_league_get_tickets_url', '#');
            set_theme_mod('sports_league_track_delivery', 'TRACK DELIVERY');
            set_theme_mod('sports_league_track_delivery_url', '#');
            set_theme_mod('sports_league_news_text', 'Terms and Condition');
            set_theme_mod('sports_league_notice_section_text', 'Support Your Favourite Team Now!Offer Available On Team Jerseys Limited Time Offer.');

            //Social Icons
            set_theme_mod('sports_league_facebook_url', 'https://www.facebook.com');
            set_theme_mod('sports_league_twitter_url', 'https://www.twitter.com');
            set_theme_mod('sports_league_instagram_url', 'https://www.instagram.com');
            set_theme_mod('sports_league_pinterest_url', 'https://www.pinterest.com');

            //Slider Section
            set_theme_mod('sports_league_slider_hide', true);
            set_theme_mod('sports_league_slider_small_title', 'POWERFUL SPORTS THEME');
            set_theme_mod('sports_league_slider_button_text', 'Read More');

            $sports_league_slider_titles = array(
                'MAKE EVERY MINUTE ON THE FIELD COUNT', 
                'UNITED TEAMS BRING THE BEST OUT OF ALL', 
                'HARD WORK PAYS OFF WITH VICTORY ON TOP', 
                'PASSION DRIVES PERFORMANCE AND SUCCESS', 
            );                        
            
            for ($sports_league_i = 0; $sports_league_i < count($sports_league_slider_titles); $sports_league_i++) {
                $sports_league_slider_title = $sports_league_slider_titles[$sports_league_i];
                $sports_league_slider_content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
                
                // Skip empty titles
                if (empty($sports_league_slider_title)) {
                    continue;
                }
            
                // Create post object
                $sports_league_my_post = array(
                    'post_title'    => wp_strip_all_tags($sports_league_slider_title),
                    'post_content'  => $sports_league_slider_content,
                    'post_status'   => 'publish',
                    'post_type'     => 'page',
                );
            
                // Insert the post into the database
                $sports_league_post_id = wp_insert_post($sports_league_my_post);
            
                if (!is_wp_error($sports_league_post_id)) {
                    // Set the theme mod for the slider page
                    set_theme_mod('sports_league_slider' . ($sports_league_i + 1), $sports_league_post_id);
            
                    // Image URL for the slider
                    $sports_league_image_url = get_template_directory_uri() . '/images/slider' . ($sports_league_i + 1) . '.png';
            
                    // Add the image to the post
                    $sports_league_image_id = media_sideload_image($sports_league_image_url, $sports_league_post_id, null, 'id');
            
                    if (!is_wp_error($sports_league_image_id)) {
                        // Set the downloaded image as the post's featured image
                        set_post_thumbnail($sports_league_post_id, $sports_league_image_id);
                    } else {
                        error_log('Error setting featured image for post ID ' . $sports_league_post_id . ': ' . $sports_league_image_id->get_error_message());
                    }
                } else {
                    error_log('Error creating post: ' . $sports_league_post_id->get_error_message());
                }
            }                    

            //Sports Section
            set_theme_mod('sports_league_section_text', 'SPORT WE OFFER');
            set_theme_mod('sports_league_section_title', 'SPORTS COACHING');
            set_theme_mod('sports_league_events_category', 'postcategory1');

            // Define post category names and post titles
            $sports_league_category_names = array('postcategory1', 'postcategory2', 'postcategory3', 'postcategory4');
            $sports_league_title_array = array(
                array("Volleyball", "Soccer", "Tennis"),
                array("Volleyball", "Soccer", "Tennis"),
                array("Volleyball", "Soccer", "Tennis"),
                array("Volleyball", "Soccer", "Tennis")
            );

            foreach ($sports_league_category_names as $sports_league_index => $sports_league_category_name) {
                // Create or retrieve the post category term ID
                $sports_league_term = term_exists($sports_league_category_name, 'category');
                if ($sports_league_term === 0 || $sports_league_term === null) {
                    // If the term does not exist, create it
                    $sports_league_term = wp_insert_term($sports_league_category_name, 'category');
                }
                if (is_wp_error($sports_league_term)) {
                    error_log('Error creating category: ' . $sports_league_term->get_error_message());
                    continue; // Skip to the next iteration if category creation fails
                }

                for ($sports_league_i = 0; $sports_league_i < 3; $sports_league_i++) {
                    // Create post content
                    $sports_league_title = $sports_league_title_array[$sports_league_index][$sports_league_i];
                    $sports_league_content = 'Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s.';

                    // Create post post object
                    $sports_league_my_post = array(
                        'post_title'    => wp_strip_all_tags($sports_league_title),
                        'post_content'  => $sports_league_content,
                        'post_status'   => 'publish',
                        'post_type'     => 'post', // Post type set to 'post'
                    );

                    // Insert the post into the database
                    $sports_league_post_id = wp_insert_post($sports_league_my_post);

                    if (is_wp_error($sports_league_post_id)) {
                        error_log('Error creating post: ' . $sports_league_post_id->get_error_message());
                        continue; // Skip to the next post if creation fails
                    }
                    // Assign the category to the post
                    wp_set_post_categories($sports_league_post_id, array((int)$sports_league_term['term_id']));

                    // Handle the featured image using media_sideload_image
                    $sports_league_image_url = get_template_directory_uri() . '/images/sports' . ($sports_league_i + 1) . '.png';
                    $sports_league_image_id = media_sideload_image($sports_league_image_url, $sports_league_post_id, null, 'id');

                    if (is_wp_error($sports_league_image_id)) {
                        error_log('Error downloading image: ' . $sports_league_image_id->get_error_message());
                        continue; // Skip to the next post if image download fails
                    }
                    // Assign featured image to post
                    set_post_thumbnail($sports_league_post_id, $sports_league_image_id);
                }
            }

            // Set the demo import completion flag
    		update_option('sports_league_demo_import_completed', true);
    		// Display success message and "View Site" button
    		echo '<p class="notice-text">' . esc_html__('Your demo import has been completed successfully.', 'sports-league') . '</p>';
    		echo '<span><a href="' . esc_url(home_url()) . '" class="button button-primary site-btn" target="_blank">' . esc_html__('VIEW SITE', 'sports-league') . '</a></span>';
            //end

        }
    ?>

    <form action="<?php echo esc_url(home_url()); ?>/wp-admin/themes.php?page=sports-league-guide-page" method="POST" onsubmit="return validate(this);">
    <?php if (!get_option('sports_league_demo_import_completed')) : ?>
        <form method="post">
        <p><?php esc_html_e('Click the below run importer button to import demo content','sports-league'); ?></p>
            <input class= "run-import" type="submit" name="submit" value="<?php esc_attr_e('Run Importer','sports-league'); ?>" class="button button-primary button-large">
        </form>
    <?php endif; ?>
    </form>
	<script type="text/javascript">
		function validate(valid) {
            if (confirm("Do you really want to import the theme demo content?")) {
                // Show loader
                document.getElementById('demo-import-loader').style.display = 'block';
                
                // Submit form
                document.forms[0].submit();
            } else {
                return false;
            }
        }
	</script>
</div>
