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

class AISB_Post_Schema {

    private static $auto_generating = false;

    public static function init() {
        add_action('add_meta_boxes', [__CLASS__, 'meta_boxes']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'assets']);
        add_action('save_post', [__CLASS__, 'maybe_auto_generate'], 20, 3);
        add_action('wp_ajax_aisb_generate_schema', [__CLASS__, 'ajax_generate']);
        add_action('wp_ajax_aisb_save_schema', [__CLASS__, 'ajax_save']);
        add_action('wp_ajax_aisb_validate_schema', [__CLASS__, 'ajax_validate']);
    }

    public static function supported_post_types() {
        return apply_filters('aisb_supported_post_types', AISB_CPT_Registry::get_enabled_post_types());
    }

    public static function meta_boxes() {
        foreach (self::supported_post_types() as $type) {
            add_meta_box(
                'aisb-schema',
                __('Pewit AI Schema Builder', 'pewit-ai-schema-builder'),
                [__CLASS__, 'render_meta_box'],
                $type,
                'normal',
                'high'
            );
        }
    }

    public static function render_meta_box($post) {
        wp_nonce_field('aisb_post_schema', 'aisb_post_schema_nonce');
        $schema = AISB_Schema::get_json($post->ID);
        $type = AISB_Schema::get_type($post->ID) ?: AISB_Schema::detect_type($post);
        $validation = $schema ? AISB_Schema::validate($schema, $type) : null;
        $api_ready = aisb_api_ready();
        $types = AISB_Schema::available_types($post);
        $json_pretty = $schema ? wp_json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : '';
        ?>
        <div class="aisb-metabox" data-post-id="<?php echo esc_attr($post->ID); ?>">
            <?php if (!$api_ready): ?>
                <p class="aisb-notice aisb-notice-warn">
                    <?php esc_html_e('Connect and test your OpenAI API key in Settings first.', 'pewit-ai-schema-builder'); ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=pewit-ai-schema-builder-settings')); ?>"><?php esc_html_e('Open Settings', 'pewit-ai-schema-builder'); ?></a>
                </p>
            <?php endif; ?>

            <div class="aisb-metabox-row">
                <label for="aisb_schema_type"><?php esc_html_e('Schema type', 'pewit-ai-schema-builder'); ?></label>
                <select id="aisb_schema_type" name="aisb_schema_type">
                    <?php foreach ($types as $key => $label): ?>
                        <?php
                        $locked = !AISB_Schema::is_type_allowed($key, $post);
                        ?>
                        <option value="<?php echo esc_attr($key); ?>" <?php selected($type, $key); ?> <?php disabled($locked); ?>>
                            <?php echo esc_html($label); ?><?php echo $locked ? ' (Pro)' : ''; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="button" class="button button-primary aisb-generate-schema" <?php disabled(!$api_ready); ?>>
                    <?php esc_html_e('Generate schema', 'pewit-ai-schema-builder'); ?>
                </button>
                <button type="button" class="button aisb-regenerate-schema" <?php disabled(!$api_ready || !$schema); ?>>
                    <?php esc_html_e('Regenerate', 'pewit-ai-schema-builder'); ?>
                </button>
                <?php if (AISB_Integrations::has_faq_content($post->ID)): ?>
                <button type="button" class="button aisb-faq-schema" <?php disabled(!$api_ready); ?>>
                    <?php esc_html_e('FAQ from content', 'pewit-ai-schema-builder'); ?>
                    <?php if (AISB_Integrations::content_assist_active()): ?>
                        <span class="aisb-badge aisb-badge-etch">Content Assist</span>
                    <?php endif; ?>
                </button>
                <?php endif; ?>
            </div>

            <label for="aisb_schema_json"><?php esc_html_e('JSON-LD preview', 'pewit-ai-schema-builder'); ?></label>
            <textarea id="aisb_schema_json" class="aisb-json-preview" rows="14" placeholder="<?php esc_attr_e('Generated JSON-LD will appear here…', 'pewit-ai-schema-builder'); ?>"><?php echo esc_textarea($json_pretty); ?></textarea>

            <div class="aisb-metabox-actions">
                <button type="button" class="button button-secondary aisb-save-schema"><?php esc_html_e('Save to post', 'pewit-ai-schema-builder'); ?></button>
                <button type="button" class="button aisb-validate-schema"><?php esc_html_e('Validate', 'pewit-ai-schema-builder'); ?></button>
                <span class="aisb-metabox-status" aria-live="polite"></span>
            </div>

            <div class="aisb-validation" id="aisb-validation-panel">
                <?php if ($validation): ?>
                    <?php self::render_validation($validation); ?>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    public static function render_validation($validation) {
        $class = !empty($validation['valid']) ? 'aisb-validation-ok' : 'aisb-validation-error';
        ?>
        <div class="aisb-validation-result <?php echo esc_attr($class); ?>">
            <?php if (!empty($validation['score']['score'])): ?>
                <?php echo wp_kses_post(AISB_Rich_Results_Score::render_badge_html((int) $validation['score']['score'])); ?>
                <p class="description"><?php echo esc_html($validation['score']['label'] ?? ''); ?></p>
                <?php if (!empty($validation['score']['missing_required'])): ?>
                    <p class="description"><strong><?php esc_html_e('Missing required:', 'pewit-ai-schema-builder'); ?></strong> <?php echo esc_html(implode(', ', $validation['score']['missing_required'])); ?></p>
                <?php endif; ?>
            <?php endif; ?>
            <?php if (!empty($validation['valid'])): ?>
                <p><strong><?php esc_html_e('Validation passed', 'pewit-ai-schema-builder'); ?></strong></p>
                <?php if (!empty($validation['google'])): ?>
                    <p class="description"><?php esc_html_e('Google/Bing rich results: required fields OK', 'pewit-ai-schema-builder'); ?></p>
                <?php endif; ?>
            <?php else: ?>
                <p><strong><?php esc_html_e('Validation issues', 'pewit-ai-schema-builder'); ?></strong></p>
                <ul>
                    <?php foreach ((array) ($validation['errors'] ?? []) as $err): ?>
                        <li><?php echo esc_html($err); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
            <?php if (!empty($validation['warnings'])): ?>
                <p class="description"><?php esc_html_e('Warnings:', 'pewit-ai-schema-builder'); ?></p>
                <ul class="aisb-validation-warnings">
                    <?php foreach ($validation['warnings'] as $warn): ?>
                        <li><?php echo esc_html($warn); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function assets($hook) {
        if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
            return;
        }
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || !in_array($screen->post_type, self::supported_post_types(), true)) {
            return;
        }
        wp_enqueue_style('aisb-admin', AISB_URL . 'assets/css/admin.css', [], AISB_VERSION);
        wp_enqueue_script('aisb-post-schema', AISB_URL . 'assets/js/admin.js', ['jquery'], AISB_VERSION, true);
        wp_localize_script('aisb-post-schema', 'AISB', [
            'ajax'        => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('aisb_nonce'),
            'apiReady'    => aisb_api_ready() ? 1 : 0,
            'canAutomate' => aisb_can_automate() ? 1 : 0,
            'i18n'        => AISB_I18n::js_strings(),
        ]);
    }

    public static function maybe_auto_generate($post_id, $post, $update) {
        if (self::$auto_generating) {
            return;
        }
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
            return;
        }
        $settings = aisb_get_settings();
        if (empty($settings['auto_generate'])) {
            return;
        }
        if (!aisb_api_ready()) {
            return;
        }
        if (!in_array($post->post_type, self::supported_post_types(), true)) {
            return;
        }
        if ($post->post_status !== 'publish') {
            return;
        }
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        self::$auto_generating = true;
        @set_time_limit(120); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- Extends time limit for long-running bulk/scan jobs.
        $type = AISB_Schema::detect_type($post);
        $result = AISB_API::generate_schema($post_id, $type);
        if (!is_wp_error($result)) {
            AISB_Schema::save($post_id, $result, $type);
        }
        self::$auto_generating = false;
    }

    public static function ajax_generate() {
        check_ajax_referer('aisb_nonce', 'nonce');
        $post_id = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0;
        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error(['message' => __('Permission denied', 'pewit-ai-schema-builder')], 403);
        }
        if (!aisb_api_ready()) {
            wp_send_json_error(['message' => __('API key not ready. Save and test your key in Settings.', 'pewit-ai-schema-builder')]);
        }
        $type = isset($_POST['schema_type']) ? sanitize_key(wp_unslash($_POST['schema_type'])) : '';
        $post = get_post($post_id);
        if (!$post) {
            wp_send_json_error(['message' => __('Post not found', 'pewit-ai-schema-builder')]);
        }
        if (!AISB_Schema::is_type_allowed($type, $post)) {
            wp_send_json_error(['message' => aisb_automation_upgrade_message()]);
        }
        $result = AISB_API::generate_schema($post_id, $type);
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }
        $validation = AISB_Schema::validate($result, $type);
        $pretty = wp_json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        wp_send_json_success([
            'schema'     => $result,
            'json'       => $pretty,
            'validation' => $validation,
            'type'       => $type,
        ]);
    }

    public static function ajax_save() {
        check_ajax_referer('aisb_nonce', 'nonce');
        $post_id = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0;
        if (!current_user_can('edit_post', $post_id)) {
            wp_send_json_error(['message' => __('Permission denied', 'pewit-ai-schema-builder')], 403);
        }
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw JSON validated by AISB_Schema::save().
        $raw = isset($_POST['schema_json']) ? wp_unslash($_POST['schema_json']) : '';
        $type = isset($_POST['schema_type']) ? sanitize_key(wp_unslash($_POST['schema_type'])) : '';
        $saved = AISB_Schema::save($post_id, $raw, $type);
        if (is_wp_error($saved)) {
            wp_send_json_error(['message' => $saved->get_error_message()]);
        }
        $validation = AISB_Schema::validate($saved, $type);
        wp_send_json_success([
            'message'    => __('Schema saved to post meta.', 'pewit-ai-schema-builder'),
            'validation' => $validation,
        ]);
    }

    public static function ajax_validate() {
        check_ajax_referer('aisb_nonce', 'nonce');
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw JSON validated by json_decode() below.
        $raw = isset($_POST['schema_json']) ? wp_unslash($_POST['schema_json']) : '';
        $type = isset($_POST['schema_type']) ? sanitize_key(wp_unslash($_POST['schema_type'])) : '';
        $decoded = json_decode($raw, true);
        if (!is_array($decoded)) {
            wp_send_json_error(['message' => __('Invalid JSON', 'pewit-ai-schema-builder')]);
        }
        $validation = AISB_Schema::validate($decoded, $type);
        ob_start();
        self::render_validation($validation);
        $html = ob_get_clean();
        wp_send_json_success(['validation' => $validation, 'html' => $html]);
    }
}
