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

/**
 * Per-post analysis metabox — runs every module for a single page and lets you
 * insert generated FAQ/Q&A into the content. Auto-analyze on save is Pro.
 */
class AIVT_Post_Editor {

    public static function init() {
        add_action('add_meta_boxes', [__CLASS__, 'add_box']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'assets']);
        add_action('save_post', [__CLASS__, 'maybe_auto_analyze'], 20, 3);
    }

    public static function assets($hook) {
        if (!in_array($hook, ['post.php', 'post-new.php'], true)) {
            return;
        }
        $screen = get_current_screen();
        if (!$screen || !in_array($screen->post_type, aivt_enabled_post_types(), true)) {
            return;
        }
        AIVT_Admin::enqueue_core();
    }

    public static function add_box() {
        foreach (aivt_enabled_post_types() as $pt) {
            add_meta_box('aivt-analysis', 'Pewit GEO Analysis Tool', [__CLASS__, 'render_box'], $pt, 'normal', 'high');
        }
    }

    public static function render_box($post) {
        $pid = (int) $post->ID;
        $geo = AIVT_Store::get($pid, AIVT_Store::META_GEO);
        $api_ready = aivt_api_ready();
        ?>
        <div class="aivt-metabox" data-post-id="<?php echo esc_attr($pid); ?>">
            <?php if (!$api_ready): ?>
                <p class="aivt-notice aivt-notice-warn">
                    <?php esc_html_e('Connect your AI key in GEO Analysis Tool → Settings to enable analysis.', 'pewit-geo-analysis-tool'); ?>
                    <a href="<?php echo esc_url(aivt_admin_url('settings')); ?>"><?php esc_html_e('Open settings', 'pewit-geo-analysis-tool'); ?></a>
                </p>
            <?php endif; ?>

            <div class="aivt-metabox-status" aria-live="polite"></div>

            <nav class="aivt-mb-tabs">
                <button type="button" class="aivt-mb-tab is-active" data-tab="autopilot"><?php esc_html_e('⚡ Autopilot', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="geo"><?php esc_html_e('GEO Score', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="entities"><?php esc_html_e('Entities', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="eeat"><?php esc_html_e('E-E-A-T', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="citability"><?php esc_html_e('Citability', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="faq"><?php esc_html_e('FAQ', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="qa"><?php esc_html_e('Q&A', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="aivt-mb-tab" data-tab="schema"><?php esc_html_e('Schema', 'pewit-geo-analysis-tool'); ?></button>
            </nav>

            <div class="aivt-mb-panel" data-panel="autopilot">
                <p class="description"><?php esc_html_e('One click: generate an answer-first intro, key facts, FAQ and schema based on this page’s weak GEO areas. Preview the predicted score, then apply (a revision is saved — fully reversible).', 'pewit-geo-analysis-tool'); ?></p>
                <div class="pewit-actions">
                    <button type="button" class="button button-primary aivt-autopilot-run" <?php disabled(!$api_ready); ?>><?php esc_html_e('Run GEO Autopilot', 'pewit-geo-analysis-tool'); ?></button>
                    <button type="button" class="button aivt-autopilot-apply" hidden><?php esc_html_e('Apply changes', 'pewit-geo-analysis-tool'); ?></button>
                    <button type="button" class="button aivt-autopilot-revert" <?php echo AIVT_Autopilot::has_backup($pid) ? '' : 'hidden'; ?>><?php esc_html_e('Revert Autopilot', 'pewit-geo-analysis-tool'); ?></button>
                </div>
                <div class="aivt-panel-result aivt-autopilot-result"></div>
            </div>
            <div class="aivt-mb-panel" data-panel="geo" hidden>
                <button type="button" class="button button-primary aivt-analyze-btn" data-kind="geo" <?php disabled(!$api_ready); ?>><?php esc_html_e('Analyze GEO Score', 'pewit-geo-analysis-tool'); ?></button>
                <div class="aivt-panel-result"><?php AIVT_Render::geo($geo, $pid); ?></div>
            </div>
            <div class="aivt-mb-panel" data-panel="entities" hidden>
                <button type="button" class="button button-primary aivt-analyze-btn" data-kind="entities" <?php disabled(!$api_ready); ?>><?php esc_html_e('Detect entities', 'pewit-geo-analysis-tool'); ?></button>
                <div class="aivt-panel-result"><?php AIVT_Render::entities(AIVT_Store::get($pid, AIVT_Store::META_ENTITIES)); ?></div>
            </div>
            <div class="aivt-mb-panel" data-panel="eeat" hidden>
                <button type="button" class="button button-primary aivt-analyze-btn" data-kind="eeat" <?php disabled(!$api_ready); ?>><?php esc_html_e('Analyze E-E-A-T', 'pewit-geo-analysis-tool'); ?></button>
                <div class="aivt-panel-result"><?php AIVT_Render::eeat(AIVT_Store::get($pid, AIVT_Store::META_EEAT)); ?></div>
            </div>
            <div class="aivt-mb-panel" data-panel="citability" hidden>
                <button type="button" class="button button-primary aivt-analyze-btn" data-kind="citability" <?php disabled(!$api_ready); ?>><?php esc_html_e('Analyze citability', 'pewit-geo-analysis-tool'); ?></button>
                <div class="aivt-panel-result"><?php AIVT_Render::citability(AIVT_Store::get($pid, AIVT_Store::META_CITE)); ?></div>
            </div>
            <div class="aivt-mb-panel" data-panel="faq" hidden>
                <button type="button" class="button button-primary aivt-generate-btn" data-kind="faq" <?php disabled(!$api_ready); ?>><?php esc_html_e('Generate FAQ', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="button aivt-insert-btn" data-kind="faq" hidden><?php esc_html_e('Insert into post', 'pewit-geo-analysis-tool'); ?></button>
                <div class="aivt-panel-result"></div>
            </div>
            <div class="aivt-mb-panel" data-panel="qa" hidden>
                <button type="button" class="button button-primary aivt-generate-btn" data-kind="qa" <?php disabled(!$api_ready); ?>><?php esc_html_e('Generate Q&A', 'pewit-geo-analysis-tool'); ?></button>
                <button type="button" class="button aivt-insert-btn" data-kind="qa" hidden><?php esc_html_e('Insert into post', 'pewit-geo-analysis-tool'); ?></button>
                <div class="aivt-panel-result"></div>
            </div>
            <div class="aivt-mb-panel" data-panel="schema" hidden>
                <button type="button" class="button button-primary aivt-generate-btn" data-kind="schema" <?php disabled(!$api_ready); ?>><?php esc_html_e('Generate schema', 'pewit-geo-analysis-tool'); ?></button>
                <p class="description"><?php
                    if (AIVT_Schema::schema_builder_active()) {
                        esc_html_e('AI Schema Builder handles frontend output; this is a preview/copy.', 'pewit-geo-analysis-tool');
                    } else {
                        esc_html_e('Saved schema is output on this page automatically.', 'pewit-geo-analysis-tool');
                    }
                ?></p>
                <textarea class="large-text code aivt-schema-json" rows="10" readonly></textarea>
            </div>
        </div>
        <?php
    }

    /** Pro: auto-analyze GEO on publish/update. */
    public static function maybe_auto_analyze($post_id, $post, $update) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) return;
        if ($post->post_status !== 'publish') return;
        if (!in_array($post->post_type, aivt_enabled_post_types(), true)) return;
        if (!aivt_api_ready()) return;
        $s = aivt_get_settings();
        if (empty($s['auto_analyze'])) return;
        // Defer to a single-run cron tick to avoid blocking the save request.
        wp_schedule_single_event(time() + 30, 'aivt_process_queue');
        $job = AIVT_Queue::get_job();
        if (!$job || !in_array($job['status'] ?? '', ['running', 'paused'], true)) {
            // Lightweight inline analysis for the just-saved post.
            AIVT_GEO_Score::analyze($post_id);
        }
    }
}
