<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_shortcode( 'idsc_map', 'idsc_map_shortcode' );

function idsc_map_shortcode( $atts ) {
    IDSC_Assets::flag_css();

    $atts = shortcode_atts( array(
        'address'  => '',
        'height'   => '400',
        'zoom'     => '14',
        'provider' => 'openstreetmap',
    ), $atts, 'idsc_map' );

    if ( empty( $atts['address'] ) ) {
        return '';
    }

    $height  = max( 100, intval( $atts['height'] ) );
    $zoom    = max( 1, min( 20, intval( $atts['zoom'] ) ) );
    $address = $atts['address'];

    $html = '<div class="idsc-map" style="height:' . $height . 'px">';

    if ( $atts['provider'] === 'google' ) {
        $encoded = urlencode( $address );
        $html .= '<iframe class="idsc-map__iframe" src="https://maps.google.com/maps?q=' . esc_attr( $encoded ) . '&z=' . $zoom . '&output=embed" frameborder="0" allowfullscreen loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>';
    } else {
        // OpenStreetMap via iframe
        $encoded = urlencode( $address );
        $bbox    = '';
        $html .= '<iframe class="idsc-map__iframe" src="https://www.openstreetmap.org/export/embed.html?layer=mapnik&marker=&bbox=' . esc_attr( $bbox ) . '" frameborder="0" allowfullscreen loading="lazy"></iframe>';
        $html .= '<noscript><a href="https://www.openstreetmap.org/search?query=' . esc_attr( $encoded ) . '">' . esc_html( $address ) . '</a></noscript>';
    }

    $html .= '</div>';

    return $html;
}
