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

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

            // Check if the Charitable plugin is installed and activated
            if (!is_plugin_active('charitable/charitable.php')) {
                $charity_welfare_funds_charitable_plugin_slug = 'charitable';
                $charity_welfare_funds_charitable_plugin_file = 'charitable/charitable.php';

                // Check if the plugin is installed
                $charity_welfare_funds_installed_plugins = get_plugins();
                if (!isset($charity_welfare_funds_installed_plugins[$charity_welfare_funds_charitable_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 Charitable plugin
                    $charity_welfare_funds_upgrader = new Plugin_Upgrader();
                    $charity_welfare_funds_upgrader->install('https://downloads.wordpress.org/plugin/charitable.latest-stable.zip');
                }

                // Activate the Charitable plugin
                activate_plugin($charity_welfare_funds_charitable_plugin_file);
            }

            // ------- Create Nav Menu --------
            $charity_welfare_funds_menuname = 'Main Menus';
            $charity_welfare_funds_bpmenulocation = 'primary';
            $charity_welfare_funds_menu_exists = wp_get_nav_menu_object($charity_welfare_funds_menuname);

            if (!$charity_welfare_funds_menu_exists) {
                $charity_welfare_funds_menu_id = wp_create_nav_menu($charity_welfare_funds_menuname);

                // Create Home Page
                $charity_welfare_funds_home_title = 'Home';
                $charity_welfare_funds_home = array(
                    'post_type' => 'page',
                    'post_title' => $charity_welfare_funds_home_title,
                    'post_content' => '',
                    'post_status' => 'publish',
                    'post_author' => 1,
                    'post_slug' => 'home'
                );
                $charity_welfare_funds_home_id = wp_insert_post($charity_welfare_funds_home);
                // Assign Home Page Template
                add_post_meta($charity_welfare_funds_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', $charity_welfare_funds_home_id);
                update_option('show_on_front', 'page');
                // Add Home Page to Menu
                wp_update_nav_menu_item($charity_welfare_funds_menu_id, 0, array(
                    'menu-item-title' => __('Home', 'charity-welfare-funds'),
                    'menu-item-classes' => 'home',
                    'menu-item-url' => home_url('/'),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $charity_welfare_funds_home_id,
                    'menu-item-object' => 'page',
                    'menu-item-type' => 'post_type'
                ));

                // Create About Us Page with Dummy Content
                $charity_welfare_funds_about_title = 'About Us';
                $charity_welfare_funds_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.';
                $charity_welfare_funds_about = array(
                    'post_type' => 'page',
                    'post_title' => $charity_welfare_funds_about_title,
                    'post_content' => $charity_welfare_funds_about_content,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    'post_slug' => 'about-us'
                );
                $charity_welfare_funds_about_id = wp_insert_post($charity_welfare_funds_about);
                // Add About Us Page to Menu
                wp_update_nav_menu_item($charity_welfare_funds_menu_id, 0, array(
                    'menu-item-title' => __('About Us', 'charity-welfare-funds'),
                    'menu-item-classes' => 'about-us',
                    'menu-item-url' => home_url('/about-us/'),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $charity_welfare_funds_about_id,
                    'menu-item-object' => 'page',
                    'menu-item-type' => 'post_type'
                ));

                // Create Pages Page with Dummy Content
                $charity_welfare_funds_event_title = 'Event';
                $charity_welfare_funds_event_content = 'Explore all the event 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 shoply 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.';
                $charity_welfare_funds_event = array(
                    'post_type' => 'page',
                    'post_title' => $charity_welfare_funds_event_title,
                    'post_content' => $charity_welfare_funds_event_content,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    'post_slug' => 'event'
                );
                $charity_welfare_funds_event_id = wp_insert_post($charity_welfare_funds_event);
                // Add Pages Page to Menu
                wp_update_nav_menu_item($charity_welfare_funds_menu_id, 0, array(
                    'menu-item-title' => __('event', 'charity-welfare-funds'),
                    'menu-item-classes' => 'event',
                    'menu-item-url' => home_url('/event/'),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $charity_welfare_funds_event_id,
                    'menu-item-object' => 'page',
                    'menu-item-type' => 'post_type'
                ));

                // Create Blog Page 
                $charity_welfare_funds_blog_page_title = 'Blog';
                $charity_welfare_funds_blog_page_query = new WP_Query(array(
                    'post_type'      => 'page',
                    'name'           => sanitize_title($charity_welfare_funds_blog_page_title),
                    'post_status'    => 'publish',
                    'posts_per_page' => 1
                ));
                if (!$charity_welfare_funds_blog_page_query->have_posts()) {
                    $charity_welfare_funds_blog_page = array(
                    'post_type'   => 'page',
                    'post_title'  => $charity_welfare_funds_blog_page_title,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    );
                    $charity_welfare_funds_blog_page_id = wp_insert_post($charity_welfare_funds_blog_page);
                    update_option('page_for_posts', $charity_welfare_funds_blog_page_id);
                    wp_update_nav_menu_item($charity_welfare_funds_menu_id, 0, array(
                    'menu-item-title'      => __('Blog', 'charity-welfare-funds'),
                    'menu-item-url'        => get_permalink($charity_welfare_funds_blog_page_id),
                    'menu-item-status'     => 'publish',
                    'menu-item-object-id'  => $charity_welfare_funds_blog_page_id,
                    'menu-item-object'     => 'page',
                    'menu-item-type'       => 'post_type',
                    ));
                }

                // Create Pages Page with Dummy Content
                $charity_welfare_funds_contact_title = 'Contact Us';
                $charity_welfare_funds_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.';
                $charity_welfare_funds_contact = array(
                    'post_type' => 'page',
                    'post_title' => $charity_welfare_funds_contact_title,
                    'post_content' => $charity_welfare_funds_contact_content,
                    'post_status' => 'publish',
                    'post_author' => 1,
                    'post_slug' => 'contact'
                );
                $charity_welfare_funds_contact_id = wp_insert_post($charity_welfare_funds_contact);
                // Add Pages Page to Menu
                wp_update_nav_menu_item($charity_welfare_funds_menu_id, 0, array(
                    'menu-item-title' => __('Contact', 'charity-welfare-funds'),
                    'menu-item-classes' => 'contact',
                    'menu-item-url' => home_url('/contact/'),
                    'menu-item-status' => 'publish',
                    'menu-item-object-id' => $charity_welfare_funds_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($charity_welfare_funds_bpmenulocation)) {
                    $charity_welfare_funds_locations = get_theme_mod('nav_menu_locations'); // Use 'nav_menu_locations' to get locations array
                    if (empty($charity_welfare_funds_locations)) {
                        $charity_welfare_funds_locations = array();
                    }
                    $charity_welfare_funds_locations[$charity_welfare_funds_bpmenulocation] = $charity_welfare_funds_menu_id;
                    set_theme_mod('nav_menu_locations', $charity_welfare_funds_locations);
                }
            }

            // Set the demo import completion flag
    		update_option('charity_welfare_funds_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.', 'charity-welfare-funds') . '</p>';
    		echo '<span><a href="' . esc_url(home_url()) . '" class="button button-primary site-btn" target="_blank">' . esc_html__('VIEW SITE', 'charity-welfare-funds') . '</a></span>';
            //end

            //Header 
            set_theme_mod( 'charity_welfare_funds_email_address_text', 'Mail' );
            set_theme_mod( 'charity_welfare_funds_email_address1', 'xyz@example.com' );
            set_theme_mod( 'charity_welfare_funds_phone_text', 'Call Us' );
            set_theme_mod( 'charity_welfare_funds_phone_number', '+00 123 456 7890' );
            set_theme_mod( 'charity_welfare_funds_location_text', 'Location' );
            set_theme_mod( 'charity_welfare_funds_add_location', '1426 washington ave.kentueky' );
            set_theme_mod( 'charity_welfare_funds_header_btn_text', 'Donate Now' );
            set_theme_mod( 'charity_welfare_funds_header_btn_url', '#' );

            //Social Icon
            set_theme_mod( 'charity_welfare_funds_facebook_url', 'https://www.facebook.com' );
            set_theme_mod( 'charity_welfare_funds_instagram_url', 'https://www.instagram.com' );
            set_theme_mod( 'charity_welfare_funds_twitter_url', 'https://www.twitter.com' );
            set_theme_mod( 'charity_welfare_funds_linkedin_url', 'https://www.linkedin.com' );

            //Slider Section
            $charity_welfare_funds_slider_data = array(
                array(
                    'bg_image' => get_template_directory_uri() . '/images/slider1.png',
                    'small_text' => 'Welcome To Charity',
                    'small_text_icon' => 'fa-solid fa-hand-holding-heart',
                    'title' => 'Make Charity The Poor People Get Helping Now',
                    'text' => 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at',
                    'btn_text' => 'Request Fund Rise',
                    'btn_url' => '#',
                    'btn_icon' => 'fa-solid fa-arrow-right',
                ),
                array(
                    'bg_image' => get_template_directory_uri() . '/images/slider2.png',
                    'small_text' => 'Join Our Mission',
                    'small_text_icon' => 'fa-solid fa-heart',
                    'title' => 'Transform Lives: Help the Poor and Make a Difference Today',
                    'text' => 'Together, we can create a better future.',
                    'btn_text' => 'Get Involved',
                    'btn_url' => '#',
                    'btn_icon' => 'fa-solid fa-handshake',
                ),
                array(
                    'bg_image' => get_template_directory_uri() . '/images/slider3.png',
                    'small_text' => 'Your Support Matters',
                    'small_text_icon' => 'fa-solid fa-globe',
                    'title' => 'Your Help Can Change Lives: Support the Needy Today',
                    'text' => 'Your contribution helps us reach more lives.',
                    'btn_text' => 'Support Us',
                    'btn_url' => '#',
                    'btn_icon' => 'fa-solid fa-arrow-circle-right',
                ),
            );
        
            set_theme_mod('charity_welfare_funds_slide_number', count($charity_welfare_funds_slider_data));
        
            foreach ($charity_welfare_funds_slider_data as $charity_welfare_funds_index => $charity_welfare_funds_data) {
                $charity_welfare_funds_i = $charity_welfare_funds_index + 1;
        
                set_theme_mod("charity_welfare_funds_slider_bg_image$charity_welfare_funds_i", $charity_welfare_funds_data['bg_image']);
                set_theme_mod("charity_welfare_funds_slider_small_text$charity_welfare_funds_i", $charity_welfare_funds_data['small_text']);
                set_theme_mod("charity_welfare_funds_slider_small_text_icon$charity_welfare_funds_i", $charity_welfare_funds_data['small_text_icon']);
                set_theme_mod("charity_welfare_funds_slider_title$charity_welfare_funds_i", $charity_welfare_funds_data['title']);
                set_theme_mod("charity_welfare_funds_slider_text$charity_welfare_funds_i", $charity_welfare_funds_data['text']);
                set_theme_mod("charity_welfare_funds_slider_btn_text$charity_welfare_funds_i", $charity_welfare_funds_data['btn_text']);
                set_theme_mod("charity_welfare_funds_slider_btn_url$charity_welfare_funds_i", $charity_welfare_funds_data['btn_url']);
                set_theme_mod("charity_welfare_funds_slider_btn_icon$charity_welfare_funds_i", $charity_welfare_funds_data['btn_icon']);
            }
            
            //Charity Section
            set_theme_mod( 'charity_welfare_funds_section_small_text', 'Dedicated to assisting those in needs' );
            set_theme_mod( 'charity_welfare_funds_section_title', 'Help & Donate Now' );

            if (class_exists('charitable')) {
                // Include WordPress file handling library
                require_once ABSPATH . 'wp-admin/includes/image.php';
                require_once ABSPATH . 'wp-admin/includes/file.php';
                require_once ABSPATH . 'wp-admin/includes/media.php';
            
                // Campaign data (for example)
                $charity_welfare_funds_campaigns = [
                    [
                        'title' => 'Support Education for Underprivileged Children',
                        'content' => 'Your donation can help provide education to children in need.',
                        'goal' => 6000,
                        'donated' => 600,
                        'image' => '/images/charity1.png',
                    ],
                    [
                        'title' => 'Healthcare for Rural Areas',
                        'content' => 'Join us in bringing healthcare to remote regions.',
                        'goal' => 10000,
                        'donated' => 3500,
                        'image' => '/images/charity2.png',
                    ],
                    [
                        'title' => 'Disaster Relief Fund',
                        'content' => 'Help us support families affected by natural disasters.',
                        'goal' => 20000,
                        'donated' => 7500,
                        'image' => '/images/charity3.png',
                    ],
                ];
            
                foreach ($charity_welfare_funds_campaigns as $charity_welfare_funds_data) {
                    // Use WP_Query to check if the post exists by title
                    $charity_welfare_funds_query = new WP_Query([
                        'post_type' => 'campaign',
                        'title'     => $charity_welfare_funds_data['title'],
                        'posts_per_page' => 1,
                        'post_status' => 'publish', // Set to 'publish'
                    ]);
            
                    if ($charity_welfare_funds_query->have_posts()) {
                        // If campaign exists, update it
                        $charity_welfare_funds_existing_campaign = $charity_welfare_funds_query->posts[0];
                        $charity_welfare_funds_campaign_id = $charity_welfare_funds_existing_campaign->ID;
            
                        // Update the post data
                        wp_update_post([
                            'ID' => $charity_welfare_funds_campaign_id,
                            'post_title' => $charity_welfare_funds_data['title'],
                            'post_content' => $charity_welfare_funds_data['content'],
                            'post_status' => 'publish', // Set to 'publish'
                        ]);
            
                        // Update custom meta fields (goal and donated)
                        update_post_meta($charity_welfare_funds_campaign_id, '_campaign_goal', $charity_welfare_funds_data['goal']);
                        update_post_meta($charity_welfare_funds_campaign_id, '_campaign_donated', $charity_welfare_funds_data['donated']);
                    } else {
                        // If campaign does not exist, create a new post
                        $charity_welfare_funds_campaign_id = wp_insert_post([
                            'post_title'   => $charity_welfare_funds_data['title'],
                            'post_content' => $charity_welfare_funds_data['content'],
                            'post_status'  => 'publish', // Set to 'publish'
                            'post_type'    => 'campaign',
                            'meta_input'   => [
                                '_campaign_goal'    => $charity_welfare_funds_data['goal'],
                                '_campaign_donated' => $charity_welfare_funds_data['donated'],
                                '_campaign_description' => '',
                                '_campaign_end_date' => 0,
                                '_campaign_suggested_donations' => array(),
                                '_campaign_allow_custom_donations' => 1,
                                '_campaign_minimum_donation_amount' => '',
                                '_campaign_suggested_donations_default' => '',
                                '_campaign_hide_amount_donated' => '',
                                '_campaign_hide_number_of_donors' => '',
                                '_campaign_hide_percent_raised' => '',
                                '_campaign_hide_time_remaining' => '',
                                '_campaign_donate_button_text' => ''
                            ],
                        ]);
                    }
            
                    if ($charity_welfare_funds_campaign_id) {
                        // Handle image upload (only if an image is specified)
                        if (!empty($charity_welfare_funds_data['image'])) {
                            $charity_welfare_funds_image_path = get_template_directory() . $charity_welfare_funds_data['image'];
            
                            if (file_exists($charity_welfare_funds_image_path)) {
                                $charity_welfare_funds_upload_dir = wp_upload_dir();
                                $charity_welfare_funds_temp_image_path = $charity_welfare_funds_upload_dir['path'] . '/' . basename($charity_welfare_funds_image_path);
            
                                // Try to copy the image to the upload directory
                                if (copy($charity_welfare_funds_image_path, $charity_welfare_funds_temp_image_path)) {
                                    $charity_welfare_funds_file_array = [
                                        'name'     => basename($charity_welfare_funds_temp_image_path),
                                        'tmp_name' => $charity_welfare_funds_temp_image_path,
                                    ];
            
                                    // Upload and attach the image
                                    $charity_welfare_funds_attachment_id = media_handle_sideload($charity_welfare_funds_file_array, $charity_welfare_funds_campaign_id);
                                    if (!is_wp_error($charity_welfare_funds_attachment_id)) {
                                        set_post_thumbnail($charity_welfare_funds_campaign_id, $charity_welfare_funds_attachment_id);
                                    } else {
                                        error_log('Attachment Error: ' . $charity_welfare_funds_attachment_id->get_error_message());
                                    }
            
                                    // Clean up temporary file
                                    if (file_exists($charity_welfare_funds_temp_image_path)) {
                                        if (!@unlink($charity_welfare_funds_temp_image_path)) {
                                            error_log('Failed to delete temporary image file: ' . $charity_welfare_funds_temp_image_path);
                                        }
                                    }
                                } else {
                                    error_log('Failed to copy image: ' . $charity_welfare_funds_image_path);
                                }
                            } else {
                                error_log('Image not found: ' . $charity_welfare_funds_image_path);
                            }
                        }
                    } else {
                        error_log('Failed to create/update campaign: ' . $charity_welfare_funds_data['title']);
                    }
                }
            }
              
            //Copyright Text
            set_theme_mod( 'charity_welfare_funds_footer_text', 'By Buywptemplate' );

        }
    ?>

    <form action="<?php echo esc_url(home_url()); ?>/wp-admin/themes.php?page=charity-welfare-funds-guide-page" method="POST" onsubmit="return validate(this);">
    <?php if (!get_option('charity_welfare_funds_demo_import_completed')) : ?>
        <form method="post">
        <p><?php esc_html_e('Click the below run importer button to import demo content','charity-welfare-funds'); ?></p>
            <input class= "run-import" type="submit" name="submit" value="<?php esc_attr_e('Run Importer','charity-welfare-funds'); ?>" 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>
