<?php
/**
 * Registration bootstrap for the language switcher widget.
 *
 * @package WPR_Translate
 */

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

require_once WPR_TRANSLATE_PATH . 'includes/widgets/language-switcher-options.php';
require_once WPR_TRANSLATE_PATH . 'includes/widgets/language-switcher-display.php';
require_once WPR_TRANSLATE_PATH . 'includes/widgets/language-switcher-control.php';

/**
 * Register the language switcher widget instances.
 */
function wpr_translate_register_language_switcher_widget() {
    // Define the base widget and control settings shared across instances.
    $widget_ops  = array(
        'classname'   => 'wpr-language-switcher-widget',
        'description' => __( 'Displays a dropdown allowing visitors to change the active language.', 'wpr-translate' ),
    );
    $control_ops = array(
        'id_base' => 'wpr_translate_language_switcher',
    );
    $name        = __( 'WPResidence Language Switcher', 'wpr-translate' );
    $options     = wpr_translate_language_switcher_get_options();

    if ( empty( $options ) ) {
        // Seed the widget options array when the plugin runs for the first time.
        $options = array(
            1 => array( 'title' => '' ),
        );
        wpr_translate_language_switcher_save_options( $options );
    }

    // Register each saved widget instance individually.
    foreach ( $options as $number => $instance ) {
        $id = 'wpr_translate_language_switcher-' . $number;

        // Register an individual widget instance with its configuration.
        wp_register_sidebar_widget(
            $id,
            $name,
            'wpr_translate_language_switcher_widget_display',
            $widget_ops,
            array( 'number' => $number )
        );

        // Pair each widget instance with its control form handler.
        wp_register_widget_control(
            $id,
            $name,
            'wpr_translate_language_switcher_widget_control',
            $control_ops,
            array( 'number' => $number )
        );
    }

    // Register a catch-all widget entry so new instances can be created from the widgets screen.
    wp_register_sidebar_widget(
        'wpr_translate_language_switcher',
        $name,
        'wpr_translate_language_switcher_widget_display',
        $widget_ops,
        array( 'number' => -1 )
    );

    // Also register a default widget instance so users can add it directly from the widgets screen.
    wp_register_widget_control(
        'wpr_translate_language_switcher',
        $name,
        'wpr_translate_language_switcher_widget_control',
        $control_ops,
        array( 'number' => -1 )
    );
}
