<?php
/**
 * Admin actions for managing stored translation strings.
 *
 * @package WPR_Translate
 */

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

/**
 * Handle deletion of selected strings from the admin list.
 */
function wpr_translate_admin_handle_delete_strings() {
    global $wpdb;

    // Verify nonce before processing delete requests.
    check_admin_referer( 'wpr_translate_delete_strings', 'wpr_translate_delete_nonce' );

    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( empty( $_POST['strings'] ) || ! is_array( $_POST['strings'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
        return;
    }

    $table = $wpdb->prefix . 'wpestate_translation_strings';
    $exists = ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table );

    if ( ! $exists ) {
        add_settings_error(
            'wpr_translate_strings',
            'wpr_translate_strings_delete_missing',
            __( 'The translation strings table could not be found.', 'wpr-translate' ),
            'error'
        );
        return;
    }

    $deleted_count = 0;
    $strings       = wp_unslash( $_POST['strings'] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing

    foreach ( $strings as $encoded ) {
        if ( ! is_string( $encoded ) || '' === trim( $encoded ) ) {
            continue;
        }

        $decoded = base64_decode( $encoded, true );

        if ( false === $decoded ) {
            continue;
        }

        $payload = json_decode( $decoded, true );

        if ( ! is_array( $payload ) ) {
            continue;
        }

        $context = isset( $payload['context'] ) ? sanitize_text_field( $payload['context'] ) : '';
        $name    = isset( $payload['name'] ) ? sanitize_text_field( $payload['name'] ) : '';

        if ( '' === $context || '' === $name ) {
            continue;
        }

        $result = $wpdb->delete(
            $table,
            array(
                'context' => $context,
                'name'    => $name,
            ),
            array( '%s', '%s' )
        );

        if ( false !== $result ) {
            $deleted_count++;
        }
    }

    if ( $deleted_count > 0 ) {
        $message = sprintf(
            _n(
                'Deleted %d string.',
                'Deleted %d strings.',
                $deleted_count,
                'wpr-translate'
            ),
            $deleted_count
        );

        add_settings_error(
            'wpr_translate_strings',
            'wpr_translate_strings_deleted',
            $message,
            'updated'
        );
    }

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

    $redirect = wp_get_referer();
    if ( empty( $redirect ) ) {
        $redirect = admin_url( 'admin.php?page=wpr-translate-strings' );
    }

    wp_safe_redirect( $redirect );
    exit;
}
