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

class AISB_Admin_Columns {
    public static function init() {
        add_filter('manage_post_posts_columns', [__CLASS__, 'columns']);
        add_action('manage_post_posts_custom_column', [__CLASS__, 'render'], 10, 2);
        add_filter('manage_page_posts_columns', [__CLASS__, 'columns']);
        add_action('manage_page_posts_custom_column', [__CLASS__, 'render'], 10, 2);

        $types = AISB_CPT_Registry::get_enabled_post_types();
        foreach ($types as $type) {
            if (in_array($type, ['post', 'page'], true)) {
                continue;
            }
            add_filter("manage_{$type}_posts_columns", [__CLASS__, 'columns']);
            add_action("manage_{$type}_posts_custom_column", [__CLASS__, 'render'], 10, 2);
        }

        add_action('wp_ajax_aisb_export_score_csv', [__CLASS__, 'ajax_export_csv']);
    }

    public static function columns($cols) {
        $new = [];
        foreach ($cols as $key => $label) {
            $new[$key] = $label;
            if ($key === 'title') {
                $new['aisb_rr_score'] = __('Schema score', 'pewit-ai-schema-builder');
            }
        }
        return $new;
    }

    public static function render($column, $post_id) {
        if ($column !== 'aisb_rr_score') {
            return;
        }
        $schema = AISB_Schema::get_json($post_id);
        if (!$schema) {
            echo '<span class="aisb-col-none">—</span>';
            return;
        }
        $result = AISB_Rich_Results_Score::compute($schema);
        echo wp_kses_post(AISB_Rich_Results_Score::render_badge_html((int) $result['score'], true));
    }

    public static function ajax_export_csv() {
        check_ajax_referer('aisb_admin', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'pewit-ai-schema-builder')], 403);
        }

        $post_types = AISB_CPT_Registry::get_enabled_post_types();
        $rows = [['post_id', 'title', 'type', 'score', 'grade', 'has_schema']];

        $q = new WP_Query([
            'post_type'      => $post_types,
            'post_status'    => 'publish',
            'posts_per_page' => 1000,
            'fields'         => 'ids',
            'no_found_rows'  => true,
        ]);

        foreach ($q->posts as $post_id) {
            $schema = AISB_Schema::get_json($post_id);
            $score = '';
            $grade = '';
            $has = $schema ? 'yes' : 'no';
            if ($schema) {
                $r = AISB_Rich_Results_Score::compute($schema);
                $score = (int) $r['score'];
                $grade = $r['grade'] ?? '';
            }
            $rows[] = [
                (int) $post_id,
                get_the_title($post_id),
                get_post_type($post_id),
                $score,
                $grade,
                $has,
            ];
        }

        wp_send_json_success(['csv' => self::to_csv($rows)]);
    }

    private static function to_csv($rows) {
        $out = fopen('php://temp', 'r+'); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- In-memory CSV buffer, not a filesystem write.
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
        rewind($out);
        $csv = stream_get_contents($out);
        fclose($out); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- In-memory CSV buffer, not a filesystem write.
        return $csv;
    }
}
