<?php

defined( 'ABSPATH' ) || exit;

/**
 * Fetch + cache weather from OpenWeatherMap.
 *
 * @param float|string $lat  Latitude.
 * @param float|string $lon  Longitude.
 * @param string       $unit Units: 'metric' or 'imperial'.
 *
 * @return array|false
 */
function mwpl_get_weather( $lat, $lon, $unit = 'metric' ) {
	// Build a cache key unique to lat/lon/unit.
	$cache_key = 'mwpl_' . md5( "{$lat}_{$lon}_{$unit}" );

	// Try cache first.
	$weather = get_transient( $cache_key );
	if ( false !== $weather ) {
		return $weather;
	}

	// Require OpenWeatherMap API key.
	$api_key = get_option( 'multiweather_api_key', '' );
	if ( empty( $api_key ) ) {
		return false;
	}

	// Admin-controlled exclusions.
	$excluded_parts = get_option( 'multiweather_excluded_parts' );
	if ( ! is_array( $excluded_parts ) ) {
		// Default fallback if option is missing or not an array.
		$excluded_parts = array( 'minutely' );
	}

	$exclude = implode( ',', array_map( 'trim', $excluded_parts ) );

	// "exclude" here is an HTTP query param for OpenWeatherMap, not a WP_Query arg.
	$url = "https://api.openweathermap.org/data/3.0/onecall?lat={$lat}&lon={$lon}&units={$unit}&exclude={$exclude}&appid={$api_key}"; // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude

	$response = wp_remote_get( $url );
	if ( is_wp_error( $response ) ) {
		return false;
	}

	$data = json_decode( wp_remote_retrieve_body( $response ), true );
	if ( ! isset( $data['current'] ) ) {
		return false;
	}

	// Cache TTL based on setting (minutes -> seconds).
	$interval = (int) get_option( 'multiweather_cache_interval', 180 );
	$ttl      = ( $interval > 0 ) ? ( $interval * 60 ) : 10800; // Default 3 hours.

	set_transient( $cache_key, $data, $ttl );

	// Track daily API usage.
	$current_count = (int) get_option( 'multiweather_daily_call_count', 0 );
	update_option( 'multiweather_daily_call_count', $current_count + 1 );

	return $data;
}
