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

/**
 * JetEngine Custom Content Types — detection and post-linked item data.
 */
class AISB_JetEngine_CCT {

    public static function is_active() {
        return class_exists('\Jet_Engine\Modules\Custom_Content_Types\Module');
    }

    public static function version() {
        return defined('JET_ENGINE_VERSION') ? JET_ENGINE_VERSION : '';
    }

    /** @return array[] */
    public static function discover() {
        if (!self::is_active()) {
            return [];
        }
        $module = \Jet_Engine\Modules\Custom_Content_Types\Module::instance();
        if (empty($module->manager) || !method_exists($module->manager, 'get_content_types')) {
            return [];
        }
        $types = $module->manager->get_content_types();
        if (!is_array($types)) {
            return [];
        }
        $out = [];
        foreach ($types as $slug => $obj) {
            if (is_string($obj)) {
                continue;
            }
            $slug = self::type_slug($obj, $slug);
            if (!$slug) {
                continue;
            }
            $related_pt = self::related_post_type($obj);
            $fields = self::type_fields($obj);
            $out[$slug] = [
                'slug'               => $slug,
                'name'               => self::type_name($obj, $slug),
                'related_post_type'  => $related_pt,
                'has_single'         => (bool) $related_pt,
                'fields'             => $fields,
                'status'             => $related_pt ? 'linked' : 'orphan',
                'hint'               => $related_pt
                    ? sprintf(/* translators: %s are replaced with dynamic values */ __('Linked to CPT "%s" — enable that post type for schema.', 'pewit-ai-schema-builder'), $related_pt)
                    : __('No single CPT linked — schema works on CPT posts only, not raw CCT rows.', 'pewit-ai-schema-builder'),
            ];
        }
        return apply_filters('aisb_jetengine_cct_discover', $out);
    }

    public static function get_item_for_post($post_id) {
        if (!self::is_active() || !$post_id) {
            return null;
        }
        $module = \Jet_Engine\Modules\Custom_Content_Types\Module::instance();
        if (empty($module->manager)) {
            return null;
        }
        $post_type = get_post_type($post_id);
        if (!$post_type || !method_exists($module->manager, 'get_content_type_for_post_type')) {
            return null;
        }
        $content_type = $module->manager->get_content_type_for_post_type($post_type);
        if (!$content_type || !method_exists($module->manager, 'get_item_for_post')) {
            return null;
        }
        $item = $module->manager->get_item_for_post($post_id, $content_type);
        return self::normalize_item($item);
    }

    public static function cct_for_post_type($post_type) {
        $post_type = sanitize_key($post_type);
        foreach (self::discover() as $cct) {
            if (($cct['related_post_type'] ?? '') === $post_type) {
                return $cct;
            }
        }
        return null;
    }

    private static function type_slug($obj, $key) {
        if (is_object($obj) && method_exists($obj, 'get_arg')) {
            return sanitize_key($obj->get_arg('slug') ?: $key);
        }
        return sanitize_key($key);
    }

    private static function type_name($obj, $slug) {
        if (is_object($obj) && method_exists($obj, 'get_arg')) {
            return (string) ($obj->get_arg('name') ?: $slug);
        }
        return $slug;
    }

    private static function related_post_type($obj) {
        if (!is_object($obj) || !method_exists($obj, 'get_arg')) {
            return '';
        }
        foreach (['related_post_type', 'single_post_type', 'post_type', 'has_single'] as $key) {
            $v = $obj->get_arg($key);
            if (is_string($v) && $v !== '' && $v !== '1') {
                return sanitize_key($v);
            }
            if ($key === 'has_single' && $v) {
                $pt = $obj->get_arg('related_post_type') ?: $obj->get_arg('single_post_type');
                if ($pt) {
                    return sanitize_key($pt);
                }
            }
        }
        return '';
    }

    private static function type_fields($obj) {
        $fields = [];
        if (is_object($obj) && method_exists($obj, 'get_arg')) {
            $raw = $obj->get_arg('fields');
            if (is_array($raw)) {
                foreach ($raw as $f) {
                    $id = $f['name'] ?? $f['id'] ?? '';
                    if ($id) {
                        $fields[] = sanitize_key($id);
                    }
                }
            }
        }
        if (is_object($obj) && empty($fields) && method_exists($obj, 'get_fields')) {
            foreach ((array) $obj->get_fields() as $f) {
                $id = is_array($f) ? ($f['name'] ?? $f['id'] ?? '') : '';
                if ($id) {
                    $fields[] = sanitize_key($id);
                }
            }
        }
        return array_values(array_unique($fields));
    }

    private static function normalize_item($item) {
        if (!$item) {
            return null;
        }
        if (is_object($item)) {
            $item = get_object_vars($item);
        }
        if (!is_array($item)) {
            return null;
        }
        $clean = [];
        foreach ($item as $k => $v) {
            if (strpos((string) $k, '_') === 0 && in_array($k, ['_ID'], true)) {
                $clean['_cct_id'] = $v;
                continue;
            }
            if (is_scalar($v) || $v === null) {
                $clean[sanitize_key($k)] = $v;
            }
        }
        return $clean;
    }
}
