<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class SEO_Fury_Import_Export {

    public function __construct() {
        add_action( 'wp_ajax_seo_fury_export_settings', array( $this, 'ajax_export_settings' ) );
        add_action( 'wp_ajax_seo_fury_import_settings', array( $this, 'ajax_import_settings' ) );
    }

    /**
     * Get all plugin option keys that should be exported.
     *
     * @return array
     */
    private function get_exportable_option_keys() {
        global $wpdb;

        $results = $wpdb->get_col(
            "SELECT option_name FROM {$wpdb->options}
             WHERE option_name LIKE 'seo_fury_%'
             AND option_name NOT LIKE '%_transient%'
             AND option_name NOT LIKE '%_nonce%'
             AND option_name NOT LIKE '%license%'
             AND option_name NOT LIKE '%_backup%'
             AND option_name NOT LIKE '%integrity%'
             AND option_name NOT LIKE '%installed_version%'
             AND option_name NOT LIKE '%_sf_srv_%'
             AND option_name NOT LIKE '%fingerprint%'
             AND option_name NOT LIKE '%cron%'
             AND option_name NOT LIKE '%changelog%'
             AND option_name NOT LIKE '%migration%'
             AND option_name NOT LIKE '%wizard%'
             AND option_name NOT LIKE '%db_version%'"
        );

        return $results ? $results : array();
    }

    /**
     * AJAX: Export all settings to JSON.
     */
    public function ajax_export_settings() {
        check_ajax_referer( 'seo_fury_import_export_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'seo-fury' ) ) );
        }

        $keys = $this->get_exportable_option_keys();

        $export = array(
            '_meta' => array(
                'plugin'    => 'seo-fury',
                'version'   => defined( 'SEO_FURY_VERSION' ) ? SEO_FURY_VERSION : '1.0.0',
                'site'      => home_url(),
                'exported'  => current_time( 'mysql' ),
                'wp_version' => get_bloginfo( 'version' ),
            ),
            'options' => array(),
        );

        foreach ( $keys as $key ) {
            $value = get_option( $key );
            // Skip AI keys — they are encrypted with site-specific salt
            if ( strpos( $key, 'seo_fury_ai_key_' ) === 0 ) {
                continue;
            }
            $export['options'][ $key ] = $value;
        }

        wp_send_json_success( array(
            'data'     => $export,
            'filename' => 'seo-fury-settings-' . gmdate( 'Y-m-d' ) . '.json',
        ) );
    }

    /**
     * AJAX: Import settings from JSON.
     */
    public function ajax_import_settings() {
        check_ajax_referer( 'seo_fury_import_export_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'seo-fury' ) ) );
        }

        $json = isset( $_POST['import_data'] ) ? wp_unslash( $_POST['import_data'] ) : '';
        if ( empty( $json ) ) {
            wp_send_json_error( array( 'message' => __( 'No data provided', 'seo-fury' ) ) );
        }

        $data = json_decode( $json, true );
        if ( json_last_error() !== JSON_ERROR_NONE ) {
            wp_send_json_error( array( 'message' => __( 'Invalid JSON format', 'seo-fury' ) ) );
        }

        if ( ! isset( $data['_meta']['plugin'] ) || $data['_meta']['plugin'] !== 'seo-fury' ) {
            wp_send_json_error( array( 'message' => __( 'This file is not a valid SEO Fury export', 'seo-fury' ) ) );
        }

        if ( ! isset( $data['options'] ) || ! is_array( $data['options'] ) ) {
            wp_send_json_error( array( 'message' => __( 'No settings found in the file', 'seo-fury' ) ) );
        }

        $imported = 0;
        $skipped  = 0;

        // Security: only allow seo_fury_ prefixed options
        foreach ( $data['options'] as $key => $value ) {
            if ( strpos( $key, 'seo_fury_' ) !== 0 ) {
                $skipped++;
                continue;
            }
            // Skip license, integrity, backup keys
            if ( preg_match( '/(license|integrity|backup|fingerprint|_sf_srv)/', $key ) ) {
                $skipped++;
                continue;
            }
            // Skip AI keys — cannot import encrypted keys from another site
            if ( strpos( $key, 'seo_fury_ai_key_' ) === 0 ) {
                $skipped++;
                continue;
            }

            // Sanitize string values (incl. array leaves) before writing —
            // update_option() bypasses the register_setting() sanitize
            // callbacks, so an import file must not be able to inject markup
            // into an option that is later rendered.
            update_option( $key, $this->sanitize_import_value( $value ) );
            $imported++;
        }

        wp_send_json_success( array(
            'message'  => sprintf(
                /* translators: 1: imported count, 2: skipped count */
                __( '%1$d settings imported, %2$d skipped.', 'seo-fury' ),
                $imported,
                $skipped
            ),
            'imported' => $imported,
            'skipped'  => $skipped,
        ) );
    }

    /**
     * Recursively sanitize an imported option value: string leaves are passed
     * through sanitize_textarea_field (strips tags, preserves newlines and
     * %variables%); booleans, ints and floats are preserved as-is.
     *
     * @param mixed $value
     * @return mixed
     */
    private function sanitize_import_value( $value ) {
        if ( is_array( $value ) ) {
            return array_map( array( $this, 'sanitize_import_value' ), $value );
        }
        if ( is_string( $value ) ) {
            return sanitize_textarea_field( $value );
        }
        return $value;
    }

    /**
     * Render the Import/Export section in the General tab.
     */
    public function render_section() {
        ?>
        <div class="seo-card" style="margin-top: 20px;">
            <h3 style="margin-top: 0;"><?php echo '📦 ' . esc_html__( 'Import / Export Settings', 'seo-fury' ); ?></h3>
            <p style="color: var(--sf-gray-500, #64748b); font-size: 13px; margin-bottom: 16px;">
                <?php esc_html_e( 'Export all plugin settings to a JSON file, or import settings from a previously exported file. API keys are excluded for security.', 'seo-fury' ); ?>
            </p>

            <div class="seo-fury-ie-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <!-- Export -->
                <div class="seo-fury-ie-card" style="background: var(--sf-primary-light,#F0F9FF); border: 1px solid var(--sf-gray-200,#BAE6FD); border-radius: 8px; padding: 20px;">
                    <h4 style="margin: 0 0 8px; display: flex; align-items: center; gap: 8px; color: var(--sf-gray-900);">
                        <span style="font-size: 20px;">📤</span>
                        <?php esc_html_e( 'Export Settings', 'seo-fury' ); ?>
                    </h4>
                    <p style="color: var(--sf-gray-500,#64748B); font-size: 13px; margin: 0 0 16px;">
                        <?php esc_html_e( 'Download all current settings as a JSON file. Use it as a backup or to transfer settings to another site.', 'seo-fury' ); ?>
                    </p>
                    <button type="button" class="button button-primary" id="seo-fury-export-btn">
                        <span class="dashicons dashicons-download" style="margin-top: 4px;"></span>
                        <?php esc_html_e( 'Export Settings', 'seo-fury' ); ?>
                    </button>
                </div>

                <!-- Import -->
                <div class="seo-fury-ie-card" style="background: var(--sf-warning-light,#FFF7ED); border: 1px solid var(--sf-gray-200,#FED7AA); border-radius: 8px; padding: 20px;">
                    <h4 style="margin: 0 0 8px; display: flex; align-items: center; gap: 8px; color: var(--sf-gray-900);">
                        <span style="font-size: 20px;">📥</span>
                        <?php esc_html_e( 'Import Settings', 'seo-fury' ); ?>
                    </h4>
                    <p style="color: var(--sf-gray-500,#64748B); font-size: 13px; margin: 0 0 16px;">
                        <?php esc_html_e( 'Upload a previously exported JSON file to restore or transfer settings. Existing settings will be overwritten.', 'seo-fury' ); ?>
                    </p>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <input type="file" id="seo-fury-import-file" accept=".json" style="display: none;">
                        <button type="button" class="button" id="seo-fury-import-choose-btn">
                            <span class="dashicons dashicons-upload" style="margin-top: 4px;"></span>
                            <?php esc_html_e( 'Choose File', 'seo-fury' ); ?>
                        </button>
                        <span id="seo-fury-import-filename" style="color: var(--sf-gray-500, #64748b); font-size: 13px;"></span>
                    </div>
                    <button type="button" class="button button-primary" id="seo-fury-import-btn" style="margin-top: 12px; display: none;">
                        <?php esc_html_e( 'Import Settings', 'seo-fury' ); ?>
                    </button>
                </div>
            </div>

            <div id="seo-fury-ie-result" style="margin-top: 12px;"></div>
        </div>
        <?php
    }
}
