<?php
/**
 * Handle AJAX request for setup steps.
 */
function setup_demo_ajax_handler() {
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'setup_demo_nonce')) {
        wp_send_json_error('Invalid request');
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error('Permission denied');
    }

    $booksUrl = get_theme_file_uri( '/inc/demo-setup/demo-content/books.json' );
    $postsUrl = get_theme_file_uri( '/inc/demo-setup/demo-content/posts.json' );
    $reviewsUrl = get_theme_file_uri( '/inc/demo-setup/demo-content/reviews.json' );
    $pagesUrl = get_theme_file_uri( '/inc/demo-setup/demo-content/pages.json' );
    $customizer = get_theme_file_path( '/inc/demo-setup/demo-content/customizer.json' );
    $widgets = get_theme_file_path( '/inc/demo-setup/demo-content/widgets.json' );

    $demo_pages = [
        'Home 6' => get_theme_file_path( '/inc/demo-setup/demo-content/home-6.json' ),
        'Home 4' => get_theme_file_path( '/inc/demo-setup/demo-content/home-4.json' ),
        'Home 1' => get_theme_file_path( '/inc/demo-setup/demo-content/home-1.json' ),
        'About Me' => get_theme_file_path( '/inc/demo-setup/demo-content/about.json' ),
    ];

    $step = isset($_POST['step']) ? sanitize_text_field($_POST['step']) : '';

    switch ($step) {
        case 'install_plugins':
            book_author_blog_install_and_activate_plugins();
            wp_send_json_success('Plugins installed & activated');
            break;

        case 'import_books':
            book_author_blog_import_books_from_url($booksUrl);
            wp_send_json_success('Books imported');
            break;

		case 'import_posts':
		    book_author_blog_import_posts_from_json_url($postsUrl);
            book_author_blog_import_reviews_from_json_url($reviewsUrl);
            book_author_blog_import_widgets_from_json_url($widgets);
            book_author_blog_import_customizer_settings_from_json_url($customizer);
		    wp_send_json_success('Posts imported');
		    break;

        case 'import_templates':
            book_author_blog_setup_demo_pages($demo_pages);
            update_option('book_author_blog_demo_setup_completed', true);
            // Mark demo as completed after the last step
            error_log('Setting permalink structure to /%postname%/');
            update_option('permalink_structure', '/%postname%/');
            error_log('Flushing rewrite rules');
            flush_rewrite_rules();
            wp_send_json_success('Elementor templates applied');
            break;

        default:
            wp_send_json_error('Invalid step');
    }
}
add_action('wp_ajax_setup_demo_ajax', 'setup_demo_ajax_handler');


function book_author_blog_new_get_page_by_title($page_title, $output = OBJECT, $post_type = 'page') {
    $args = array(
        'post_type'              => $post_type,
        'post_status'            => 'published',
        'posts_per_page'         => 1,
        'no_found_rows'          => true,
        'orderby'                => 'post_date ID',
        'order'                  => 'ASC',
        'title'                  => $page_title, // ✅ Now using the correct parameter
    );

    $query = new WP_Query($args);
    $pages = $query->posts;

    if (empty($pages)) {
        return null;
    }

    return get_post($pages[0], $output);
}


/**
 * Create Menu and Assign Imported Pages
 */
function book_author_blog_setup_demo_menu($imported_pages) {
    if (empty($imported_pages)) {
        return;
    }

    $menu_name = 'Demo Menu';
    $menu_exists = wp_get_nav_menu_object($menu_name);

    // Create the menu if it doesn't exist
    if (!$menu_exists) {
        $menu_id = wp_create_nav_menu($menu_name);
    } else {
        $menu_id = $menu_exists->term_id;
    }

    // Assign pages to the menu
    foreach ($imported_pages as $page_id) {
        wp_update_nav_menu_item($menu_id, 0, [
            'menu-item-object-id'   => $page_id,
            'menu-item-object'      => 'page',
            'menu-item-type'        => 'post_type',
            'menu-item-status'      => 'publish',
        ]);
    }

    // Assign the menu to the primary location (if the theme supports it)
    $locations = get_theme_mod('nav_menu_locations');
    if (!is_array($locations)) {
        $locations = [];
    }
    $locations['main-menu'] = $menu_id; // Assign menu to 'primary' location
    $locations['footer-menu'] = $menu_id; // Assign menu to 'primary' location
    set_theme_mod('nav_menu_locations', $locations);
}

