<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Sample_Data_Seeder
{
    public const OPTION_KEY = 'puffergo_sample_data_imported';

    public const SAMPLE_META_KEY = '_puffergo_sample_data';

    public const REST_NAMESPACE = 'puffergo/v1';

    private static $slug_image_map = array();

    public const SEED_MAP = array('puffergo_product' => 'products.json', 'puffergo_solution' => 'solutions.json', 'puffergo_case' => 'cases.json', 'puffergo_testimonial' => 'testimonials.json', 'post' => 'posts.json', );

    public const READINESS_EXCLUDED_TYPES = array('post');

    public function __construct()
    {
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    public function register_rest_routes(): void
    {
        register_rest_route(self::REST_NAMESPACE, '/sample-data/status', array('methods' => 'GET', 'callback' => array($this, 'rest_status'), 'permission_callback' => array($this, 'can_manage'), ));
        register_rest_route(self::REST_NAMESPACE, '/sample-data/delete', array('methods' => 'POST', 'callback' => array($this, 'rest_delete'), 'permission_callback' => array($this, 'can_manage'), ));
        register_rest_route(self::REST_NAMESPACE, '/showroom/import', array('methods' => 'POST', 'callback' => array($this, 'rest_showroom_import'), 'permission_callback' => array($this, 'can_manage'), ));
        register_rest_route(self::REST_NAMESPACE, '/showroom/delete', array('methods' => 'POST', 'callback' => array($this, 'rest_showroom_delete'), 'permission_callback' => array($this, 'can_manage'), ));
    }

    public function can_manage(): bool
    {
        return current_user_can('manage_options');
    }

    public function rest_status(): WP_REST_Response
    {
        return new WP_REST_Response(array('imported' => self::has_imported(), 'counts' => self::get_sample_counts(), 'site_readiness' => self::get_site_readiness(), ));
    }

    public function rest_delete(): WP_REST_Response
    {
        $deleted = self::delete_all();
        delete_option(self::OPTION_KEY);

        return new WP_REST_Response(array('success' => true, 'message' => sprintf(__('Successfully deleted %d sample posts.', 'puffergo'), $deleted), ));
    }

    public function rest_showroom_import(WP_REST_Request $request): WP_REST_Response
    {
        if (self::has_imported()) {
            return new WP_REST_Response(array('success' => false, 'message' => __('Showroom already active. Delete it first.', 'puffergo'), ), 409);
        } $readiness = self::get_site_readiness();
        $force = (bool) $request->get_param('force');

        if (! $readiness['is_fresh'] && ! $force) {
            return new WP_REST_Response(array('success' => false, 'code' => 'not_fresh', 'message' => __('Site has existing content. Pass force=true to override.', 'puffergo'), 'site_readiness' => $readiness, ), 409);
        } $result = self::import_all();
        $homepage_id = self::create_showroom_homepage();

        if ($homepage_id) {
            $result['post_ids'][] = $homepage_id;
            update_option('show_on_front', 'page');
            update_option('page_on_front', $homepage_id);
        } $result['post_ids'] = array_merge($result['post_ids'], self::create_showroom_structural_pages());

        if (function_exists('puffergo_ensure_blog_page')) {
            puffergo_ensure_blog_page();
        } self::sync_showroom_menu($homepage_id);
        self::sync_showroom_footer_menu();

        if (! get_option('puffergo_template_header')) {
            update_option('puffergo_template_header', 'default');
        }

if (! get_option('puffergo_template_footer')) {
            update_option('puffergo_template_footer', 'default');
        }

if (! get_option(PufferGo_Design_System::OPTION_KEY)) {
            $apple_css = self::fetch_apple_design_css();

            if ($apple_css !== '') {
                update_option(PufferGo_Design_System::OPTION_KEY, array('schemes' => array(array('id' => 'preset_apple', 'name' => 'Apple', 'compiledCss' => $apple_css)), 'activeSchemeId' => 'preset_apple', 'compiledCss' => $apple_css, 'updatedAt' => gmdate('c'), ));
            }
        } update_option(self::OPTION_KEY, array('imported_at' => current_time('mysql'), 'post_ids' => $result['post_ids'], 'showroom' => true, ));

        return new WP_REST_Response(array('success' => true, 'message' => sprintf(__('Showroom imported: %d posts created.', 'puffergo'), count($result['post_ids'])), 'counts' => $result['counts'], ));
    }

    public function rest_showroom_delete(): WP_REST_Response
    {
        $deleted = self::delete_all();
        $deleted += self::delete_sample_pages();
        delete_option(self::OPTION_KEY);

        return new WP_REST_Response(array('success' => true, 'message' => sprintf(__('Showroom removed: %d posts deleted.', 'puffergo'), $deleted), ));
    }

    public static function has_imported(): bool
    {
        return (bool) get_option(self::OPTION_KEY, false);
    }

    public static function get_sample_counts(): array
    {
        $counts = array();

        foreach (array_keys(self::SEED_MAP) as $cpt) {
            $counts[$cpt] = self::count_sample_posts($cpt);
        }

return $counts;
    }

    public static function import_all(): array
    {
        PufferGo_Content_Importer::reset_caches();
        self::$slug_image_map = array();
        $post_ids = array();
        $counts = array();
        $data_dir = self::get_data_dir();

        foreach (self::SEED_MAP as $cpt => $filename) {
            if ('puffergo_testimonial' === $cpt && ! PufferGo_Base_CPT::is_enabled('testimonial')) {
                $counts[ $cpt ] = 0;
                continue;
            } $file = $data_dir . $filename;

            if (! is_readable($file)) {
                $counts[$cpt] = 0;
                continue;
            } $ids = self::import_file($cpt, $file);
            $post_ids = array_merge($post_ids, $ids);
            $counts[$cpt] = count($ids);
        }

return array('post_ids' => $post_ids, 'counts' => $counts);
    }

    public static function delete_all(): int
    {
        $deleted = 0;

        foreach (array_keys(self::SEED_MAP) as $cpt) {
            $deleted += self::delete_sample_posts($cpt);
        }

return $deleted;
    }

    private static function import_file(string $cpt, string $file): array
    {
        $json = json_decode(file_get_contents($file), true);

        if (! is_array($json)) {
            return array();
        }

if (! empty($json['terms'])) {
            PufferGo_Content_Importer::ensure_terms($json['terms']);
        } $ids = array();
        $posts = $json['posts'] ?? array();

        foreach ($posts as $post_data) {
            $id = self::create_sample_post($cpt, $post_data);

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

return $ids;
    }

    private static function create_sample_post(string $cpt, array $data): int
    {
        $post_id = PufferGo_Content_Importer::create_post($cpt, $data, array('post_status' => 'publish', 'marker_meta' => array(self::SAMPLE_META_KEY => '1'), ));

        if (! $post_id) {
            return 0;
        }

if ($cpt === 'puffergo_product' && ! empty($data['_sample_images'])) {
            $slug = $data['slug'] ?? sanitize_title($data['title']);
            self::$slug_image_map[$slug] = $data['_sample_images'];
        } $images = $data['_sample_images'] ?? array();

        if (empty($images) && $cpt === 'puffergo_case') {
            $images = self::resolve_case_images_from_products($data);
        }

if (! empty($images)) {
            $image_ids = self::sideload_sample_images($post_id, $images);
            self::apply_images_to_post($cpt, $post_id, $image_ids);
        }

return $post_id;
    }

    private static function get_data_dir(): string
    {
        return PUFFERGO_PLUGIN_DIR . '/php/data/sample/';
    }

    private static function count_sample_posts(string $cpt): int
    {
        $q = new WP_Query(array('post_type' => $cpt, 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_query' => array(array('key' => self::SAMPLE_META_KEY, 'value' => '1', )), ));

        return $q->post_count;
    }

    private static function delete_sample_posts(string $cpt): int
    {
        $posts = get_posts(array('post_type' => $cpt, 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_query' => array(array('key' => self::SAMPLE_META_KEY, 'value' => '1', )), ));
        $count = 0;

        foreach ($posts as $post_id) {
            self::delete_sample_attachments($post_id);
            wp_delete_post($post_id, true);
            $count++;
        }

return $count;
    }

    private static function delete_sample_attachments(int $post_id): void
    {
        PufferGo_Content_Importer::delete_marked_attachments($post_id, self::SAMPLE_META_KEY, '1');
    }

    private static function resolve_case_images_from_products(array $case_data): array
    {
        $product_slugs = $case_data['meta']['_puffergo_case_products'] ?? array();

        if (empty($product_slugs) || ! is_array($product_slugs)) {
            return array();
        }

foreach ($product_slugs as $slug) {
            $images = self::$slug_image_map[$slug] ?? array();

            if (empty($images)) {
                $products_file = self::get_data_dir() . 'products.json';

                if (is_readable($products_file)) {
                    $products_json = json_decode(file_get_contents($products_file), true);

                    foreach ($products_json['posts'] ?? array() as $product) {
                        if (($product['slug'] ?? '') === $slug) {
                            $images = $product['_sample_images'] ?? array();

                            if (! empty($images)) {
                                self::$slug_image_map[$slug] = $images;
                            } break;
                        }
                    }
                }
            }

if (! empty($images)) {
                return $images;
            }
        }

return array();
    }

    private static function sideload_sample_images(int $post_id, array $images): array
    {
        return PufferGo_Content_Importer::sideload_images($post_id, $images, array('marker_meta' => array(self::SAMPLE_META_KEY => '1'), ));
    }

    public static function get_site_readiness(): array
    {
        $cpt_total = 0;

        foreach (array_keys(self::SEED_MAP) as $cpt) {
            if (in_array($cpt, self::READINESS_EXCLUDED_TYPES, true)) {
                continue;
            }

if ('puffergo_testimonial' === $cpt && ! PufferGo_Base_CPT::is_enabled('testimonial')) {
                continue;
            } $count_obj = wp_count_posts($cpt);
            $cpt_total += isset($count_obj->publish) ? (int) $count_obj->publish : 0;
            $cpt_total += isset($count_obj->draft) ? (int) $count_obj->draft : 0;
        } $page_count = (int) wp_count_posts('page')->publish;
        $show_on_front = get_option('show_on_front');
        $page_on_front = (int) get_option('page_on_front');
        $has_homepage = ($show_on_front === 'page' && $page_on_front > 0);
        $is_fresh = ($cpt_total === 0 && $page_count <= 2 && ! $has_homepage);

        return array('is_fresh' => $is_fresh, 'has_homepage' => $has_homepage, 'cpt_total' => $cpt_total, 'page_count' => $page_count, );
    }

    public static function create_showroom_homepage(): int
    {
        $json_file = self::get_data_dir() . 'homepage.json';

        if (! is_readable($json_file)) {
            return 0;
        } $data = json_decode(file_get_contents($json_file), true);

        if (! is_array($data)) {
            return 0;
        } $content = str_replace('ADMIN_AI_BUILDER_URL', admin_url('admin.php?page=puffergo-ai-site-builder'), $data['content'] ?? '');
        $post_id = wp_insert_post(array('post_type' => 'page', 'post_title' => $data['title'] ?? __('Sample Homepage', 'puffergo'), 'post_content' => $content, 'post_status' => 'publish', 'post_name' => 'home', ), true);

        if (is_wp_error($post_id)) {
            return 0;
        } update_post_meta($post_id, self::SAMPLE_META_KEY, '1');
        update_post_meta($post_id, '_puffergo_managed', true);

        if (class_exists('PufferGo_Homepage_Guard')) {
            PufferGo_Homepage_Guard::mark_as_homepage_candidate($post_id);
        }

if (! empty($data['template'])) {
            update_post_meta($post_id, '_wp_page_template', $data['template']);
        }

return $post_id;
    }

    private static function b2b_pages(): array
    {
        return array(array('slug' => 'about', 'label' => __('About Us', 'puffergo')), array('slug' => 'contact', 'label' => __('Contact Us', 'puffergo')), );
    }

    public static function create_showroom_structural_pages(): array
    {
        $ids = array();

        foreach (self::b2b_pages() as $page) {
            $existing = get_page_by_path($page['slug'], OBJECT, 'page');

            if ($existing) {
                update_post_meta($existing->ID, '_puffergo_managed', true);
                update_post_meta($existing->ID, self::SAMPLE_META_KEY, '1');
                update_post_meta($existing->ID, '_wp_page_template', 'puffergo-fullpage.php');
                $ids[] = $existing->ID;
                continue;
            } $post_id = wp_insert_post(array('post_type' => 'page', 'post_title' => $page['label'], 'post_name' => $page['slug'], 'post_content' => '<!-- wp:paragraph --><p>' . sprintf(__('This is a placeholder for the %s page. It will be replaced with AI-generated content when you run the AI Site Builder.', 'puffergo'), $page['label']) . '</p><!-- /wp:paragraph -->', 'post_status' => 'publish', ), true);

            if (is_wp_error($post_id)) {
                continue;
            } update_post_meta($post_id, self::SAMPLE_META_KEY, '1');
            update_post_meta($post_id, '_puffergo_managed', true);
            update_post_meta($post_id, '_wp_page_template', 'puffergo-fullpage.php');
            $ids[] = $post_id;
        }

return $ids;
    }

    public static function sync_showroom_footer_menu(): int
    {
        $menu_id = function_exists('puffergo_resolve_menu_id') ? puffergo_resolve_menu_id('puffergo_footer', 'PufferGo Footer') : 0;

        if ($menu_id <= 0) {
            return 0;
        } $existing = wp_get_nav_menu_items($menu_id);

        if (is_array($existing)) {
            foreach ($existing as $item) {
                wp_delete_post($item->ID, true);
            }
        } $sections = array(array('title' => __('Products', 'puffergo'), 'links' => array(array('name' => __('All Products', 'puffergo'), 'url' => home_url('/products')), ), ), array('title' => __('Company', 'puffergo'), 'links' => array_values(array_filter(array(array('name' => __('About Us', 'puffergo'), 'url' => home_url('/about')), array('name' => __('Factory Tour', 'puffergo'), 'url' => home_url('/factory-tour')), array('name' => __('Case Studies', 'puffergo'), 'url' => home_url('/case-studies')), PufferGo_Base_CPT::is_enabled('testimonial') ? array('name' => __('Testimonials', 'puffergo'), 'url' => home_url('/testimonials')) : null, array('name' => __('Blog', 'puffergo'), 'url' => home_url('/blog')), ))), ), array('title' => __('Support', 'puffergo'), 'links' => array(array('name' => __('Contact Us', 'puffergo'), 'url' => home_url('/contact')), array('name' => __('Get a Quote', 'puffergo'), 'url' => home_url('/contact')), array('name' => __('Privacy Policy', 'puffergo'), 'url' => home_url('/privacy-policy')), array('name' => __('Terms of Service', 'puffergo'), 'url' => home_url('/terms')), ), ), );

        foreach ($sections as $section) {
            $parent_id = wp_update_nav_menu_item($menu_id, 0, array('menu-item-title' => $section['title'], 'menu-item-url' => '#', 'menu-item-type' => 'custom', 'menu-item-status' => 'publish', ));

            if (is_wp_error($parent_id)) {
                continue;
            } update_post_meta($parent_id, '_puffergo_managed', true);

            foreach ($section['links'] as $link) {
                $child_id = wp_update_nav_menu_item($menu_id, 0, array('menu-item-title' => $link['name'], 'menu-item-url' => $link['url'], 'menu-item-type' => 'custom', 'menu-item-status' => 'publish', 'menu-item-parent-id' => (int) $parent_id, ));

                if (! is_wp_error($child_id)) {
                    update_post_meta($child_id, '_puffergo_managed', true);
                }
            }
        }

return $menu_id;
    }

    private static function fetch_apple_design_css(): string
    {
        $response = wp_remote_get(rtrim(PUFFERGO_AI_PAGE_BUILDER_BASE_URL, '/') . '/api/patterns/presets/apple/css', array('timeout' => 10, ));

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            return '';
        } $body = json_decode(wp_remote_retrieve_body($response), true);

        return is_array($body) && isset($body['css']) && is_string($body['css']) ? $body['css'] : '';
    }

    public static function sync_showroom_menu(int $homepage_id): void
    {
        if (! function_exists('puffergo_sync_primary_menu')) {
            return;
        } $home_url = $homepage_id > 0 ? get_permalink($homepage_id) : home_url('/');
        $items = array(array('label' => __('Home', 'puffergo'), 'url' => $home_url), array('label' => __('Products', 'puffergo'), 'url' => home_url('/products')), array('label' => __('Solutions', 'puffergo'), 'url' => home_url('/solutions')), array('label' => __('Case Studies', 'puffergo'), 'url' => home_url('/case-studies')), array('label' => __('About Us', 'puffergo'), 'url' => home_url('/about'), 'children' => array(array('label' => __('Company', 'puffergo'), 'url' => home_url('/about')), array('label' => __('Factory Tour', 'puffergo'), 'url' => home_url('/factory-tour')), ), ), array('label' => __('Blog', 'puffergo'), 'url' => home_url('/blog')), array('label' => __('Contact Us', 'puffergo'), 'url' => home_url('/contact')), );
        puffergo_sync_primary_menu($items);
    }

    private static function delete_sample_pages(): int
    {
        $posts = get_posts(array('post_type' => 'page', 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids', 'no_found_rows' => true, 'meta_query' => array(array('key' => self::SAMPLE_META_KEY, 'value' => '1', )), ));
        $count = 0;

        foreach ($posts as $post_id) {
            wp_delete_post($post_id, true);
            $count++;
        }

return $count;
    }

    private static function apply_images_to_post(string $cpt, int $post_id, array $image_ids): void
    {
        PufferGo_Content_Importer::apply_images_to_post($cpt, $post_id, $image_ids);
    }
}
