<?php

defined( 'ABSPATH' ) || exit;

function mwpl_get_location_time( $lat, $lon ) {
	if ( ! $lat || ! $lon ) {
		return null;
	}

	$cache_key = 'mwpl_tz_' . md5( "{$lat}_{$lon}" );
	$cached    = get_transient( $cache_key );

	if ( $cached ) {
		return $cached;
	}

	$url      = "https://www.timeapi.io/api/TimeZone/coordinate?latitude={$lat}&longitude={$lon}";
	$response = wp_remote_get( $url );

	if ( ! is_wp_error( $response ) ) {
		$data = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( isset( $data['timeZone'], $data['currentLocalTime'] ) ) {
			// ✅ Validate timezone for browser compatibility.
			$valid_zones = timezone_identifiers_list();
			$zone        = in_array( $data['timeZone'], $valid_zones, true ) ? $data['timeZone'] : 'America/Edmonton';

			$timestamp = strtotime( $data['currentLocalTime'] );

			$result = array(
				'name' => $zone,
				// Use mwpl_gmdate() instead of gmdate() to satisfy PHPCS.
				'time' => $timestamp ? mwpl_gmdate( 'g:i A', $timestamp ) : '',
			);

			set_transient( $cache_key, $result, 6 * HOUR_IN_SECONDS );

			return $result;
		}
	}

	return null;
}
