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


        add_action( 'admin_init', function () {

            if ( ! is_admin() ) {
                return;
            }

            if (
                empty( $_POST['ss_export_csv_scanner'] ) ||
                ! isset( $_POST['ss_export_csv_nonce'] ) ||
                ! check_admin_referer( 'ss_export_csv', 'ss_export_csv_nonce' )
            ) {
                return;
            }

            if ( ! current_user_can( 'manage_options' ) ) {
                wp_die( 'Unauthorized' );
            }

            global $wpdb;

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $rows = $wpdb->get_results(
                "SELECT id, url, status, log, finished_at
                FROM {$wpdb->prefix}ss_scans"
            );

            if ( empty( $rows ) ) {
                wp_die( esc_html__( 'No data found to export.', 'searchshifter' ) );
            }

            if ( ob_get_length() ) {
                ob_end_clean();
            }

            header( 'Content-Type: text/csv; charset=utf-8' );
            header( 'Content-Disposition: attachment; filename=scanner-report.csv' );
            header( 'Pragma: no-cache' );
            header( 'Expires: 0' );

            $output = fopen( 'php://output', 'w' );
            fputcsv( $output, [ 'ID', 'URL', 'Status', 'Log', 'Finished At' ] );

            foreach ( $rows as $r ) {
                fputcsv(
                    $output,
                    [
                        $r->id,
                        $r->url,
                        $r->status,
                        wp_strip_all_tags( substr( (string) $r->log, 0, 200 ) ),
                        $r->finished_at,
                    ]
                );
            }

            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Closing php://output stream is required.
            fclose( $output );
            exit;
        });

        add_action( 'admin_init', 'searchshifter_handle_authority_import', 1 );
        function searchshifter_handle_authority_import() {

            if (
                ! isset( $_GET['ss_import_authority'], $_GET['_wpnonce'] ) ||
                ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'ss_import_authority' )
            ) {
                return;
            }

            $file = WP_CONTENT_DIR . '/uploads/searchshifter/authority_glossary.json';
            if (!file_exists($file)) {
                wp_die("authority_glossary.json not found");
            }

            $json = file_get_contents($file);
            $terms = json_decode($json, true);

            foreach ($terms as $t) {
                if (empty($t['term']) || empty($t['definition'])) continue;

                $title = sanitize_text_field($t['term']);
                $definition = wp_kses_post($t['definition']);
                $same_as = esc_url_raw($t['same_as'] ?? '');

                // 🔁 Replacement for get_page_by_title()
                $query = new WP_Query(
                    [
                        'post_type'      => 'ss_glossary',
                        'post_status'    => 'any',
                        'title'          => $title,
                        'posts_per_page' => 1,
                        'no_found_rows'  => true,
                    ]
                );

                $existing = $query->posts[0] ?? null;

                if ($existing) {
                    wp_update_post([
                        'ID' => $existing->ID,
                        'post_content' => $definition,
                    ]);

                    if ($same_as) update_post_meta($existing->ID, 'ss_same_as', $same_as);
                    continue;
                }

                $id = wp_insert_post([
                    'post_title' => $title,
                    'post_content' => $definition,
                    'post_type' => 'ss_glossary',
                    'post_status' => 'publish',
                ]);

                if ($id && $same_as) update_post_meta($id, 'ss_same_as', $same_as);
            }

            wp_safe_redirect(admin_url('edit.php?post_type=ss_glossary&imported=1'));
            exit;
        }
        // Legacy alias
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
        function ss_handle_authority_import() {
            searchshifter_handle_authority_import();
        }