<div class="theme-offer">
<?php

function legacy_videography_create_customizer_nav_menu() {
    $legacy_videography_menuname = 'Primary';
    $legacy_videography_menulocation = 'primary';
    $legacy_videography_menu_exists = wp_get_nav_menu_object($legacy_videography_menuname);

    if (!$legacy_videography_menu_exists) {
        $legacy_videography_menu_id = wp_create_nav_menu($legacy_videography_menuname);

        wp_update_nav_menu_item($legacy_videography_menu_id, 0, array(
            'menu-item-title' => __('Home', 'legacy-videography'),
            'menu-item-url' => home_url('/'),
            'menu-item-status' => 'publish',
        ));

        wp_update_nav_menu_item($legacy_videography_menu_id, 0, array(
            'menu-item-title' => __('About Us', 'legacy-videography'),
            'menu-item-url' => home_url('/index.php/about-us/'),
            'menu-item-status' => 'publish',
        ));

        wp_update_nav_menu_item($legacy_videography_menu_id, 0, array(
            'menu-item-title' => __('Services', 'legacy-videography'),
            'menu-item-url' => home_url('/index.php/services/'),
            'menu-item-status' => 'publish',
        ));

        wp_update_nav_menu_item($legacy_videography_menu_id, 0, array(
            'menu-item-title' => __('Pages', 'legacy-videography'),
            'menu-item-url' => home_url('/index.php/pages/'),
            'menu-item-status' => 'publish',
        ));

        wp_update_nav_menu_item($legacy_videography_menu_id, 0, array(
            'menu-item-title' => __('Blog', 'legacy-videography'),
            'menu-item-url' => home_url('/index.php/blog/'),
            'menu-item-status' => 'publish',
        ));

        $legacy_videography_locations = get_theme_mod('nav_menu_locations');
        if (!is_array($legacy_videography_locations)) {
            $legacy_videography_locations = array();
        }
        $legacy_videography_locations[$legacy_videography_menulocation] = $legacy_videography_menu_id;
        set_theme_mod('nav_menu_locations', $legacy_videography_locations);
    }
}

function legacy_videography_importer_attach_image( $image_url, $post_id ) {

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

    $image_name= 'Team'.$post_id.'.png';

    if ( ! $image_data ) return false;

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

    if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'].'/'.$filename;
    } else {
            $file = $upload_dir['basedir'].'/'.$filename;
    }

    file_put_contents($file, $image_data);
    $wp_filetype = wp_check_filetype($filename, null);

    $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title'     => sanitize_file_name($filename),
            'post_type'      => 'services',
            '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);

    return $attach_id;
}

if (isset($_POST['submit'])) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
    include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
    include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
    include_once(ABSPATH . 'wp-admin/includes/file.php');
    include_once(ABSPATH . 'wp-admin/includes/misc.php');

    $legacy_videography_plugins = array(
        array(
            'slug' => 'classic-widgets',
            'file' => 'classic-widgets/classic-widgets.php',
            'download_url' => 'https://downloads.wordpress.org/plugin/classic-widgets.zip'
        ),
        array(
            'slug' => 'tlp-team',
            'file' => 'tlp-team/tlp-team.php',
            'download_url' => 'https://downloads.wordpress.org/plugin/tlp-team.zip'
        )
    );


    foreach ($legacy_videography_plugins as $plugin) {
        $installed_plugins = get_plugins();
        if (!isset($installed_plugins[$plugin['file']])) {
            $upgrader = new Plugin_Upgrader();
            $upgrader->install($plugin['download_url']);
        }

        if (file_exists(WP_PLUGIN_DIR . '/' . $plugin['file']) && !is_plugin_active($plugin['file'])) {
            activate_plugin($plugin['file']);
        }
    }

    // Function to create a page if it doesn't exist
    function create_demo_page($title, $content = '', $template = '') {
        $page_id = legacy_videography_get_page_id_by_title($title); // use existing function

        if (!$page_id) {
            $page_data = array(
                'post_type'    => 'page',
                'post_title'   => $title,
                'post_content' => $content,
                'post_status'  => 'publish',
                'post_author'  => 1,
            );

            $page_id = wp_insert_post($page_data);

            if ($template && !is_wp_error($page_id)) {
                update_post_meta($page_id, '_wp_page_template', $template);
            }
        }

        return $page_id;
    }

    // Create and assign pages
    $legacy_videography_home_id = create_demo_page('Home', '', 'home/home.php');
    update_option('page_on_front', $legacy_videography_home_id);
    update_option('show_on_front', 'page');

    create_demo_page('Pages', '<p>Lorem Ipsum ...</p>');
    create_demo_page('About Us', '<p>Lorem Ipsum ...</p>');
    create_demo_page('Services', '<p>Service description...</p>');

    // Create blog page and assign it to display posts
    $blog_page_id = create_demo_page('Blog');
    update_option('page_for_posts', $blog_page_id);

    // Create the nav menu
    legacy_videography_create_customizer_nav_menu();

        // ------- Set Theme Mods --------
        
        set_theme_mod('legacy_videography_social_media1_heading', 'www.facebook.com');
        set_theme_mod('legacy_videography_social_media2_heading', 'www.instagram.com');
        set_theme_mod('legacy_videography_social_media3_heading', 'www.twitter.com');
        set_theme_mod('legacy_videography_social_media5_heading', 'www.pinterest.com');
        set_theme_mod('legacy_videography_social_media4_heading', 'www.youtube.com');
        set_theme_mod('legacy_videography_social_media6_heading', 'www.linkedin.com');

        // ------- Banner Section --------

        set_theme_mod("legacy_videography_home_enable_banner_settings", true);

        $legacy_videography_banner_headings = array('Outstanding Studio For Making Movies & Films', 'An exceptional studio for film production');
        set_theme_mod('legacy_videography_slide_number', 2);
        for ($i = 1; $i <= 2; $i++) {
            set_theme_mod("legacy_videography_slide_image$i", get_template_directory_uri() . "/img/banner$i.png");
            set_theme_mod("legacy_videography_slide_heading$i", $legacy_videography_banner_headings[$i - 1]);
            set_theme_mod("legacy_videography_slide_sub_heading$i", 'Welcome To Videographer');
            set_theme_mod("legacy_videography_slide_text$i", 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.');
            set_theme_mod("legacy_videography_slide_btnurl$i", '#');
            set_theme_mod("legacy_videography_slide_btntext$i", 'Read More');
        }

        // ------- Services Section --------
        set_theme_mod('legacy_videography_destination_small_heading', 'Our Team');
        set_theme_mod('legacy_videography_destination_main_heading', 'Our Best Videographer');

        // Exit if TLP Team plugin (CPT 'team') does not exist
        if ( ! post_type_exists( 'team' ) ) {
            return;
        }

        $socials_arr = array(
            array(
                "id" => "facebook",
                "url" => "#"
            ),
            array(
                "id" => "twitter",
                "url" => "#"
            ),
            array(
                "id" => "linkedin",
                "url" => "#"
            ),
            array(
                "id" => "instagram",
                "url" => "#"
            ),
            array(
                "id" => "youtube",
                "url" => "#"
            )
        );

        // Demo data for team members
        $demo_team_members = array(
            array(
                'name' => 'John Doe',
                'designation' => 'Founder & CEO',
                'image' => '/img/teams1.png',
                'social' => $socials_arr,
            ),
            array(
                'name' => 'Travis Smith',
                'designation' => 'Head Videographer',
                'image' => '/img/teams2.png',
                'social' => $socials_arr,
            ),
            array(
                'name' => 'Michael Brown',
                'designation' => 'Lead Photographer',
                'image' => '/img/teams3.png',
                'social' => $socials_arr,
            ),
            array(
                'name' => 'Tim Johnson',
                'designation' => 'Project Manager',
                'image' => '/img/teams4.png',
                'social' => $socials_arr,
            ),
            array(
                'name' => 'David Williams',
                'designation' => 'UI/UX Designer',
                'image' => '/img/teams5.png',
                'social' => $socials_arr,
            )
        );

        foreach ( $demo_team_members as $member ) {

            // Check if team member already exists using WP_Query
            $existing_member = new WP_Query( array(
                'post_type'      => 'team',
                'title'          => $member['name'],
                'posts_per_page' => 1,
                'fields'         => 'ids',
            ) );

            if ( $existing_member->have_posts() ) {
                continue; // Skip if already exists
            }

            // Create the team post
            $team_id = wp_insert_post( array(
                'post_title'   => $member['name'],
                'post_type'    => 'team',
                'post_status'  => 'publish',
                'post_content' => 'This is demo content for ' . $member['name'] . '.',
            ) );

            if ( $team_id ) {

                // Assign designation term
                wp_set_object_terms( $team_id, $member['designation'], 'team_designation', true );

                // Upload and set featured image from theme folder
                $image_path = get_template_directory() . $member['image'];
                
                if ( file_exists( $image_path ) ) {

                    $image_url = get_template_directory_uri() . $member['image'];
                    $image_id  = legacy_videography_importer_attach_image( $image_url, $team_id );

                    if ( $image_id ) {
                        set_post_thumbnail( $team_id, $image_id );
                    }
                }

                // Add social links as post meta
                update_post_meta( $team_id, 'social', $member['social'] );
            }
        }

        
        echo '<div class="success">Demo Import Successful</div>';
    }
?>

<ul>
    <li>
        <hr>
        <?php if (!isset($_POST['submit'])) : ?>
            <?php echo esc_html__('Click on the below button to get demo content installed.', 'legacy-videography'); ?>
            <br>
            <form id="demo-importer-form" action="" method="POST" onsubmit="return confirm('Do you really want to do this?');">
                <input class="run-btn" type="submit" name="submit" value="<?php echo esc_attr('Run Importer', 'legacy-videography'); ?>">
            </form>
        <?php else: ?>
            <div class="visit">
                <a href="<?php echo esc_url(home_url()); ?>" class="button button-primary button-large run-btn" style="margin-top: 10px;" target="_blank">View Site</a>
            </div>
        <?php endif; ?>
        <hr>
    </li>
</ul>
</div>