<?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 = RSWPTHEMES_AWT_PLUGIN_URL . '/includes/demo-setup/demo-content/books.json';
    $postsUrl = RSWPTHEMES_AWT_PLUGIN_URL . '/includes/demo-setup/demo-content/posts.json';
    $reviewsUrl = RSWPTHEMES_AWT_PLUGIN_URL . '/includes/demo-setup/demo-content/reviews.json';
    $pagesUrl = RSWPTHEMES_AWT_PLUGIN_URL . '/includes/demo-setup/demo-content/pages.json';

    $demo_pages = [
        'Home' => RSWPTHEMES_AWT_PLUGIN_PATH . '/includes/demo-setup/demo-content/home.json',
        'About Me' => RSWPTHEMES_AWT_PLUGIN_PATH . '/includes/demo-setup/demo-content/about.json',
    ];

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

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

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

		case 'import_posts':
		    rswpthemes_import_posts_from_url($postsUrl);
            rswpthemes_import_reviews_from_url($reviewsUrl);
		    wp_send_json_success('Posts imported');
		    break;

        case 'import_templates':
            rswpthemes_awt_setup_demo_pages($demo_pages);
            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');