<?php
// includes/importer.php
defined('ABSPATH') || exit;

/**
 * Import a single post/page from a WordPress WXR (export) XML file.
 * - Reads the FIRST <item> in the file
 * - Inserts it using wp_insert_post()
 * - Copies categories/tags (creates terms if missing)
 * - Copies all postmeta entries
 * - Forces the post slug to $override_slug
 *
 * @param string $xml_file Absolute path to the WXR XML file.
 * @param string $override_slug Slug to force on the imported post.
 * @param int    $author_id WP user ID to set as post_author (fallback if not in XML).
 * @return int|\WP_Error Post ID on success, WP_Error on failure.
 */
function blog_maker_import_wxr_template($xml_file, $override_slug, $author_id = 0) {
    if (empty($xml_file) || !file_exists($xml_file)) {
        return new WP_Error('blog_maker_missing_xml', 'XML template not found: ' . esc_html(basename($xml_file)));
    }

    // Load XML safely
    libxml_use_internal_errors(true);
    $xml = simplexml_load_file($xml_file, 'SimpleXMLElement', LIBXML_NOCDATA);
    if ($xml === false) {
        $errors = libxml_get_errors();
        libxml_clear_errors();
        $msg = 'Failed to read XML template.';
        if (!empty($errors)) {
            $msg .= ' ' . trim($errors[0]->message);
        }
        return new WP_Error('blog_maker_bad_xml', $msg);
    }

    // Register namespaces used by WXR
    $namespaces = $xml->getNamespaces(true);

    if (!isset($xml->channel) || !isset($xml->channel->item)) {
        return new WP_Error('blog_maker_bad_xml_structure', 'XML template is missing channel/item nodes.');
    }

    // Use the first item in the export
    $item = $xml->channel->item[0];

    $wp = isset($namespaces['wp']) ? $namespaces['wp'] : null;
    $content_ns = isset($namespaces['content']) ? $namespaces['content'] : null;
    $excerpt_ns = isset($namespaces['excerpt']) ? $namespaces['excerpt'] : null;

    $wp_item = $wp ? $item->children($wp) : null;
    $content_item = $content_ns ? $item->children($content_ns) : null;
    $excerpt_item = $excerpt_ns ? $item->children($excerpt_ns) : null;

    $post_type = ($wp_item && isset($wp_item->post_type)) ? (string) $wp_item->post_type : 'post';

    // Force a clean slug
    $override_slug = sanitize_title($override_slug);

    $postarr = array(
        'post_title'   => isset($item->title) ? (string) $item->title : '',
        'post_content' => ($content_item && isset($content_item->encoded)) ? (string) $content_item->encoded : '',
        'post_excerpt' => ($excerpt_item && isset($excerpt_item->encoded)) ? (string) $excerpt_item->encoded : '',
        'post_status'  => 'draft',
        'post_type'    => $post_type,
        'post_name'    => $override_slug,
    );

    // Preserve dates if present
    if ($wp_item && isset($wp_item->post_date) && (string) $wp_item->post_date !== '0000-00-00 00:00:00') {
        $postarr['post_date'] = (string) $wp_item->post_date;
    }
    if ($wp_item && isset($wp_item->post_date_gmt) && (string) $wp_item->post_date_gmt !== '0000-00-00 00:00:00') {
        $postarr['post_date_gmt'] = (string) $wp_item->post_date_gmt;
    }

    // Author
    if (!empty($author_id)) {
        $postarr['post_author'] = (int) $author_id;
    } else if ($wp_item && isset($wp_item->post_author) && is_numeric((string) $wp_item->post_author)) {
        $postarr['post_author'] = (int) $wp_item->post_author;
    }

    // Insert the post
    $post_id = wp_insert_post($postarr, true);
    if (is_wp_error($post_id)) {
        return $post_id;
    }

    // Terms (categories/tags)
    $categories = array();
    $tags = array();

    if (isset($item->category)) {
        foreach ($item->category as $cat_node) {
            $domain = isset($cat_node['domain']) ? (string) $cat_node['domain'] : '';
            $name = trim((string) $cat_node);
            if ($name === '') {
                continue;
            }

            if ($domain === 'category') {
                $term = term_exists($name, 'category');
                if (!$term) {
                    $term = wp_insert_term($name, 'category');
                }
                if (!is_wp_error($term) && isset($term['term_id'])) {
                    $categories[] = (int) $term['term_id'];
                }
            } else if ($domain === 'post_tag') {
                $term = term_exists($name, 'post_tag');
                if (!$term) {
                    $term = wp_insert_term($name, 'post_tag');
                }
                if (!is_wp_error($term) && isset($term['term_id'])) {
                    $tags[] = (int) $term['term_id'];
                }
            }
        }
    }

    if (!empty($categories)) {
        wp_set_post_terms($post_id, $categories, 'category', false);
    }
    if (!empty($tags)) {
        wp_set_post_terms($post_id, $tags, 'post_tag', false);
    }

    // Post meta
    if ($wp_item && isset($wp_item->postmeta)) {
        foreach ($wp_item->postmeta as $meta_node) {
            $meta = $meta_node->children($wp);
            if (!isset($meta->meta_key)) {
                continue;
            }
            $meta_key = (string) $meta->meta_key;
            
            // IMPORTANT: WXR CDATA often includes indentation/newlines around meta_value.
            // Use a trimmed copy ONLY for serialized detection/unserialize, but keep raw otherwise.
            $raw_meta_value = isset($meta->meta_value) ? (string) $meta->meta_value : '';
            $trimmed        = is_string($raw_meta_value) ? trim($raw_meta_value) : $raw_meta_value;
            
            $meta_value = $raw_meta_value;
            if (is_string($trimmed) && is_serialized($trimmed)) {
                $meta_value = maybe_unserialize($trimmed);
            }
            
            // Deep-unserialize meta_value (handles s:"a:..." cases from WXR)
            $meta_value = blog_maker_deep_unserialize($meta_value, 3);
            
            // Keep meta single-valued (prevents BB keys from duplicating)
            delete_post_meta($post_id, $meta_key);
            update_post_meta($post_id, $meta_key, $meta_value);
        }
    }

    // If Beaver Builder is active, ensure the post is marked as BB-enabled.
    if (class_exists('FLBuilderModel')) {
        update_post_meta($post_id, '_fl_builder_enabled', '1');

        /**
         * IMPORTANT:
         * Beaver Builder edits the DRAFT meta key. If draft is missing/empty, BB often won’t allow edits.
         * Ensure draft exists and matches the imported data.
         */
        $data  = get_post_meta($post_id, '_fl_builder_data', true);
        $draft = get_post_meta($post_id, '_fl_builder_draft', true);

        if (empty($draft) && !empty($data)) {
            update_post_meta($post_id, '_fl_builder_draft', $data);
        }

        /**
         * Some sites get “stuck” because the page still has block-editor content.
         * If you want BB to fully own rendering/editing, you can clear post_content.
         * (Optional but often fixes “can’t edit” cases.)
         */
        // wp_update_post(array(
        //     'ID'           => $post_id,
        //     'post_content' => '',
        // ));

        /**
         * Try to force BB to rebuild its cached assets (method names vary by version).
         * These checks prevent fatals if a method doesn’t exist.
         */
        if (method_exists('FLBuilderModel', 'delete_asset_cache')) {
            FLBuilderModel::delete_asset_cache($post_id);
        }
        if (method_exists('FLBuilderModel', 'delete_layout_asset_cache')) {
            FLBuilderModel::delete_layout_asset_cache($post_id);
        }
        if (method_exists('FLBuilderModel', 'update_layout_css')) {
            FLBuilderModel::update_layout_css($post_id);
        }
        if (method_exists('FLBuilderModel', 'update_layout_js')) {
            FLBuilderModel::update_layout_js($post_id);
        }
    }

    // Ensure our forced slug sticks (in case another post already had it and WP auto-suffixed)
    if (get_post_field('post_name', $post_id) !== $override_slug) {
        wp_update_post(array(
            'ID'        => $post_id,
            'post_name' => wp_unique_post_slug($override_slug, $post_id, $postarr['post_status'], $post_type, 0),
        ));
    }

    return (int) $post_id;
}

// Helper function to download an image from a URL (if needed)
function download_image($url) {
    $image_data = file_get_contents($url);

    if ($image_data === false) {
        return ''; // Return an empty string on failure
    }

    // Save the downloaded image to a temporary file
    $temp_file = tempnam(sys_get_temp_dir(), 'image_');
    file_put_contents($temp_file, $image_data);

    return $temp_file; // Return the path to the temporary image file
}
