<?php
/**
 * Option management helpers for the language switcher widget.
 *
 * @package WPR_Translate
 */

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

if ( ! defined( 'WPR_TRANSLATE_LANGUAGE_SWITCHER_OPTION' ) ) {
    define( 'WPR_TRANSLATE_LANGUAGE_SWITCHER_OPTION', 'wpr_translate_language_switcher' );
}

/**
 * Retrieve saved widget instances.
 *
 * @return array
 */
function wpr_translate_language_switcher_get_options() {
    // Load widget options from the database.
    $options = get_option( WPR_TRANSLATE_LANGUAGE_SWITCHER_OPTION, array() );

    if ( ! is_array( $options ) ) {
        return array();
    }

    // Sanitize each stored widget instance.
    $sanitized = array();

    foreach ( $options as $number => $instance ) {
        $number = absint( $number );

        if ( $number <= 0 ) {
            continue;
        }

        $title = '';

        if ( isset( $instance['title'] ) ) {
            $title = sanitize_text_field( $instance['title'] );
        }

        $sanitized[ $number ] = array(
            'title' => $title,
        );
    }

    if ( empty( $sanitized ) ) {
        return array();
    }

    ksort( $sanitized );

    return $sanitized;
}

/**
 * Persist widget instance settings.
 *
 * @param array $options Widget options.
 */
function wpr_translate_language_switcher_save_options( $options ) {
    // Remove the option when no instances are stored.
    if ( empty( $options ) ) {
        delete_option( WPR_TRANSLATE_LANGUAGE_SWITCHER_OPTION );
        return;
    }

    // Persist widget instances to the options table.
    update_option( WPR_TRANSLATE_LANGUAGE_SWITCHER_OPTION, $options );
}

/**
 * Determine the next available widget instance number.
 *
 * @param array $options Current options.
 *
 * @return int
 */
function wpr_translate_language_switcher_next_number( $options ) {
    // Default to the first instance when no options exist.
    if ( empty( $options ) ) {
        return 1;
    }

    // Return the next numeric index.
    $numbers = array_map( 'absint', array_keys( $options ) );

    return max( $numbers ) + 1;
}
