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

    // Function to install and activate plugins
    function newspaper_magazine_blog_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' => '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
    newspaper_magazine_blog_import_demo_content();

    // ------- Create Nav Menu --------
$newspaper_magazine_blog_menuname = 'Main Menus';
$newspaper_magazine_blog_bpmenulocation = 'primary-menu';
$newspaper_magazine_blog_menu_exists = wp_get_nav_menu_object($newspaper_magazine_blog_menuname);

if (!$newspaper_magazine_blog_menu_exists) {
    $newspaper_magazine_blog_menu_id = wp_create_nav_menu($newspaper_magazine_blog_menuname);

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

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

    // Add Home Page to Menu
    wp_update_nav_menu_item($newspaper_magazine_blog_menu_id, 0, array(
        'menu-item-title' => __('Home', 'newspaper-magazine-blog'),
        'menu-item-classes' => 'home',
        'menu-item-url' => home_url('/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $newspaper_magazine_blog_home_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create About Us Page with Dummy Content
    $newspaper_magazine_blog_about_title = 'About Us';
    $newspaper_magazine_blog_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.';
    $newspaper_magazine_blog_about = array(
        'post_type' => 'page',
        'post_title' => $newspaper_magazine_blog_about_title,
        'post_content' => $newspaper_magazine_blog_about_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'about-us'
    );
    $newspaper_magazine_blog_about_id = wp_insert_post($newspaper_magazine_blog_about);

    // Add About Us Page to Menu
    wp_update_nav_menu_item($newspaper_magazine_blog_menu_id, 0, array(
        'menu-item-title' => __('About Us', 'newspaper-magazine-blog'),
        'menu-item-classes' => 'about-us',
        'menu-item-url' => home_url('/about-us/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $newspaper_magazine_blog_about_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Services Page with Dummy Content
    $newspaper_magazine_blog_services_title = 'Services';
    $newspaper_magazine_blog_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.';
    $newspaper_magazine_blog_services = array(
        'post_type' => 'page',
        'post_title' => $newspaper_magazine_blog_services_title,
        'post_content' => $newspaper_magazine_blog_services_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'services'
    );
    $newspaper_magazine_blog_services_id = wp_insert_post($newspaper_magazine_blog_services);

    // Add Services Page to Menu
    wp_update_nav_menu_item($newspaper_magazine_blog_menu_id, 0, array(
        'menu-item-title' => __('Services', 'newspaper-magazine-blog'),
        'menu-item-classes' => 'services',
        'menu-item-url' => home_url('/services/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $newspaper_magazine_blog_services_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Pages Page with Dummy Content
    $newspaper_magazine_blog_pages_title = 'Pages';
    $newspaper_magazine_blog_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>';
    $newspaper_magazine_blog_pages = array(
        'post_type' => 'page',
        'post_title' => $newspaper_magazine_blog_pages_title,
        'post_content' => $newspaper_magazine_blog_pages_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'pages'
    );
    $newspaper_magazine_blog_pages_id = wp_insert_post($newspaper_magazine_blog_pages);

    // Add Pages Page to Menu
    wp_update_nav_menu_item($newspaper_magazine_blog_menu_id, 0, array(
        'menu-item-title' => __('Pages', 'newspaper-magazine-blog'),
        'menu-item-classes' => 'pages',
        'menu-item-url' => home_url('/pages/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $newspaper_magazine_blog_pages_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Contact Page with Dummy Content
    $newspaper_magazine_blog_contact_title = 'Contact';
    $newspaper_magazine_blog_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.';
    $newspaper_magazine_blog_contact = array(
        'post_type' => 'page',
        'post_title' => $newspaper_magazine_blog_contact_title,
        'post_content' => $newspaper_magazine_blog_contact_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'contact'
    );
    $newspaper_magazine_blog_contact_id = wp_insert_post($newspaper_magazine_blog_contact);

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

        //---Header--//
        set_theme_mod('newspaper_magazine_blog_query_text', 'Have any question?');
        set_theme_mod('newspaper_magazine_blog_query_link', '#');

        set_theme_mod('newspaper_magazine_blog_mail', 'magazine@example.com');
        set_theme_mod('newspaper_magazine_blog_call', '+91-1234-456-789');

        set_theme_mod('newspaper_magazine_blog_interactive_globe_symbol', '#');

        set_theme_mod('newspaper_magazine_blog_subscribe_text', 'Subscribe');
        set_theme_mod('newspaper_magazine_blog_subscribe_link', '#');

        set_theme_mod('newspaper_magazine_blog_sign_in_text', 'Sign in');
        set_theme_mod('newspaper_magazine_blog_sign_in_link', '#');
        
        
       // Enable the section and set the number of categories (tabs)
        set_theme_mod('newspaper_magazine_blog_slider_section_show', true);
        set_theme_mod('newspaper_magazine_blog_projetcs_number', '7');

        set_theme_mod('holiday_vacation_tab_icon1', 'fas fa-home');
        set_theme_mod('newspaper_magazine_blog_project_tab_image1', get_template_directory_uri().'/assets/images/tab1.png');
        set_theme_mod('newspaper_magazine_blog_project_tab_image2', get_template_directory_uri().'/assets/images/tab2.png');
        set_theme_mod('newspaper_magazine_blog_project_tab_image3', get_template_directory_uri().'/assets/images/tab3.png');
        set_theme_mod('newspaper_magazine_blog_project_tab_image4', get_template_directory_uri().'/assets/images/tab4.png');
        set_theme_mod('newspaper_magazine_blog_project_tab_image5', get_template_directory_uri().'/assets/images/tab5.png');
        set_theme_mod('newspaper_magazine_blog_project_tab_image6', get_template_directory_uri().'/assets/images/tab6.png');
        set_theme_mod('newspaper_magazine_blog_project_tab_image7', get_template_directory_uri().'/assets/images/tab7.png');

        // Create one category: postcategory1
        $category_name = 'postcategory1';
        $category_id = wp_create_category($category_name);

        // Set tab titles and assign same category to all
        $tab_titles = array('Food', 'Animal', 'car', 'Sport', 'Music', 'Technology', 'Abstract');

        for ($i = 1; $i <= 6; $i++) {
            set_theme_mod('newspaper_magazine_blog_projetcs_text' . $i, $tab_titles[$i - 1]);
            set_theme_mod('newspaper_magazine_blog_projetcs_category' . $i, $category_name);
        }

        // Create demo posts under 'postcategory1'
        $blog_titles = array(
            'Game Changing Virtual Reality Console Technologyaaa Profit To Serve The Community',
            'New Modern Iphone 14pro Max Extrea Revolutionary Features',
            'A Guide To Image Optimization On Jamstack Sites',
            'Using Automated Test Results To Improve Accessibility'
        );

        for ($i = 1; $i <= count($blog_titles); $i++) {
            $title = $blog_titles[$i - 1];

            $newspaper_magazine_blog_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($title),
                'post_content'  => $newspaper_magazine_blog_content,
                'post_status' => 'publish',
                'post_type'   => 'post',
                'post_category' => array($category_id)
            );

            $post_id = wp_insert_post($my_post);

            // Add featured image
            $image_url = get_template_directory_uri() . '/assets/images/post-img' . $i . '.png';
            $image_name = 'blogs' . $i . '.png';

            $upload_dir = wp_upload_dir();
            $image_data = @file_get_contents($image_url);

            if ($image_data === false) {
                continue;
            }

            $unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
            $filename = basename($unique_file_name);
            $file = $upload_dir['path'] . '/' . $filename;

            if (!function_exists('WP_Filesystem')) {
                require_once(ABSPATH . 'wp-admin/includes/file.php');
            }

            WP_Filesystem();
            global $wp_filesystem;

            if (!$wp_filesystem->put_contents($file, $image_data, FS_CHMOD_FILE)) {
                continue;
            }

            $wp_filetype = wp_check_filetype($filename, null);

            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title'     => sanitize_file_name($filename),
                'post_content'   => '',
                'post_status'    => 'inherit'
            );

            $attach_id = wp_insert_attachment($attachment, $file, $post_id);

            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $file);
            wp_update_attachment_metadata($attach_id, $attach_data);
            set_post_thumbnail($post_id, $attach_id);
        }

    // Our Services Section
    set_theme_mod('newspaper_magazine_blog_featured_section_title', 'CATEGORY');
    set_theme_mod('newspaper_magazine_blog_product_section_btn_text1', 'View All');
    set_theme_mod('newspaper_magazine_blog_product_section_btn_link1', '#');

    // Define post categories and their posts
        $custom_blog_categories = array(
            'Football' => array('Lorem Ipsum is simply dummy', 'Lorem Ipsum is simply dummy'),
            'social' => array('Lorem Ipsum is simply dummy', 'Lorem Ipsum is simply dummy'),
            'HEALTH' => array('Lorem Ipsum is simply dummy', 'Lorem Ipsum is simply dummy'),
            'TECHNOLOGY' => array('Lorem Ipsum is simply dummy', 'Lorem Ipsum is simply dummy'),
        );

        $upload_dir = wp_upload_dir();

        // Make sure WP_Filesystem is available
        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        WP_Filesystem();
        global $wp_filesystem;

        $index = 1;

        foreach ($custom_blog_categories as $cat_name => $post_titles) {
            // Create the category
            $cat_result = wp_insert_term(
                $cat_name,
                'category',
                array(
                    'description' => 'Auto-generated category: ' . $cat_name,
                    'slug' => sanitize_title($cat_name)
                )
            );

            if (is_wp_error($cat_result)) {
                // Skip if error (like already exists)
                $term_obj = get_term_by('slug', sanitize_title($cat_name), 'category');
                $term_id = $term_obj ? $term_obj->term_id : 0;
            } else {
                $term_id = $cat_result['term_id'];
            }

            // Optional: Add image to category via term meta (for themes/plugins that support it)
            $image_path = get_template_directory() . '/assets/images/cat' . $index . '.png';
            if (file_exists($image_path)) {
                $image_data = file_get_contents($image_path);
                $filename = 'cat' . $index . '.png';
                $file = trailingslashit($upload_dir['path']) . $filename;

                if ($wp_filesystem->put_contents($file, $image_data, FS_CHMOD_FILE)) {
                    $wp_filetype = wp_check_filetype($filename, null);
                    $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title' => sanitize_file_name($filename),
                        'post_status' => 'inherit',
                    );

                    $attach_id = wp_insert_attachment($attachment, $file);
                    require_once ABSPATH . 'wp-admin/includes/image.php';
                    $attach_data = wp_generate_attachment_metadata($attach_id, $file);
                    wp_update_attachment_metadata($attach_id, $attach_data);

                    // Save image to category (if your theme/plugin supports it)
                    update_term_meta($term_id, 'category_image_id', $attach_id);
                }
            }

            // Insert demo posts
            foreach ($post_titles as $post_title) {
                $post_id = wp_insert_post(array(
                    'post_title' => wp_strip_all_tags($post_title),
                    'post_content' => 'This is an auto-generated post for category: ' . $cat_name,
                    'post_status' => 'publish',
                    'post_type' => 'post',
                    'post_category' => array($term_id),
                ));

                // Set featured image for post
                $slug = sanitize_title($post_title);
                $post_image_path = get_template_directory() . '/assets/images/post-img' . $slug . '.png';

                if (file_exists($post_image_path)) {
                    $post_image_data = file_get_contents($post_image_path);
                    $post_filename = 'post-img' . $slug . '.png';
                    $post_file = trailingslashit($upload_dir['path']) . $post_filename;

                    if ($wp_filesystem->put_contents($post_file, $post_image_data, FS_CHMOD_FILE)) {
                        $wp_filetype = wp_check_filetype($post_filename, null);
                        $attachment = array(
                            'post_mime_type' => $wp_filetype['type'],
                            'post_title' => sanitize_file_name($post_filename),
                            'post_status' => 'inherit',
                        );

                        $attach_id = wp_insert_attachment($attachment, $post_file, $post_id);
                        require_once ABSPATH . 'wp-admin/includes/image.php';
                        $attach_data = wp_generate_attachment_metadata($attach_id, $post_file);
                        wp_update_attachment_metadata($attach_id, $attach_data);

                        set_post_thumbnail($post_id, $attach_id);
                    }
                }
            }

            $index++;
        }        

    }
?>