<?php
/**
 * Admin control form for the language switcher widget.
 *
 * @package WPR_Translate
 */

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

/**
 * Render the widget configuration form.
 *
 * @param array $args Widget control arguments.
 */
function wpr_translate_language_switcher_widget_control( $args ) {
    // Load existing widget instances and current index.
    $options = wpr_translate_language_switcher_get_options();
    $number  = isset( $args['number'] ) ? (int) $args['number'] : -1;

    if ( -1 === $number ) {
        // Create a new widget instance when needed.
        $number             = wpr_translate_language_switcher_next_number( $options );
        $options[ $number ] = array( 'title' => '' );
        wpr_translate_language_switcher_save_options( $options );
        wpr_translate_register_language_switcher_widget();
    }

    if ( 'post' === strtolower( $_SERVER['REQUEST_METHOD'] ?? '' ) ) {
        // Validate the widget placement and persist submitted changes.
        $sidebar = isset( $_POST['sidebar'] ) ? sanitize_text_field( wp_unslash( $_POST['sidebar'] ) ) : '';

        if ( $sidebar ) {
            $sidebars_widgets = wp_get_sidebars_widgets();

            if ( isset( $sidebars_widgets[ $sidebar ] ) ) {
                $widget_ids = $sidebars_widgets[ $sidebar ];

                if ( ! in_array( 'wpr_translate_language_switcher-' . $number, $widget_ids, true ) ) {
                    unset( $options[ $number ] );
                    wpr_translate_language_switcher_save_options( $options );
                    return;
                }
            }
        }

        $submitted = isset( $_POST['wpr-translate-language-switcher'] ) ? wp_unslash( $_POST['wpr-translate-language-switcher'] ) : array();

        if ( isset( $submitted[ $number ] ) && is_array( $submitted[ $number ] ) ) {
            $title = isset( $submitted[ $number ]['title'] ) ? sanitize_text_field( $submitted[ $number ]['title'] ) : '';
            $options[ $number ] = array( 'title' => $title );
            wpr_translate_language_switcher_save_options( $options );
        }
    }

    // Render the title field with the saved value.
    $title = isset( $options[ $number ]['title'] ) ? $options[ $number ]['title'] : '';
    ?>
    <p>
        <label for="wpr-translate-language-switcher-title-<?php echo esc_attr( $number ); ?>"><?php esc_html_e( 'Title:', 'wpr-translate' ); ?></label>
        <input class="widefat" id="wpr-translate-language-switcher-title-<?php echo esc_attr( $number ); ?>" name="wpr-translate-language-switcher[<?php echo esc_attr( $number ); ?>][title]" type="text" value="<?php echo esc_attr( $title ); ?>" />
    </p>
    <input type="hidden" name="wpr-translate-language-switcher[<?php echo esc_attr( $number ); ?>][number]" value="<?php echo esc_attr( $number ); ?>" />
    <?php
}
