<?php

add_filter( 'etm_machine_translation_engines', 'etm_othermt_add_engine', 6 );
/**
 * Add the Custom provider engine to the list of machine translation engines.
 *
 * @param array $engines The existing list of machine translation engines.
 * @return array The updated list of machine translation engines with the Custom provider engine added.
 */
function etm_othermt_add_engine( $engines ){
    $engines[] = array( 'value' => 'othermt', 'label' => __( 'Custom provider', 'etranslation-multilingual' ) );

    return $engines;
}

add_action( 'etm_machine_translation_extra_settings_middle', 'etm_othermt_add_settings' );
/**
 * Add the extra settings fields for the Custom provider engine.
 *
 * @param array $mt_settings The existing machine translation settings.
 */
function etm_othermt_add_settings( $mt_settings ){
    $etm                = ETM_eTranslation_Multilingual::get_etm_instance();
    $machine_translator = $etm->get_component( 'machine_translator' );

    $translation_engine = isset( $mt_settings['translation-engine'] ) ? $mt_settings['translation-engine'] : '';
    $othermt_engine = 'othermt';

    // Check for errors.
    $error_message = '';
    $show_errors   = false;

    // Validate the Custom provider Base URL.
    if ( isset( $mt_settings['other-mt-url'] ) && ! filter_var( $mt_settings['other-mt-url'], FILTER_VALIDATE_URL ) ) {
        $error_message = wp_kses( __( 'Please enter a valid URL' ), array() );
        $show_errors    = true;
    } else {
        // Check for API errors only if the translation engine is 'othermt'.
        if ( $othermt_engine === $translation_engine ) {
            $api_check = $machine_translator->check_api_key_validity();
        }

        // Check if there are errors with the API key.
        if ( isset( $api_check ) && true === $api_check['error'] ) {
            $error_message = $api_check['message'];
            $show_errors    = true;
        }
    }

    $text_input_classes = array(
        'etm-text-input',
    );

    // Add the error class to the input fields if there are errors and Custom provider is the active engine.
    if ( $show_errors && $othermt_engine === $translation_engine ) {
        $text_input_classes[] = 'etm-text-input-error';
    }

    ?>
    <tr>
        <th scope="row" id="base-url-label"><?php esc_html_e( 'Base URL', 'etranslation-multilingual' ); ?> </th>
        <td class="other-mt-fields">
        <?php
            // Display an error message above the input if there are errors and Custom provider is the active engine.
            if ( $show_errors && $othermt_engine === $translation_engine ) {
                ?>
                <p class="etm-error-inline">
                    <?php echo wp_kses_post( $error_message ); ?>
                </p>
                <?php
            }
            ?>
            <input aria-labelledby="base-url-label" type="text" class="<?php echo esc_html( implode( ' ', $text_input_classes ) ); ?>" name="etm_machine_translation_settings[other-mt-url]" value="<?php if( !empty( $mt_settings['other-mt-url'] ) ) echo esc_attr( $mt_settings['other-mt-url']);?>"/>
        </td>
    </tr>
    <tr>
        <th scope="row" id="api-key-label"><?php esc_html_e( 'API key', 'etranslation-multilingual' ); ?> </th>
        <td class="other-mt-fields">
            <input aria-labelledby="api-key-label" type="text" class="<?php echo esc_html( implode( ' ', $text_input_classes ) ); ?>" name="etm_machine_translation_settings[other-mt-key]" value="<?php if( !empty( $mt_settings['other-mt-key'] ) ) echo esc_attr( $mt_settings['other-mt-key']);?>"/>
            <?php
            // Only show errors if the Custom provider is active and the 'etm_output_svg' function exists.
            if ( $machine_translator->is_available() && $othermt_engine === $translation_engine && function_exists( 'etm_output_svg' ) ) {
                $machine_translator->automatic_translation_svg_output( $show_errors );
            }
            ?>
            <p class="description">
                <?php
                echo wp_kses(
                    __( 'Get <a target="_blank" href="https://website-translation.language-tools.ec.europa.eu/automated-translation_en">MT provider access</a>', 'etranslation-multilingual' ),
                    array(
                        'a' => array(
                            'href' => array(),
                            'target' => array(),
                        ),
                    )
                );
                ?>
            </p>
        </td>
    </tr>

    <?php
}

/**
 * Get the Custom provider API response codes.
 *
 * @param int $code The response code.
 * @return array An array containing the response message and error status.
 */
function etm_othermt_response_codes( $code ) {
    $is_error       = false;
    $code           = intval( $code );
    $return_message = '';

    // Check if the response code indicates an error (4xx or 5xx).
    if ( preg_match( '/4\d\d/', $code ) || preg_match( '/5\d\d/', $code ) ) {
        $is_error = true;
        $return_message = esc_html__( 'There was an error with your Custom provider configuration. Click on "Test API credentials" button for more details. ', 'etranslation-multilingual' );
    }

    return array(
        'message' => $return_message,
        'error'   => $is_error,
    );
}

add_filter( 'pre_update_option_etm_machine_translation_settings', function( $new_value, $old_value ) {
    $keys = array( 'other-mt-url', 'other-mt-key' );
    $mt_provider_data_changed = false;

    foreach( $keys as $key ) {
        if ( $new_value && $new_value[ $key ] && ( ! $old_value || $old_value[ $key ] != $new_value[ $key ] ) ) {
            $mt_provider_data_changed = true;
            break;
        }
    }
    
    if ( $mt_provider_data_changed ) {
        // delete domain list.
        delete_option( 'etm_mt_domains_othermt' );
        // delete domain selection.
        $etm = ETM_eTranslation_Multilingual::get_etm_instance();
        $settings = $etm->get_component( 'settings' )->get_settings();
        unset( $settings['translation-languages-domain-parameter'] );
        update_option( 'etm_settings', $settings );
    }

    return $new_value;
}, 10, 2 );