<?php
/**
 * Generates the shortcode to add the quick search form.
 *
 * @return string The HTML output of the quick search form.
 */
function Irent_Generate_ShortCode_QuickSearch()
{
    // Fetch the necessary data from the database
    $data = Irent_Get_Data_DB();

    // Plain-text attributes — safe to sanitize and escape as text
    $atts = array(
        'guid'    => $data['code'],
        'page-id' => get_permalink($data['searchId']),
        'theme'   => 'theme_' . $data['theme'],
        'lang'    => $data['language'] === 'auto' ? Irent_Get_HTML_Language() : $data['language'],
    );

    array_walk($atts, function (&$value) {
        $value = esc_attr(sanitize_text_field($value));
    });

    // JSON attributes — esc_attr once is enough; sanitize_text_field corrupts JSON
    $plugin_version = defined('IRENT_PLUGIN_VERSION') ? IRENT_PLUGIN_VERSION : '1.0.0';
    $json_atts = array(
        'css-urls' => esc_attr(wp_json_encode([
            'common' => plugins_url('../../assets/css/common.css', __FILE__) . '?v=' . $plugin_version,
        ])),
        'js-urls' => esc_attr(wp_json_encode([
            'common' => plugins_url('../../assets/js/component-library.umd.cjs', __FILE__) . '?v=' . $plugin_version,
        ])),
    );

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

    ob_start();
    ?>
        <irent-quicksearch id='IQuickSearch'
            guid="<?php echo $atts['guid']?>"
            page-id="<?php echo $atts['page-id']?>"
            theme="<?php echo $atts['theme']?>"
            lang="<?php echo $atts['lang']?>"
            css-urls="<?php echo $json_atts['css-urls']?>"
            js-urls="<?php echo $json_atts['js-urls']?>"
        ></irent-quicksearch>
    <?php
    
    // Capture the output into a variable
    $output = ob_get_clean();

    // Enqueue necessary scripts and styles, and pass translations to the frontend
    wp_enqueue_script('irent-quick-search-script', plugins_url('../../assets/js/quick-search.js', __FILE__), array(), $plugin_version, true);
    wp_add_inline_script(
        'irent-quick-search-script',
        'const IRENT_API_URL_API = ' . wp_json_encode(IRENT_API_URL_API) . ';' .
        'const IRENT_API_URL_EDITOR = ' . wp_json_encode(IRENT_API_URL_EDITOR) . ';',
        'before'
    );
    return $output;
}
