<?php
/**
 * Server-side render for playard/facility-map block.
 *
 * @var array<string,mixed> $attributes
 */
if ( ! defined( 'ABSPATH' ) ) exit;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

global $wpdb;

$height       = max( 200, min( 700, (int) ( $attributes['height']      ?? 420  ) ) );
$zoom         = max( 10,  min( 20,  (int) ( $attributes['zoom']        ?? 15   ) ) );
$rounded      = (bool) ( $attributes['rounded']     ?? true  );
$show_card    = (bool) ( $attributes['showCard']    ?? true  );
$show_phone   = (bool) ( $attributes['showPhone']   ?? true  );
$show_address = (bool) ( $attributes['showAddress'] ?? true  );

$facility = $wpdb->get_row(
	"SELECT name, address, lat, lng, phone
	 FROM {$wpdb->prefix}playard_facilities
	 WHERE status = 'active'
	 ORDER BY id ASC
	 LIMIT 1"
);

if ( ! $facility || empty( $facility->address ) ) {
	echo '<p style="color:#94A3B8;font-size:14px;padding:24px;text-align:center;background:#F8FAFC;border-radius:12px;border:1px dashed #E2E8F0;">'
		. esc_html__( 'No facility address configured. Add it in Playard → Facility Setup.', 'playard' )
		. '</p>';
	return;
}

// Prefer stored lat/lng; otherwise geocode server-side so the embed always
// uses coordinates — text-address embeds fail for public (non-logged-in) users.
$lat = (float) ( $facility->lat ?? 0 );
$lng = (float) ( $facility->lng ?? 0 );

if ( $lat === 0.0 && $lng === 0.0 ) {
	$geo = playard_geocode_address( (string) $facility->address );
	if ( $geo ) {
		$lat = $geo['lat'];
		$lng = $geo['lng'];
	}
}

if ( $lat !== 0.0 || $lng !== 0.0 ) {
	// Coordinate-based embed — never requires Google login to render correctly
	$map_query      = $lat . ',' . $lng;
	$directions_dst = $lat . ',' . $lng;
} else {
	// Last resort: plain address string (may not render on public pages)
	$map_query      = rawurlencode( (string) $facility->address );
	$directions_dst = $map_query;
}

$map_src        = 'https://maps.google.com/maps?q=' . $map_query . '&output=embed&hl=en&z=' . $zoom;
$directions_url = 'https://www.google.com/maps/dir/?api=1&destination=' . $directions_dst;
$radius         = $rounded ? '12px' : '0';
$uid            = 'pfm-' . wp_rand( 1000, 9999 );

// Build scoped CSS in a buffer, then emit via wp_add_inline_style() —
// WordPress.org forbids raw inline <style> tags in markup.
ob_start();
?>
/* Outer wrapper — NO overflow:hidden so overlays aren't clipped */
.<?php echo esc_attr( $uid ); ?>{position:relative;width:100%;}

/* Inner iframe wrapper handles clipping for rounded corners */
.<?php echo esc_attr( $uid ); ?> .py-map-frame{overflow:hidden;border-radius:<?php echo esc_attr( $radius ); ?>;line-height:0;}
.<?php echo esc_attr( $uid ); ?> .py-map-frame iframe{display:block;width:100%;height:<?php echo esc_attr( $height ); ?>px;border:0;}

/* Overlays sit inside the outer wrapper — free from clipping */
.<?php echo esc_attr( $uid ); ?> .py-map-card{
  position:absolute;bottom:24px;left:16px;
  background:#fff;border-radius:12px;
  padding:14px 18px;
  box-shadow:0 6px 24px rgba(15,23,42,.18);
  max-width:240px;z-index:10;
}
.<?php echo esc_attr( $uid ); ?> .py-map-card__name{font-size:14px;font-weight:700;color:#0F172A;margin:0 0 2px;}
.<?php echo esc_attr( $uid ); ?> .py-map-card__row{display:flex;align-items:flex-start;gap:7px;margin-top:7px;}
.<?php echo esc_attr( $uid ); ?> .py-map-card__icon{flex-shrink:0;width:15px;height:15px;margin-top:1px;stroke:#3B82F6;fill:none;}
.<?php echo esc_attr( $uid ); ?> .py-map-card__text{font-size:12px;color:#64748B;line-height:1.4;margin:0;}
.<?php echo esc_attr( $uid ); ?> .py-map-card__phone{font-size:13px;color:#3B82F6;font-weight:600;text-decoration:none;line-height:1;}
.<?php echo esc_attr( $uid ); ?> .py-map-card__phone:hover{text-decoration:underline;}

.<?php echo esc_attr( $uid ); ?> .py-map-directions{
  position:absolute;bottom:24px;right:16px;z-index:10;
  background:#0F172A;color:#fff;
  font-size:12px;font-weight:600;
  padding:9px 16px;border-radius:8px;
  text-decoration:none;
  display:inline-flex;align-items:center;gap:6px;
  transition:opacity .15s;
  white-space:nowrap;
}
.<?php echo esc_attr( $uid ); ?> .py-map-directions:hover{opacity:.82;color:#fff;}
<?php
$playard_css    = ob_get_clean();
$playard_handle = 'playard-facility-map-block';
wp_register_style( $playard_handle, false, [], PLAYARD_VERSION );
wp_enqueue_style( $playard_handle );
wp_add_inline_style( $playard_handle, $playard_css );
?>

<div class="<?php echo esc_attr( $uid ); ?>">

  <!-- iframe in its own clipping shell -->
  <div class="py-map-frame">
    <iframe
      src="<?php echo esc_url( $map_src ); ?>"
      allowfullscreen=""
      loading="lazy"
      referrerpolicy="no-referrer-when-downgrade"
      <?php /* translators: %s: facility name */ ?>
      title="<?php echo esc_attr( sprintf( __( '%s location map', 'playard' ), $facility->name ) ); ?>"
    ></iframe>
  </div>

  <?php if ( $show_card ) : ?>
  <div class="py-map-card">
    <p class="py-map-card__name"><?php echo esc_html( $facility->name ); ?></p>

    <?php if ( $show_address && $facility->address ) : ?>
    <div class="py-map-card__row">
      <svg class="py-map-card__icon" viewBox="0 0 24 24" stroke-width="2">
        <path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/>
        <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1 1 15 0Z"/>
      </svg>
      <p class="py-map-card__text"><?php echo esc_html( $facility->address ); ?></p>
    </div>
    <?php endif; ?>

    <?php if ( $show_phone && $facility->phone ) : ?>
    <div class="py-map-card__row">
      <svg class="py-map-card__icon" viewBox="0 0 24 24" stroke-width="2">
        <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z"/>
      </svg>
      <a class="py-map-card__phone" href="tel:<?php echo esc_attr( $facility->phone ); ?>">
        <?php echo esc_html( $facility->phone ); ?>
      </a>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <a
    class="py-map-directions"
    href="<?php echo esc_url( $directions_url ); ?>"
    target="_blank"
    rel="noopener noreferrer"
  >
    <svg width="13" height="13" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
      <path stroke-linecap="round" stroke-linejoin="round" d="M9 6.75V15m6-6v8.25m.503 3.498 4.875-2.437c.381-.19.622-.58.622-1.006V4.82c0-.836-.88-1.38-1.628-1.006l-3.869 1.934c-.317.159-.69.159-1.006 0L9.503 3.252a1.125 1.125 0 0 0-1.006 0L3.622 5.689C3.24 5.88 3 6.27 3 6.695V19.18c0 .836.88 1.38 1.628 1.006l3.869-1.934c.317-.159.69-.159 1.006 0l4.994 2.497c.317.158.69.158 1.006 0Z"/>
    </svg>
    <?php esc_html_e( 'Directions', 'playard' ); ?>
  </a>

</div>
