<?php 
if (isset($_GET['import-demo']) && $_GET['import-demo'] == true) {
 
    // Function to install and activate plugins
    function online_education_lms_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' => 'learnpress',
                'file' => 'learnpress/learnpress.php',
                'url'  => 'https://downloads.wordpress.org/plugin/learnpress.latest-stable.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>';

    }

    // Call the import function
    online_education_lms_import_demo_content();


    // ------- Create Nav Menu --------
$online_education_lms_menuname = 'Main Menus';
$online_education_lms_bpmenulocation = 'primary-menu';
$online_education_lms_menu_exists = wp_get_nav_menu_object($online_education_lms_menuname);

if (!$online_education_lms_menu_exists) {
    $online_education_lms_menu_id = wp_create_nav_menu($online_education_lms_menuname);

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

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

    // Add Home Page to Menu
    wp_update_nav_menu_item($online_education_lms_menu_id, 0, array(
        'menu-item-title' => __('Home', 'online-education-lms'),
        'menu-item-classes' => 'home',
        'menu-item-url' => home_url('/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $online_education_lms_home_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create About Us Page with Dummy Content
    $online_education_lms_about_title = 'About Us';
    $online_education_lms_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.';
    $online_education_lms_about = array(
        'post_type' => 'page',
        'post_title' => $online_education_lms_about_title,
        'post_content' => $online_education_lms_about_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'about-us'
    );
    $online_education_lms_about_id = wp_insert_post($online_education_lms_about);

    // Add About Us Page to Menu
    wp_update_nav_menu_item($online_education_lms_menu_id, 0, array(
        'menu-item-title' => __('About Us', 'online-education-lms'),
        'menu-item-classes' => 'about-us',
        'menu-item-url' => home_url('/about-us/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $online_education_lms_about_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Services Page with Dummy Content
    $online_education_lms_services_title = 'Services';
    $online_education_lms_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.';
    $online_education_lms_services = array(
        'post_type' => 'page',
        'post_title' => $online_education_lms_services_title,
        'post_content' => $online_education_lms_services_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'services'
    );
    $online_education_lms_services_id = wp_insert_post($online_education_lms_services);

    // Add Services Page to Menu
    wp_update_nav_menu_item($online_education_lms_menu_id, 0, array(
        'menu-item-title' => __('Services', 'online-education-lms'),
        'menu-item-classes' => 'services',
        'menu-item-url' => home_url('/services/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $online_education_lms_services_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Pages Page with Dummy Content
    $online_education_lms_pages_title = 'Pages';
    $online_education_lms_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>';
    $online_education_lms_pages = array(
        'post_type' => 'page',
        'post_title' => $online_education_lms_pages_title,
        'post_content' => $online_education_lms_pages_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'pages'
    );
    $online_education_lms_pages_id = wp_insert_post($online_education_lms_pages);

    // Add Pages Page to Menu
    wp_update_nav_menu_item($online_education_lms_menu_id, 0, array(
        'menu-item-title' => __('Pages', 'online-education-lms'),
        'menu-item-classes' => 'pages',
        'menu-item-url' => home_url('/pages/'),
        'menu-item-status' => 'publish',
        'menu-item-object-id' => $online_education_lms_pages_id,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type'
    ));

    // Create Contact Page with Dummy Content
    $online_education_lms_contact_title = 'Contact';
    $online_education_lms_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.';
    $online_education_lms_contact = array(
        'post_type' => 'page',
        'post_title' => $online_education_lms_contact_title,
        'post_content' => $online_education_lms_contact_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => 'contact'
    );
    $online_education_lms_contact_id = wp_insert_post($online_education_lms_contact);

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

        //---Header--//
        set_theme_mod('online_education_lms_first_header_button', 'Dashboard');
        set_theme_mod('online_education_lms_header_first_link', '#');

         // Slider Section
        set_theme_mod('online_education_lms_slider_arrows', true);
        set_theme_mod('online_education_lms_slider_short_heading', 'WELCOME TO LMS EDUCATION THEME');
        set_theme_mod('online_education_lms_show_slider_title', 'Learn Everyday and any new skills with top Instructor.');
        set_theme_mod('online_education_lms_show_slider_content', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.');
        set_theme_mod('online_education_lms_product_btn_text1', 'Explore Cources');
        set_theme_mod('online_education_lms_product_btn_link1', '#');
        set_theme_mod('online_education_lms_product_btn_text2', 'Become an Instructor');
        set_theme_mod('online_education_lms_product_btn_link2', '#');
        set_theme_mod('bakery_patisserie_shop_about_bg1', get_template_directory_uri().'/assets/images/slider-img.png');
        set_theme_mod('online_education_lms_banner_main_tab_heading', 'Learn new skills everyday!');
        set_theme_mod('online_education_lms_banner_main_tab_para', 'Lorem ipsum dolor sit amit.');
        set_theme_mod('online_education_lms_banner_main_tab_icon', 'fas fa-university');


            $course_cat_slug = 'beginner';   
$course_cat_name = 'Beginner';  

if ( ! term_exists( $course_cat_slug, 'course_category' ) ) {
    wp_insert_term(
        $course_cat_name,
        'course_category',
        array( 'slug' => $course_cat_slug )
    );
}

// Demo courses.
$demo_courses = array(
    array(
        'title'      => 'Bachelor Of Science In Data Science And AI',
        'content'    => 'Demo course content for Data Science & AI.',
        'sale_price' => '30.00',
        'duration'   => array( 'duration' => 2, 'unit' => 'week' ),
        'students'   => 50,
        'image'      => get_template_directory_uri() . '/assets/images/course.png',
    ),
    array(
        'title'      => 'Introduction to Machine Learning',
        'content'    => 'Demo course content for Machine Learning.',
        'sale_price' => '45.00',
        'duration'   => array( 'duration' => 2, 'unit' => 'week' ),
        'students'   => 80,
        'image'      => get_template_directory_uri() . '/assets/images/course.png',
    ),
);

require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

foreach ( $demo_courses as $course ) {
    //  FIXED: WP_Query instead of deprecated get_page_by_title()
    $query = new WP_Query( [
        'post_type'      => 'lp_course',
        'post_status'    => 'any',
        'title'          => $course['title'],
        'posts_per_page' => 1,
        'fields'         => 'ids'
    ] );
    
    if ( $query->have_posts() ) {
        $existing_id = $query->posts[0];
        // Ensure category is attached
        wp_set_object_terms( $existing_id, $course_cat_slug, 'course_category', false );
        wp_reset_postdata();
        continue;
    }
    wp_reset_postdata();

    // Create LearnPress course.
    $course_id = wp_insert_post( array(
        'post_title'   => wp_strip_all_tags( $course['title'] ),
        'post_content' => $course['content'],
        'post_status'  => 'publish',
        'post_type'    => 'lp_course',
    ) );

    if ( $course_id && ! is_wp_error( $course_id ) ) {
        // Attach category "Beginner"
        wp_set_object_terms(
            $course_id,
            $course_cat_slug,
            'course_category',
            false
        );

        //  FIXED: Convert duration array to string "2 week"
        $duration_string = $course['duration']['duration'] . ' ' . $course['duration']['unit'];
        
        // LearnPress meta.
        update_post_meta( $course_id, '_lp_sale_price', $course['sale_price'] );
        update_post_meta( $course_id, '_lp_regular_price', $course['sale_price'] );
        update_post_meta( $course_id, '_lp_max_students', $course['students'] );
        update_post_meta( $course_id, '_lp_duration', $duration_string ); //  FIXED

        // Featured image.
        if ( ! empty( $course['image'] ) ) {
            $image_src = media_sideload_image( $course['image'], $course_id, null, 'src' );
            if ( ! is_wp_error( $image_src ) ) {
                $attach_id = attachment_url_to_postid( $image_src );
                if ( $attach_id ) {
                    set_post_thumbnail( $course_id, $attach_id );
                }
            }
        }
    }
}

// Customizer settings.
set_theme_mod( 'online_education_lms_online_courses_per_page', 2 );
set_theme_mod( 'online_education_lms_save_link', '#' );
set_theme_mod( 'online_education_lms_courses_small_img', get_template_directory_uri() . '/assets/images/small-img.png' );
set_theme_mod( 'online_education_lms_online_courses_category', $course_cat_slug );

        // About Section
        set_theme_mod('online_education_lms_about_show_hide', true);
        set_theme_mod('online_education_lms_service_sub_heading', 'About Us');
    set_theme_mod( 'online_education_lms_about_bg', get_template_directory_uri() . '/assets/images/about-bg.png' );

        set_theme_mod('online_education_lms_about_video_bg', get_template_directory_uri().'/assets/images/abt-video.png' );
        set_theme_mod('online_education_lms_youtube_url', '#');

        set_theme_mod('online_education_lms_main_tab_heading1', '100% Certified Courses');
        set_theme_mod('online_education_lms_main_tab_heading2', 'Learn any where');
        set_theme_mod('online_education_lms_main_tab_para1', 'Lorem Ipsum is simply dummy text of the printing industry.');
        set_theme_mod('online_education_lms_main_tab_para2', 'Lorem Ipsum is simply dummy text of the printing industry.');
        set_theme_mod('online_education_lms_main_tab_icon1', 'fas fa-university');
        set_theme_mod('online_education_lms_main_tab_icon2', 'fas fa-university');

        set_theme_mod('online_education_lms_tab_icon1', 'fas fa-check');
        set_theme_mod('online_education_lms_tab_icon2', 'fas fa-check');
        set_theme_mod('online_education_lms_tab_icon3', 'fas fa-check');
        set_theme_mod('online_education_lms_tab_heading1', 'Get access to 4,000+ of our top courses.');
        set_theme_mod('online_education_lms_tab_heading2', 'Find the right instructor for you.');
        set_theme_mod('online_education_lms_tab_heading3', 'Very fast & so easy to create.');

        set_theme_mod('online_education_lms_abt_button', 'More About Us');
        set_theme_mod('online_education_lms_abt_link', '#');

        set_theme_mod('online_education_lms_customer_review', '12 M+');

        // Create About page and set the featured image
        $online_education_lms_abt_title = 'Take the next step toward your personal & professional goals';
        $online_education_lms_abt_content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys 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.';

        $my_post = array(
            'post_title'    => wp_strip_all_tags($online_education_lms_abt_title),
            'post_content'  => $online_education_lms_abt_content,
            'post_status'   => 'publish',
            'post_type'     => 'page',
        );

        $post_id = wp_insert_post($my_post);

        if ($post_id) {
            set_theme_mod('online_education_lms_about_page', $post_id);
            $image_url = get_template_directory_uri() . '/assets/images/about-img.png';
            $image_id = media_sideload_image($image_url, $post_id, null, 'id');
            if (!is_wp_error($image_id)) {
                set_post_thumbnail($post_id, $image_id);
            }
        }

        // Define post category names
        $online_education_lms_category_names = array('postcategory1');

        // Set theme mod values for the customer review and selected category
        set_theme_mod('online_education_lms_customer_review', '1500+');
        set_theme_mod('online_education_lms_about_catData', 'postcategory1');

        foreach ($online_education_lms_category_names as $online_education_lms_category_name) {
            // Check if the category exists, and insert if necessary
            $online_education_lms_term = term_exists($online_education_lms_category_name, 'category');
            
            if (!$online_education_lms_term) {
                $online_education_lms_term = wp_insert_term($online_education_lms_category_name, 'category');
            }

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

            // Ensure the term ID is retrieved correctly
            $online_education_lms_term_id = is_array($online_education_lms_term) ? $online_education_lms_term['term_id'] : $online_education_lms_term;

            // Loop for creating posts under the category
            for ($online_education_lms_i = 0; $online_education_lms_i < 4; $online_education_lms_i++) {
                $online_education_lms_my_post = array(
                    'post_title'   => 'Post ' . ($online_education_lms_i + 1),
                    'post_content' => 'This is the content for post ' . ($online_education_lms_i + 1),
                    'post_status'  => 'publish',
                    'post_type'    => 'post',
                );

                $online_education_lms_post_id = wp_insert_post($online_education_lms_my_post);
                if (is_wp_error($online_education_lms_post_id)) {
                    error_log('Error creating post: ' . $online_education_lms_post_id->get_error_message());
                    continue;
                }

                // Assign the category to the post
                wp_set_post_categories($online_education_lms_post_id, array($online_education_lms_term_id));

                // Handle featured image
                $online_education_lms_image_url = get_template_directory_uri() . '/assets/images/customer' . ($online_education_lms_i + 1) . '.png';
                $online_education_lms_image_id = media_sideload_image($online_education_lms_image_url, $online_education_lms_post_id, null, 'id');

                if (!is_wp_error($online_education_lms_image_id)) {
                    set_post_thumbnail($online_education_lms_post_id, $online_education_lms_image_id);
                }
            }
        }
        

    }
?>