<?php
/**
 * Import Posts From JSON
 */
function book_author_blog_import_posts_from_json_url($json_file_url) {
    $response = wp_remote_get($json_file_url);
    if (is_wp_error($response)) return new WP_Error('fetch_error', 'Unable to retrieve JSON file.');

    $json_input = wp_remote_retrieve_body($response);
    $posts = json_decode($json_input, true);

    if (empty($posts) || !is_array($posts)) return new WP_Error('empty_data', 'No post data found.');

    foreach ($posts as $post_data) {
        $post_title = sanitize_text_field($post_data['title']);
        $post_content = wp_kses_post($post_data['content']);
        $post_excerpt = wp_kses_post($post_data['excerpt']);

        // ✅ FIXED: Use WP_Query instead of deprecated get_page_by_title()
        $existing_post_title = rswpthemes_awt_new_get_page_by_title($post_title, OBJECT, 'post');

        if ($existing_post_title) {
            wp_reset_postdata();
            continue; // Skip if post exists
        }

        $post_id = wp_insert_post([
            'post_title'   => $post_title,
            'post_content' => $post_content,
            'post_excerpt' => $post_excerpt,
            'post_status'  => 'publish',
            'post_type'    => 'post'
        ]);

        if (is_wp_error($post_id)) continue;

        // ✅ FIXED: Handle WP_Term properly
        $category_ids = [];
        foreach ($post_data['categories'] as $category_name) {
            $category = get_term_by('name', $category_name, 'category');
            if (!$category) {
                $category = wp_insert_term($category_name, 'category');
            }
            if (!is_wp_error($category)) {
                $category_ids[] = $category instanceof WP_Term ? $category->term_id : $category['term_id'];
            }
        }
        wp_set_post_categories($post_id, $category_ids);

        // ✅ FIXED: Assign tags correctly
        $tag_ids = [];
        foreach ($post_data['tags'] as $tag_name) {
            $tag = get_term_by('name', $tag_name, 'post_tag');
            if (!$tag) {
                $tag = wp_insert_term($tag_name, 'post_tag');
            }
            if (!is_wp_error($tag)) {
                $tag_ids[] = $tag instanceof WP_Term ? $tag->term_id : $tag['term_id'];
            }
        }
        wp_set_post_tags($post_id, $tag_ids);

        // ✅ Handle Featured Image
        if (!empty($post_data['featured_image'])) {
            rswpthemes_awt_set_featured_image_from_url($post_id, $post_data['featured_image']);
        }

        // ✅ Handle Custom Meta Fields
        if (!empty($post_data['custom_meta'])) {
            foreach ($post_data['custom_meta'] as $meta_key => $meta_value) {
                update_post_meta($post_id, sanitize_key($meta_key), sanitize_text_field($meta_value));
            }
        }
    }
    return count($posts);
}

/**
 * Import Book Reviews From Json
 */
function book_author_blog_import_reviews_from_json_url($json_file_url) {
    $response = wp_remote_get($json_file_url);
    if (is_wp_error($response)) return new WP_Error('fetch_error', 'Unable to retrieve JSON file.');

    $json_input = wp_remote_retrieve_body($response);
    $reviews = json_decode($json_input, true);

    if (empty($reviews) || !is_array($reviews)) return new WP_Error('empty_data', 'No review data found.');

    $import_count = 0;

    foreach ($reviews as $review_data) {
        $review_title = sanitize_text_field($review_data['title']);
        $review_content = wp_kses_post($review_data['content']);

        // ✅ Check if review already exists using WP_Query (instead of deprecated get_page_by_title)
        $existing_review_query = new WP_Query([
            'post_type'      => 'book_reviews',
            'posts_per_page' => 1,
            'title'         => $review_title
        ]);

        if ($existing_review_query->have_posts()) {
            wp_reset_postdata();
            continue; // ✅ Skip if review already exists
        }
        wp_reset_postdata();

        // ✅ Insert new review post
        $review_id = wp_insert_post([
            'post_title'   => $review_title,
            'post_content' => $review_content,
            'post_status'  => 'publish',
            'post_type'    => 'book_reviews'
        ]);

        if (is_wp_error($review_id)) continue;

        // ✅ Set Featured Image if available
        if (!empty($review_data['featured_image'])) {
            rswpthemes_awt_set_featured_image_from_url($review_id, $review_data['featured_image']);
        }

        // ✅ Import Custom Meta Fields (Reviewer Name, Email, Rating, Reviewed Book)
        if (!empty($review_data['meta_data'])) {
            foreach ($review_data['meta_data'] as $meta_key => $meta_value) {
                update_post_meta($review_id, sanitize_key($meta_key), sanitize_text_field($meta_value));
            }
        }

        $import_count++;
    }

    return $import_count; // ✅ Return the count of imported reviews
}
