<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Documentation;

defined('ABSPATH') || exit;

final class DocumentationCatalog
{
    public const DEFAULT_PUBLIC_BASE_URL = 'https://designer.asukadev.com/documentation/';

    private const POST_TYPE = 'apd_documentation';
    private const TAXONOMY = 'apd_doc_section';

    public static function guides(array $statuses = ['publish', 'draft', 'pending', 'private', 'future']) : array
    {
        $posts = post_type_exists(self::POST_TYPE) ? get_posts([
            'post_type' => self::POST_TYPE,
            'post_status' => $statuses,
            'posts_per_page' => -1,
            'orderby' => ['menu_order' => 'ASC', 'title' => 'ASC'],
            'order' => 'ASC',
            'no_found_rows' => true,
        ]) : [];
        if ($posts === []) {
            return array_map(
                static fn(array $guide): array => array_merge($guide, [
                    'post_id' => 0,
                    'status' => 'built-in',
                    'view_url' => self::publicBaseUrl() . rawurlencode($guide['slug']) . '/',
                ]),
                self::defaults()
            );
        }

        $defaults = [];
        foreach (self::defaults() as $definition) {
            $defaults[$definition['slug']] = $definition;
        }

        $guides = [];
        foreach ($posts as $index => $post) {
            $slug = (string) $post->post_name;
            $definition = $defaults[$slug] ?? [];
            $terms = wp_get_post_terms($post->ID, self::TAXONOMY);
            $group = ! is_wp_error($terms) && $terms !== []
                ? (string) $terms[0]->name
                : (string) ($definition['group'] ?? __('General', 'asuka-product-designer'));
            $copy = trim((string) $post->post_excerpt);
            if ($copy === '') {
                $copy = (string) ($definition['copy'] ?? wp_trim_words(wp_strip_all_tags(strip_shortcodes((string) $post->post_content)), 28));
            }
            $number = trim((string) get_post_meta($post->ID, '_apd_doc_number', true));
            if ($number === '') {
                $number = str_pad((string) ($post->menu_order > 0 ? $post->menu_order : $index + 1), 2, '0', STR_PAD_LEFT);
            }
            $keywords = trim((string) get_post_meta($post->ID, '_apd_doc_keywords', true));
            if ($keywords === '') {
                $keywords = (string) ($definition['keywords'] ?? '');
            }

            $guides[] = [
                'post_id' => (int) $post->ID,
                'number' => $number,
                'group' => $group,
                'slug' => $slug,
                'title' => get_the_title($post),
                'copy' => $copy,
                'keywords' => $keywords,
                'status' => (string) $post->post_status,
                'view_url' => $post->post_status === 'publish'
                    ? (string) get_permalink($post)
                    : (string) get_preview_post_link($post),
            ];
        }

        return $guides;
    }

    public static function publicBaseUrl() : string
    {
        return trailingslashit((string) apply_filters(
            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- The apd_ hook is a documented integration API retained for backward compatibility.
            'apd_documentation_public_base_url',
            self::DEFAULT_PUBLIC_BASE_URL
        ));
    }

    public static function defaultBySlug(string $slug) : ?array
    {
        foreach (self::defaults() as $guide) {
            if ($guide['slug'] === $slug) {
                return $guide;
            }
        }

        return null;
    }

    public static function defaults() : array
    {
        return [
            ['number' => '01', 'group' => __('Start here', 'asuka-product-designer'), 'slug' => 'getting-started', 'title' => __('Getting started', 'asuka-product-designer'), 'copy' => __('Install, connect licensing, prepare the shared catalog, publish a product, and place the first test order.', 'asuka-product-designer'), 'keywords' => 'install activation first product checklist requirements'],
            ['number' => '02', 'group' => __('Start here', 'asuka-product-designer'), 'slug' => 'administration-tour', 'title' => __('Administration tour', 'asuka-product-designer'), 'copy' => __('Understand Overview, Products, Assets, Commerce, Documentation, Settings, and every focused workspace.', 'asuka-product-designer'), 'keywords' => 'menus dashboard overview navigation'],
            ['number' => '03', 'group' => __('Build products', 'asuka-product-designer'), 'slug' => 'product-configuration', 'title' => __('Product configuration', 'asuka-product-designer'), 'copy' => __('Configure views, initial state, templates, permissions, validation, catalog filters, pricing, and pagination.', 'asuka-product-designer'), 'keywords' => 'products builder permissions validation save reload'],
            ['number' => '04', 'group' => __('Build products', 'asuka-product-designer'), 'slug' => '2d-views', 'title' => __('2D views', 'asuka-product-designer'), 'copy' => __('Build Fabric views with product images, drawing areas, real measurements, layers, and reliable history.', 'asuka-product-designer'), 'keywords' => 'fabric canvas image drawing area dpi measurement history'],
            ['number' => '05', 'group' => __('Build products', 'asuka-product-designer'), 'slug' => '3d-views', 'title' => __('3D views', 'asuka-product-designer'), 'copy' => __('Prepare GLB models, map meshes, configure materials, save cameras, and validate surface placement.', 'asuka-product-designer'), 'keywords' => 'babylon glb mesh material camera surface optimizer'],
            ['number' => '06', 'group' => __('Build products', 'asuka-product-designer'), 'slug' => 'elements-variations', 'title' => __('Elements and variations', 'asuka-product-designer'), 'copy' => __('Model product parts and synchronize their variations across 2D and 3D views.', 'asuka-product-designer'), 'keywords' => 'elements variations synchronization product parts selection'],
            ['number' => '07', 'group' => __('Build products', 'asuka-product-designer'), 'slug' => 'drawing-areas-markers', 'title' => __('Drawing areas and markers', 'asuka-product-designer'), 'copy' => __('Constrain layers to printable regions and create guided replacement points in 2D and 3D.', 'asuka-product-designer'), 'keywords' => 'drawing areas markers fixed slots constraints placement'],
            ['number' => '08', 'group' => __('Design the experience', 'asuka-product-designer'), 'slug' => 'templates-layout', 'title' => __('Templates, modules, and layout', 'asuka-product-designer'), 'copy' => __('Place every module in navigation, selection tools, page content, or an asynchronous CSS portal.', 'asuka-product-designer'), 'keywords' => 'templates modules zones portal contextual menu responsive'],
            ['number' => '09', 'group' => __('Design the experience', 'asuka-product-designer'), 'slug' => 'assets-libraries', 'title' => __('Designs, shapes, and shared assets', 'asuka-product-designer'), 'copy' => __('Create reusable visual catalogs and expose the correct subset to every product.', 'asuka-product-designer'), 'keywords' => 'assets designs shapes catalog filters media'],
            ['number' => '10', 'group' => __('Design the experience', 'asuka-product-designer'), 'slug' => 'fonts-typography', 'title' => __('Fonts and typography', 'asuka-product-designer'), 'copy' => __('Configure system, Google, and custom fonts with variants, previews, filters, and runtime checks.', 'asuka-product-designer'), 'keywords' => 'fonts google system custom woff typography text family'],
            ['number' => '11', 'group' => __('Design the experience', 'asuka-product-designer'), 'slug' => 'colors-printing', 'title' => __('Colors and printing methods', 'asuka-product-designer'), 'copy' => __('Build compatible production palettes with defaults, references, visibility, and price adjustments.', 'asuka-product-designer'), 'keywords' => 'colors printing methods compatibility palette price'],
            ['number' => '12', 'group' => __('Sell and produce', 'asuka-product-designer'), 'slug' => 'pricing-validation', 'title' => __('Pricing and validation', 'asuka-product-designer'), 'copy' => __('Create conditional price rules and stop invalid dimensions, DPI, colors, or placements before checkout.', 'asuka-product-designer'), 'keywords' => 'pricing rules conditions handlers validation dpi dimensions'],
            ['number' => '13', 'group' => __('Sell and produce', 'asuka-product-designer'), 'slug' => 'commerce-production', 'title' => __('WooCommerce, orders, and production', 'asuka-product-designer'), 'copy' => __('Bind products and preserve previews, design state, pricing, and production metadata through fulfilment.', 'asuka-product-designer'), 'keywords' => 'woocommerce cart checkout orders production hpos blocks'],
            ['number' => '14', 'group' => __('Operate and integrate', 'asuka-product-designer'), 'slug' => 'settings-integrations', 'title' => __('Settings, licensing, and providers', 'asuka-product-designer'), 'copy' => __('Configure runtime defaults, license security, provider credentials, uploads, AI, and data retention.', 'asuka-product-designer'), 'keywords' => 'settings license api pixabay pexels google fonts ai uploads'],
            ['number' => '15', 'group' => __('Operate and integrate', 'asuka-product-designer'), 'slug' => 'tools-translations', 'title' => __('Tools, import, export, and translations', 'asuka-product-designer'), 'copy' => __('Move configuration packages safely and localize runtime labels without editing bundled JavaScript.', 'asuka-product-designer'), 'keywords' => 'tools import export json translations locale migration'],
            ['number' => '16', 'group' => __('Operate and integrate', 'asuka-product-designer'), 'slug' => 'embedding-advanced', 'title' => __('Embedding and advanced integration', 'asuka-product-designer'), 'copy' => __('Choose product binding, Gutenberg, shortcode, CSS portals, and renderer code splitting correctly.', 'asuka-product-designer'), 'keywords' => 'shortcode gutenberg block portal theme custom integration'],
            ['number' => '17', 'group' => __('Support and maintenance', 'asuka-product-designer'), 'slug' => 'troubleshooting', 'title' => __('Troubleshooting and maintenance', 'asuka-product-designer'), 'copy' => __('Diagnose licensing, saving, rendering, uploads, providers, themes, and safe plugin updates.', 'asuka-product-designer'), 'keywords' => 'diagnostics errors missing save reload blink support update'],
        ];
    }
}
