<?php
defined('ABSPATH') || exit;

// Icon pack for this card.
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$icon_pack = 'erikflowers';

wp_enqueue_style(
    'erik-icons-core',
    plugin_dir_url(__FILE__) . '../weather-icons/css/weather-icons.css',
    array(),
    '1.0.0'
);

wp_enqueue_style(
    'mw-card15-style',
    plugin_dir_url(__FILE__) . '../assets/card/card15-style.css',
    array(),
    time()
);

require_once plugin_dir_path(__FILE__) . '../inc/icon-loader.php';
require_once plugin_dir_path(__FILE__) . '../inc/utilities.php';
require_once plugin_dir_path(__FILE__) . '../inc/tide-loader.php';

if ( ! wp_script_is( 'mw-tide-js', 'enqueued' ) ) {
    wp_enqueue_script(
        'mw-tide-js',
        plugin_dir_url(__FILE__) . '../js/tide.js',
        array(),
        time(),
        true
    );
}

// ---------- Core weather ----------
$mwpl_current = $weather['current'] ?? array();
$mwpl_hourly  = $weather['hourly'] ?? array();
$mwpl_daily   = $weather['daily'] ?? array();

$mwpl_lat = $atts['lat'] ?? null;
$mwpl_lon = $atts['lon'] ?? null;

if ( ! $mwpl_lat || ! $mwpl_lon ) {
    return;
}

// Store raw label, escape on output.
$mwpl_label       = $atts['label'] ?? "{$mwpl_lat}, {$mwpl_lon}";
$mwpl_unit        = $atts['units'] ?? 'metric';
$mwpl_unit_symbol = ( 'imperial' === $mwpl_unit ) ? '°F' : '°C';

// 🌅 Sunrise / Sunset – use CURRENT values.
$mwpl_sunrise_ts = isset( $mwpl_current['sunrise'] ) ? (int) $mwpl_current['sunrise'] : null;
$mwpl_sunset_ts  = isset( $mwpl_current['sunset'] ) ? (int) $mwpl_current['sunset'] : null;

// 🌙 Moon
$mwpl_moon_phase = $mwpl_daily[0]['moon_phase'] ?? null;
$mwpl_moon_image = 'moon-new.png';

if ( null !== $mwpl_moon_phase ) {
    if ( 0 === $mwpl_moon_phase || 1 === $mwpl_moon_phase ) {
        $mwpl_moon_image = 'moon-new.png';
    } elseif ( $mwpl_moon_phase > 0 && $mwpl_moon_phase < 0.25 ) {
        $mwpl_moon_image = 'moon-waxing-crescent.png';
    } elseif ( 0.25 === $mwpl_moon_phase ) {
        $mwpl_moon_image = 'moon-first-quarter.png';
    } elseif ( $mwpl_moon_phase > 0.25 && $mwpl_moon_phase < 0.5 ) {
        $mwpl_moon_image = 'moon-waxing-gibbous.png';
    } elseif ( 0.5 === $mwpl_moon_phase ) {
        $mwpl_moon_image = 'moon-full.png';
    } elseif ( $mwpl_moon_phase > 0.5 && $mwpl_moon_phase < 0.75 ) {
        $mwpl_moon_image = 'moon-waning-gibbous.png';
    } elseif ( 0.75 === $mwpl_moon_phase ) {
        $mwpl_moon_image = 'moon-last-quarter.png';
    } elseif ( $mwpl_moon_phase > 0.75 && $mwpl_moon_phase < 1.0 ) {
        $mwpl_moon_image = 'moon-waning-crescent.png';
    }
}

    $mwpl_moon_image_url = MWPL_URL . 'assets/icons/moon/' . $mwpl_moon_image;

// 🌊 Marine / Tide
$mwpl_marine_lat = $atts['lat'] ?? '49.2827';
$mwpl_marine_lon = $atts['lon'] ?? '-123.1207'; // coastal-ish fallback

$mwpl_marine_url  =
    'https://marine-api.open-meteo.com/v1/marine' .
    '?latitude=' . rawurlencode( (string) $mwpl_marine_lat ) .
    '&longitude=' . rawurlencode( (string) $mwpl_marine_lon ) .
    '&hourly=wave_height,sea_surface_temperature,sea_level_height_msl' .
    '&timezone=auto';

$mwpl_marine_data = get_transient( "mwpl_mw15_marine_{$mwpl_marine_lat}_{$mwpl_marine_lon}" );
if ( ! $mwpl_marine_data ) {
    $mwpl_response    = wp_remote_get( $mwpl_marine_url );
    $mwpl_body        = wp_remote_retrieve_body( $mwpl_response );
    $mwpl_marine_data = json_decode( $mwpl_body, true );
    set_transient( "mwpl_mw15_marine_{$mwpl_marine_lat}_{$mwpl_marine_lon}", $mwpl_marine_data, 3 * HOUR_IN_SECONDS );
}

// local current index for marine timeline
$mwpl_current_index = 0;
if ( isset( $mwpl_marine_data['hourly']['time'] ) && is_array( $mwpl_marine_data['hourly']['time'] ) ) {
    $mwpl_now = time();
    foreach ( $mwpl_marine_data['hourly']['time'] as $mwpl_i => $mwpl_ts ) {
        if ( strtotime( $mwpl_ts ) > $mwpl_now ) {
            $mwpl_current_index = max( 0, (int) $mwpl_i - 1 );
            break;
        }
    }
}
?>

<div class="mw-card card-15 card-<?php echo isset( $card ) ? intval( $card ) : 15; ?>"
     data-lat="<?php echo esc_attr( $mwpl_lat ); ?>"
     data-lon="<?php echo esc_attr( $mwpl_lon ); ?>">

  <?php if ( isset( $mwpl_current['weather'][0]['icon'] ) ) : ?>
    <div class="mw15-icon-topleft">
      <i class="wi <?php echo esc_attr( mw_erikflowers_icon_map( $mwpl_current['weather'][0]['icon'] ) ); ?>"></i>
    </div>
  <?php endif; ?>

  <div class="mw15-header">
    <div class="mw15-location">
        <?php echo esc_html( $mwpl_label ); ?>
    </div>

    <div class="mw15-weather">
      <div class="mw15-temp">
        <?php
        if ( isset( $mwpl_current['temp'] ) ) {
            $mwpl_temp_display = round( $mwpl_current['temp'] ) . $mwpl_unit_symbol;
        } else {
            $mwpl_temp_display = '--';
        }
        echo esc_html( $mwpl_temp_display );
        ?>
      </div>
      <div class="mw15-hi-lo">
        <?php
        $mwpl_hi = isset( $mwpl_daily[0]['temp']['max'] ) ? round( $mwpl_daily[0]['temp']['max'] ) : null;
        $mwpl_lo = isset( $mwpl_daily[0]['temp']['min'] ) ? round( $mwpl_daily[0]['temp']['min'] ) : null;

        $mwpl_hi_lo_str = sprintf(
            'H: %s° / L: %s°',
            ( null === $mwpl_hi ? '--' : $mwpl_hi ),
            ( null === $mwpl_lo ? '--' : $mwpl_lo )
        );
        echo esc_html( $mwpl_hi_lo_str );
        ?>
      </div>
      <div class="mw15-pressure">
        <?php
        $mwpl_pressure_val = isset( $mwpl_current['pressure'] ) ? (int) $mwpl_current['pressure'] : 0;
        $mwpl_pressure_str = $mwpl_pressure_val ? $mwpl_pressure_val . ' hPa' : '-- hPa';
        echo esc_html( 'Pressure: ' . $mwpl_pressure_str );
        ?>
      </div>
    </div>
  </div>

  <div class="mw15-data-columns">
    <div class="mw15-left">
      <!-- 🌊 Tide stats -->
      <div class="mw15-tide-stats">
        <?php if ( ( $mwpl_tide_data['tide_source'] ?? '' ) === 'Open-Meteo' ) : ?>
          <div>
            Current Tide:
            <span class="mw15-current-tide">
              <?php
              $mwpl_current_tide = isset( $mwpl_marine_data['hourly']['sea_level_height_msl'][ $mwpl_current_index ] )
                  ? round( (float) $mwpl_marine_data['hourly']['sea_level_height_msl'][ $mwpl_current_index ], 2 ) . ' m'
                  : '-- m';
              echo esc_html( $mwpl_current_tide );
              ?>
            </span>
          </div>
          <div>
            Next High:
            <span class="mw15-high-time">
              <?php echo esc_html( $mwpl_tide_data['next_high']['local'] ?? '--:--' ); ?>
            </span>
            <span class="mw15-high-val">
              <?php
              $mwpl_high_val = isset( $mwpl_tide_data['next_high']['value'] )
                  ? $mwpl_tide_data['next_high']['value'] . ' m'
                  : '-- m';
              echo esc_html( $mwpl_high_val );
              ?>
            </span>
          </div>
          <div>
            Next Low:
            <span class="mw15-low-time">
              <?php echo esc_html( $mwpl_tide_data['next_low']['local'] ?? '--:--' ); ?>
            </span>
            <span class="mw15-low-val">
              <?php
              $mwpl_low_val = isset( $mwpl_tide_data['next_low']['value'] )
                  ? $mwpl_tide_data['next_low']['value'] . ' m'
                  : '-- m';
              echo esc_html( $mwpl_low_val );
              ?>
            </span>
          </div>
          <div>
            Tide Trend:
            <span class="mw15-trend">
              <?php echo esc_html( $mwpl_tide_data['trend'] ?? '--' ); ?>
            </span>
          </div>

        <?php elseif ( ( $mwpl_tide_data['tide_source'] ?? '' ) === 'WorldTides' ) : ?>
          <div>
            Current Tide:
            <span class="mw15-current-tide">
              <?php
              $mwpl_current_tide = isset( $mwpl_tide_data['current_tide'] )
                  ? $mwpl_tide_data['current_tide'] . ' m'
                  : '-- m';
              echo esc_html( $mwpl_current_tide );
              ?>
            </span>
          </div>
          <div>
            Next High:
            <span class="mw15-high-time">
              <?php
              $mwpl_high_time = isset( $mwpl_tide_data['next_high']['local'] )
                  ? gmdate( 'g:i A', strtotime( $mwpl_tide_data['next_high']['local'] ) )
                  : '--:--';
              echo esc_html( $mwpl_high_time );
              ?>
            </span>
            <span class="mw15-high-val">
              <?php
              $mwpl_high_val = isset( $mwpl_tide_data['next_high']['value'] )
                  ? $mwpl_tide_data['next_high']['value'] . ' m'
                  : '-- m';
              echo esc_html( $mwpl_high_val );
              ?>
            </span>
          </div>
          <div>
            Next Low:
            <span class="mw15-low-time">
              <?php
              $mwpl_low_time = isset( $mwpl_tide_data['next_low']['local'] )
                  ? gmdate( 'g:i A', strtotime( $mwpl_tide_data['next_low']['local'] ) )
                  : '--:--';
              echo esc_html( $mwpl_low_time );
              ?>
            </span>
            <span class="mw15-low-val">
              <?php
              $mwpl_low_val = isset( $mwpl_tide_data['next_low']['value'] )
                  ? $mwpl_tide_data['next_low']['value'] . ' m'
                  : '-- m';
              echo esc_html( $mwpl_low_val );
              ?>
            </span>
          </div>
          <div>
            Tide Trend:
            <span class="mw15-trend">
              <?php echo esc_html( $mwpl_tide_data['trend'] ?? '--' ); ?>
            </span>
          </div>
        <?php endif; ?>
      </div>

      <!-- 🌊 Marine Data -->
      <div class="mw15-marine">
        <div>
          🌡 Sea Surface Temp:
          <span class="mw15-sea-temp">
            <?php
            $mwpl_sea_temp = isset( $mwpl_marine_data['hourly']['sea_surface_temperature'][ $mwpl_current_index ] )
                ? round( (float) $mwpl_marine_data['hourly']['sea_surface_temperature'][ $mwpl_current_index ], 1 ) . ' °C'
                : '-- °C';
            echo esc_html( $mwpl_sea_temp );
            ?>
          </span>
        </div>
        <div>
          🌊 Swell Height:
          <span class="mw15-swell">
            <?php
            $mwpl_swell = isset( $mwpl_marine_data['hourly']['wave_height'][ $mwpl_current_index ] )
                ? (float) $mwpl_marine_data['hourly']['wave_height'][ $mwpl_current_index ] . ' m'
                : '-- m';
            echo esc_html( $mwpl_swell );
            ?>
          </span>
        </div>
      </div>
    </div>

    <div class="mw15-right">
      <div class="mw15-weather-details">
        <div>
          <?php
          $mwpl_hum_val = isset( $mwpl_current['humidity'] ) ? (int) $mwpl_current['humidity'] : 0;
          $mwpl_hum_str = $mwpl_hum_val ? $mwpl_hum_val . '%' : '--%';
          echo esc_html( '💧 Humidity: ' . $mwpl_hum_str );
          ?>
        </div>
        <div>
          <?php
          $mwpl_dew_str = isset( $mwpl_current['dew_point'] )
              ? round( $mwpl_current['dew_point'] ) . $mwpl_unit_symbol
              : '--' . $mwpl_unit_symbol;
          echo esc_html( '🧊 Dew Point: ' . $mwpl_dew_str );
          ?>
        </div>
        <div>
          <?php
          $mwpl_cloud_val = isset( $mwpl_current['clouds'] ) ? (int) $mwpl_current['clouds'] : 0;
          $mwpl_cloud_str = $mwpl_cloud_val ? $mwpl_cloud_val . '%' : '--%';
          echo esc_html( '☁️ Clouds: ' . $mwpl_cloud_str );
          ?>
        </div>
        <?php
        if ( isset( $mwpl_current['wind_speed'], $mwpl_current['wind_deg'] ) ) {
            $mwpl_dirs = array(
                'N','NNE','NE','ENE','E',
                'ESE','SE','SSE','S','SSW',
                'SW','WSW','W','WNW','NW','NNW',
            );
            $mwpl_deg       = (float) $mwpl_current['wind_deg'];
            $mwpl_dir_index = (int) ( ( $mwpl_deg / 22.5 ) + 0.5 ) % 16;
            $mwpl_compass   = $mwpl_dirs[ $mwpl_dir_index ];

            $mwpl_speed_mps  = (float) $mwpl_current['wind_speed'];
            $mwpl_wind_speed = ( 'imperial' === $mwpl_unit )
                ? round( $mwpl_speed_mps * 2.237, 1 ) . ' mph'
                : round( $mwpl_speed_mps * 3.6, 1 ) . ' km/h';

            echo '<div>' . esc_html( '💨 Wind: ' . $mwpl_wind_speed . ' ' . $mwpl_compass ) . '</div>';
        } else {
            echo '<div>' . esc_html( '💨 Wind: --' ) . '</div>';
        }

        if ( isset( $mwpl_current['wind_gust'] ) ) {
            $mwpl_gust_mps   = (float) $mwpl_current['wind_gust'];
            $mwpl_gust_speed = ( 'imperial' === $mwpl_unit )
                ? round( $mwpl_gust_mps * 2.237, 1 ) . ' mph'
                : round( $mwpl_gust_mps * 3.6, 1 ) . ' km/h';

            echo '<div>' . esc_html( '🌬️ Gust: ' . $mwpl_gust_speed ) . '</div>';
        } else {
            echo '<div>' . esc_html( '🌬️ Gust: --' ) . '</div>';
        }
        ?>
      </div>

      <!-- 🌅 Sunrise/Sunset -->
      <?php if ( $mwpl_sunrise_ts || $mwpl_sunset_ts ) : ?>
        <div class="mw15-sun-block">
          <?php if ( $mwpl_sunrise_ts ) : ?>
            <div class="mw15-sunrise">
              <i class="wi wi-sunrise"></i>
              <span class="local-time"
                    data-utc="<?php echo esc_attr( $mwpl_sunrise_ts ); ?>">
                <?php echo esc_html( date_i18n( 'H:i', $mwpl_sunrise_ts ) ); ?>
              </span>
            </div>
          <?php endif; ?>

          <?php if ( $mwpl_sunset_ts ) : ?>
            <div class="mw15-sunset">
              <i class="wi wi-sunset"></i>
              <span class="local-time"
                    data-utc="<?php echo esc_attr( $mwpl_sunset_ts ); ?>">
                <?php echo esc_html( date_i18n( 'H:i', $mwpl_sunset_ts ) ); ?>
              </span>
            </div>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- 🧭 Tide dial -->
  <div class="mw15-dial-wrapper">
    <img
      src="<?php echo esc_url( plugin_dir_url(__FILE__) . '../assets/svg/white-dial.svg' ); ?>"
      alt="<?php echo esc_attr__( 'Tide Dial', 'multiweather' ); ?>"
      class="mw15-dial"
    />

    <div class="mw15-dial-hand"></div>

    <div class="mw15-dial-moon">
      <img src="<?php echo esc_url( $mwpl_moon_image_url ); ?>"
           alt="<?php echo esc_attr__( 'Moon Phase', 'multiweather' ); ?>"
           class="mw15-moon-img" />
    </div>

    <div class="mw15-dial-time-container">
      <?php
      $mwpl_tz = function_exists( 'mwpl_get_location_time' )
          ? mwpl_get_location_time( $mwpl_lat, $mwpl_lon )
          : null;
      ?>
      <div class="mw-date-wrap">
        <div class="mw-date">
            <?php echo esc_html( mwpl_gmdate( 'l, j F' ) ); ?>
        </div>
        <div class="mw-local-time"
             data-timezone="<?php echo esc_attr( $mwpl_tz['name'] ?? 'UTC' ); ?>">
          <span class="mw-live-time">--:--</span>
        </div>
      </div>
    </div>
  </div>
</div>

<?php if ( ! empty( $mwpl_tide_data ) && isset( $mwpl_tide_data['percent_between'] ) ) : ?>
<?php
// Provide tide dial payload via WP enqueued script (no inline script tags in templates).
wp_enqueue_script( 'mwpl-front' );
$mwpl_tide_payload = array(
	'selector'            => '.mw-card.card-15',
	'dialClass'           => '.mw15-dial-hand',
	'heightClass'         => '.mw15-current-tide',
	'trendClass'          => '.mw15-trend',
	'percentBetweenTides' => $mwpl_tide_data['percent_between'] ?? null,
	'trend'               => $mwpl_tide_data['trend'] ?? null,
	'currentHeight'       => $mwpl_tide_data['current_tide'] ?? null,
);
$mwpl_inline = 'window.mwTideData = window.mwTideData || []; window.mwTideData.push(' . wp_json_encode( $mwpl_tide_payload ) . ');';
wp_add_inline_script( 'mwpl-front', $mwpl_inline, 'after' );
?>
<?php endif; ?>
