<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Content_Importer
{
    public const SLUG_REF_META = array('_puffergo_solution_products', '_puffergo_case_products', );

    private static $url_cache = array();

    public static function reset_caches(): void
    {
        self::$url_cache = array();
    }

    public static function ensure_terms(array $terms_by_tax): void
    {
        foreach ($terms_by_tax as $tax => $term_names) {
            foreach ((array) $term_names as $name) {
                if (! term_exists($name, $tax)) {
                    wp_insert_term($name, $tax);
                }
            }
        }
    }

    public static function create_post(string $cpt, array $data, array $opts = array()): int
    {
        $post_status = isset($opts['post_status']) ? $opts['post_status'] : 'publish';
        $marker_meta = isset($opts['marker_meta']) ? (array) $opts['marker_meta'] : array();
        $post_id = wp_insert_post(array('post_type' => $cpt, 'post_title' => $data['title'], 'post_content' => $data['content'] ?? '', 'post_excerpt' => $data['excerpt'] ?? '', 'post_status' => $post_status, 'post_name' => $data['slug'] ?? PufferGo_Slug_Helper::slug_for_title($data['title']), ), true, false);

        if (is_wp_error($post_id)) {
            return 0;
        }

foreach ($marker_meta as $key => $value) {
            update_post_meta($post_id, $key, $value);
        } PufferGo_Polylang::set_post_language($post_id, PufferGo_Polylang::default_language());

        if (! empty($data['meta'])) {
            foreach ($data['meta'] as $key => $value) {
                $value = self::resolve_meta_value($key, $value);
                update_post_meta($post_id, $key, is_array($value) ? wp_json_encode($value) : $value);
            }
        }

if (! empty($data['taxonomies'])) {
            foreach ($data['taxonomies'] as $tax => $terms) {
                wp_set_object_terms($post_id, $terms, $tax);
            }
        }

return $post_id;
    }

    public static function resolve_meta_value(string $meta_key, $value)
    {
        if (! in_array($meta_key, self::SLUG_REF_META, true) || ! is_array($value)) {
            return $value;
        } $ids = array();

        foreach ($value as $slug) {
            $id = self::find_post_id_by_slug('puffergo_product', $slug);

            if ($id) {
                $ids[] = $id;
            }
        }

return $ids;
    }

    public static function find_post_id_by_slug(string $post_type, string $slug): int
    {
        $posts = get_posts(array('post_type' => $post_type, 'post_status' => 'any', 'name' => $slug, 'posts_per_page' => 1, 'fields' => 'ids', 'no_found_rows' => true, ));

        return ! empty($posts) ? (int) $posts[0] : 0;
    }

    public static function sideload_images(int $post_id, array $images, array $opts = array()): array
    {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        $marker_meta = isset($opts['marker_meta']) ? (array) $opts['marker_meta'] : array();
        $attachment_ids = array();

        foreach ($images as $img) {
            if (is_string($img)) {
                $url = $img;
                $ext = pathinfo(wp_parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'webp';
            } elseif (is_array($img)) {
                $url = $img['url'] ?? '';
                $ext = pathinfo(wp_parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'jpg';
            } else {
                $attachment_ids[] = 0;
                continue;
            }

if (empty($url)) {
                $attachment_ids[] = 0;
                continue;
            }

if (isset(self::$url_cache[ $url ])) {
                $attachment_ids[] = self::$url_cache[ $url ];
                continue;
            } $filename = pathinfo(wp_parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);

            if (empty($filename)) {
                $attachment_ids[] = 0;
                continue;
            } $tmp = download_url($url, 60);

            if (is_wp_error($tmp)) {
                $attachment_ids[] = 0;
                continue;
            } $file_array = array('name' => sanitize_file_name($filename) . '.' . $ext, 'tmp_name' => $tmp, );
            $attachment_id = media_handle_sideload($file_array, $post_id);

            if (is_wp_error($attachment_id)) {
                @unlink($tmp);
                $attachment_ids[] = 0;
                continue;
            }

foreach ($marker_meta as $key => $value) {
                update_post_meta($attachment_id, $key, $value);
            } self::$url_cache[ $url ] = $attachment_id;
            $attachment_ids[] = $attachment_id;
        }

return $attachment_ids;
    }

    public static function apply_images_to_post(string $cpt, int $post_id, array $image_ids): void
    {
        $valid_ids = array_values(array_filter($image_ids));

        if (empty($valid_ids)) {
            return;
        } $first_id = reset($valid_ids);
        set_post_thumbnail($post_id, $first_id);

        switch ($cpt) {
            case 'puffergo_product': $gallery = array_map(function ($id) { return array('type' => 'image', 'id' => $id); }, $valid_ids);
                update_post_meta($post_id, '_puffergo_gallery', wp_json_encode($gallery));
                break;
            case 'puffergo_testimonial': update_post_meta($post_id, '_puffergo_testimony_photo', $first_id);
                break;
        }
    }

    public static function delete_marked_attachments(int $post_id, string $marker_key, string $marker_value = '1'): void
    {
        $attachments = get_posts(array('post_type' => 'attachment', 'post_status' => 'any', 'post_parent' => $post_id, 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_query' => array(array('key' => $marker_key, 'value' => $marker_value, )), ));

        foreach ($attachments as $attachment_id) {
            wp_delete_attachment($attachment_id, true);
        }
    }
}
