<?php
/**
 * Reset settings and stored translation data.
 *
 * @package WPR_Translate
 */

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

/**
 * Handle the reset settings form submission.
 */
function wpr_translate_admin_handle_reset_settings() {
    // Ensure the reset form was submitted.
    if ( empty( $_POST['wpr_translate_reset_settings'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
        return;
    }

    // Only allow admins to reset plugin data.
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    // Validate the reset nonce before mutating data.
    check_admin_referer( 'wpr_translate_reset_settings', 'wpr_translate_reset_settings_nonce' );

    // Perform the reset and capture any errors.
    $result = wpr_translate_admin_reset_plugin_data();

    if ( is_wp_error( $result ) ) {
        add_settings_error(
            'wpr_translate_settings',
            'wpr_translate_reset_error',
            $result->get_error_message(),
            'error'
        );
    } else {
        add_settings_error(
            'wpr_translate_settings',
            'wpr_translate_reset_success',
            __( 'Translation settings were reset. Existing translated posts were kept.', 'wpr-translate' ),
            'updated'
        );
    }

    set_transient( 'settings_errors', get_settings_errors(), 30 );

    // Redirect back to the settings page with a status flag.
    $redirect = add_query_arg(
        array(
            'page'             => 'wpr-translate-settings',
            'settings-updated' => 'true',
        ),
        admin_url( 'admin.php' )
    );

    wp_safe_redirect( $redirect );
    exit;
}

/**
 * Reset plugin data while keeping translated posts.
 *
 * @return true|WP_Error
 */
function wpr_translate_admin_reset_plugin_data() {
    global $wpdb;

    // Clear plugin-owned tables without touching posts.
    $tables = array(
        $wpdb->prefix . 'wpestate_translation_translations',
        $wpdb->prefix . 'wpestate_translation_strings',
        $wpdb->prefix . 'wpestate_translation_slugs',
        $wpdb->prefix . 'wpestate_translation_glossary',
        $wpdb->prefix . 'wpestate_translation_memory',
        $wpdb->prefix . 'wpestate_translation_languages',
    );

    foreach ( $tables as $table ) {
        // Skip tables that do not exist in this installation.
        $exists = ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table );

        if ( ! $exists ) {
            continue;
        }

        // Truncate table data while keeping the schema intact.
        $truncated = $wpdb->query( "TRUNCATE TABLE {$table}" );

        if ( false === $truncated ) {
            return new WP_Error(
                'wpr_translate_reset_table_failed',
                sprintf(
                    /* translators: %s: Database table name. */
                    __( 'Failed to clear data from %s.', 'wpr-translate' ),
                    esc_html( $table )
                )
            );
        }
    }

    // Remove stored plugin options and cached state.
    $options = array(
        'wpr_translate_version',
        'wpr_translate_languages',
        'wpr_translate_language_catalog',
        'wpr_translate_settings',
        'wpr_translate_auto_translation',
        'wpr_translate_glossary',
        'wpr_translate_theme_admin_strings_domain',
        'wpr_translate_theme_admin_strings_hash',
        'wpr_translate_theme_widget_strings_domain',
        'wpr_translate_theme_widget_strings_hash',
        'wpr_translate_scan_state',
        'wpr_translate_custom_directory',
        'wpr_cf_rules_defaults',
        'wpr_cf_rule_overrides',
        'wpr_cf_file_state',
        'wpr_translate_language_switcher',
    );

    foreach ( $options as $option_name ) {
        // Remove each known plugin option.
        delete_option( $option_name );
    }

    if ( function_exists( 'wpr_translate_clear_custom_field_rules_cache' ) ) {
        // Clear in-memory caches after resetting options.
        wpr_translate_clear_custom_field_rules_cache();
    }

    if ( function_exists( 'wpr_translate_activate_plugin' ) ) {
        // Re-run activation to rebuild defaults after the reset.
        wpr_translate_activate_plugin();
    }

    return true;
}
