<?php
if (!defined('ABSPATH')) exit;

/**
 * Custom post type discovery, enablement and schema-type mapping.
 */
class AISB_CPT_Registry {

    /** Schema.org types aligned with Google Search / Bing rich results where applicable. */
    public static function schema_type_catalog() {
        return [
            'Article'        => __('Article / BlogPosting', 'pewit-ai-schema-builder'),
            'WebPage'        => __('WebPage', 'pewit-ai-schema-builder'),
            'AboutPage'      => __('AboutPage', 'pewit-ai-schema-builder'),
            'ContactPage'    => __('ContactPage', 'pewit-ai-schema-builder'),
            'FAQPage'        => __('FAQPage', 'pewit-ai-schema-builder'),
            'Product'        => __('Product', 'pewit-ai-schema-builder'),
            'LocalBusiness'  => __('LocalBusiness', 'pewit-ai-schema-builder'),
            'Organization'   => __('Organization', 'pewit-ai-schema-builder'),
            'Event'          => __('Event', 'pewit-ai-schema-builder'),
            'Service'        => __('Service', 'pewit-ai-schema-builder'),
            'HowTo'          => __('HowTo', 'pewit-ai-schema-builder'),
            'Course'         => __('Course', 'pewit-ai-schema-builder'),
            'JobPosting'     => __('JobPosting', 'pewit-ai-schema-builder'),
            'Recipe'         => __('Recipe', 'pewit-ai-schema-builder'),
            'ItemList'       => __('ItemList (archives)', 'pewit-ai-schema-builder'),
        ];
    }

    /** Public CPTs available for schema (excludes internal WP types). */
    public static function discover_post_types() {
        $exclude = apply_filters('aisb_excluded_post_types', [
            'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset',
            'oembed_cache', 'user_request', 'wp_block', 'wp_template', 'wp_template_part',
            'wp_global_styles', 'wp_navigation',
        ]);

        $types = get_post_types(['public' => true], 'objects');
        $out = [];
        foreach ($types as $name => $obj) {
            if (in_array($name, $exclude, true)) {
                continue;
            }
            $cct = AISB_JetEngine_CCT::cct_for_post_type($name);
            $mb = AISB_MetaBox_Fields::discover_tables();
            $out[$name] = [
                'name'           => $name,
                'label'          => $obj->labels->singular_name,
                'plural'         => $obj->labels->name,
                'count'          => (int) wp_count_posts($name)->publish,
                'etch'           => AISB_Etch::is_etch_post_type($name),
                'jet_cct'        => $cct ? $cct['slug'] : '',
                'jet_cct_name'   => $cct ? $cct['name'] : '',
                'metabox_fields' => $mb[$name]['fields'] ?? [],
            ];
        }
        uasort($out, function ($a, $b) {
            return strcasecmp($a['label'], $b['label']);
        });
        return $out;
    }

    public static function default_enabled_post_types() {
        $enabled = ['post', 'page'];
        if (class_exists('WooCommerce')) {
            $enabled[] = 'product';
        }
        return $enabled;
    }

    public static function get_enabled_post_types() {
        $s = aisb_get_settings();
        $enabled = [];
        if (isset($s['enabled_post_types']) && is_array($s['enabled_post_types'])) {
            $enabled = array_map('sanitize_key', $s['enabled_post_types']);
        }
        if (empty($enabled)) {
            $enabled = self::default_enabled_post_types();
        }
        $enabled = array_values(array_unique(array_filter($enabled)));
        return apply_filters('aisb_enabled_post_types', $enabled);
    }

    public static function get_cpt_schema_map() {
        $s = aisb_get_settings();
        $map = isset($s['cpt_schema_map']) && is_array($s['cpt_schema_map']) ? $s['cpt_schema_map'] : [];
        $clean = [];
        foreach ($map as $pt => $type) {
            $clean[sanitize_key($pt)] = sanitize_key($type);
        }
        return $clean;
    }

    public static function get_schema_type_for_post_type($post_type) {
        $post_type = sanitize_key($post_type);
        $map = self::get_cpt_schema_map();
        if (!empty($map[$post_type])) {
            return $map[$post_type];
        }
        return self::guess_schema_type($post_type);
    }

    /**
     * Heuristic schema type from CPT slug / label (Google/Bing-friendly defaults).
     */
    public static function guess_schema_type($post_type, $label = '') {
        $post_type = sanitize_key($post_type);
        $hay = strtolower($post_type . ' ' . $label);

        if ($post_type === 'product') {
            return 'Product';
        }
        if ($post_type === 'page') {
            return 'WebPage';
        }
        if ($post_type === 'post') {
            return 'Article';
        }

        $rules = [
            'Event'         => ['event', 'events', 'webinar', 'conference', 'wydarzen'],
            'LocalBusiness' => ['location', 'locations', 'branch', 'store', 'shop', 'salon', 'clinic', 'office', 'lokal'],
            'Service'       => ['service', 'services', 'uslug', 'offering'],
            'JobPosting'    => ['job', 'jobs', 'career', 'careers', 'vacancy', 'praca', 'oferta-pracy'],
            'Course'        => ['course', 'courses', 'training', 'szkolen', 'kurs'],
            'Recipe'        => ['recipe', 'recipes', 'przepis'],
            'FAQPage'       => ['faq', 'faqs', 'pytania'],
            'HowTo'         => ['howto', 'how-to', 'tutorial', 'guide', 'poradnik'],
            'ContactPage'   => ['contact', 'kontakt'],
            'AboutPage'     => ['about', 'o-nas', 'team', 'zespol'],
            'Organization'  => ['organization', 'org', 'partner', 'partners'],
            'ItemList'      => ['portfolio', 'project', 'projects', 'case', 'cases', 'reference'],
        ];

        foreach ($rules as $type => $needles) {
            foreach ($needles as $needle) {
                if (strpos($hay, $needle) !== false) {
                    return $type;
                }
            }
        }

        return 'Article';
    }

    public static function is_post_type_enabled($post_type) {
        return in_array(sanitize_key($post_type), self::get_enabled_post_types(), true);
    }

    public static function seed_defaults() {
        $s = aisb_get_settings();
        if (!empty($s['cpt_defaults_seeded'])) {
            return;
        }
        $map = [];
        foreach (self::discover_post_types() as $name => $info) {
            $map[$name] = self::guess_schema_type($name, $info['label']);
        }
        $s['cpt_schema_map'] = $map;
        $s['enabled_post_types'] = self::default_enabled_post_types();
        $s['cpt_defaults_seeded'] = 1;
        aisb_update_settings($s);
    }
}
