<?php
/**
 * This function generates the shortcode to add the plugin.
 *
 * @return string The HTML code for the shortcode.
 */
function Irent_Generate_ShortCode_Script()
{

    $data = Irent_Get_Data_DB();
    
    // Define the default attributes and map them to the retrieved data
    $atts = array(
        'code'     => $data['code'],                    // Client ID code
        'map_key'  => $data['map_key'],                 // The map API key
        'theme'    => $data['theme'],                   // Colour theme, e.g., 'beige'
        'language' => $data['language'] === 'auto' ?    // Language, e.g., 'en'
            Irent_Get_HTML_Language() :
            $data['language'],
    );

    // Sanitize and escape all attribute values to prevent security vulnerabilities
    array_walk($atts, function (&$value) {
        $value = esc_attr(sanitize_text_field($value));
    });

    $result = Irent_Validate_Keys(array_filter($atts, function ($key) {
        return $key !== 'map_key';
    }, ARRAY_FILTER_USE_KEY));

    if (is_wp_error($result)) {
        return Irent_Get_Error_Messages($result->get_error_message());
    }

    // Start output buffering to capture the generated HTML
    ob_start();
    ?>
        <irent-script
            website-code="<?php echo esc_attr($atts['code'])?>"
            map-key="<?php echo esc_attr($atts['map_key'])?>"
            theme="<?php echo esc_attr($atts['theme'])?>"
            language="<?php echo esc_attr($atts['language'])?>">
        </irent-script>
    <?php
    
    // Get the buffered output and store it in $output
    $output = ob_get_clean();

    // Enqueue the necessary external script from i-rent.net
    wp_enqueue_script('irent-script', IRENT_API_URL_SCRIPT . '/js/app.js', array(), null, true);

    // Return the generated HTML for the shortcode
    return $output;
}
