<?php
/**
 * Server-side rendering of the `nisje/card-rs-stats` block.
 *
 * @package Nisje
 */

namespace Nisje\RS\BlockLibrary\CardStats;

/**
 * Renders the `nisje/card-rs-stats` block on server
 *
 * @param array $attributes The block attributes.
 *
 * @return string Returns the post content with links added.
 */
function render_block( array $attributes ): string {
	$cache_key = 'nisje_rs_stat_cache';

	$content = \get_transient( 'nisje_rs_stat_cache' );
	if ( false === $content ) {
		$content = [
			'stats'    => [],
			'featured' => 0,
		];

		$response = \wp_remote_get( 'https://www.redningsselskapet.no/wp-json/rs/v1/statistics/intranett?secret=9wvU4aEUomw0ZartsuCdlb3NdblvHwUW' );
		if ( ! \is_wp_error( $response ) ) {
			$values = json_decode( \wp_remote_retrieve_body( $response ), true );

			if ( isset( $values['success'], $values['data'] ) && $values['success'] ) {
				$defaults = [
					'persons_assisted_current_year' => \esc_html__( 'persons assisted', 'nisje-rs' ),
					'vessels_salvaged_current_year' => \esc_html__( 'vessels salvaged', 'nisje-rs' ),
					'members'                       => \esc_html__( 'members', 'nisje-rs' ),
				];

				foreach ( $defaults as $key => $translation ) {
					if ( isset( $values['data'][ $key ] ) ) {
						// translators: %1$d stat number %2$s stat text.
						$content['stats'][] = sprintf( \esc_html_x( '%1$d %2$s', 'stat number and string', 'nisje-rs' ), \absint( $values['data'][ $key ] ), \esc_html( $translation ) );
					}
				}
			}

			if ( isset( $values['data']['lives_saved_current_year'] ) ) {
				$content['featured'] = \absint( $values['data']['lives_saved_current_year'] );
			}

			$content['year'] = gmdate( 'Y' );
			$content['type'] = 'rs-stats-card';

			\set_transient( $cache_key, $content, HOUR_IN_SECONDS );
		}
	}

	$content['className'] = "has-{$attributes['columns']}-columns has-{$attributes['rows']}-rows";

	return \wp_json_encode( $content );
}

/**
 * Registers the `nisje/card-rs-stats` block on server.
 */
if ( function_exists( 'nisje_register_block' ) ) {
	\nisje_register_block( __DIR__, [
		'render_callback' => __NAMESPACE__ . '\\render_block',
	] );
}
