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

namespace Nisje\BlockLibrary\CardTwitter;

use Abraham\TwitterOAuth\TwitterOAuth;

/**
 * Check if twitter settings is set.
 */
function has_settings() {
	return (
		defined( 'NISJE_TWITTER_CONSUMER_KEY' ) && ! empty( NISJE_TWITTER_CONSUMER_KEY ) &&
		defined( 'NISJE_TWITTER_CONSUMER_SECRET' ) && ! empty( NISJE_TWITTER_CONSUMER_SECRET ) &&
		defined( 'NISJE_TWITTER_ACCESS_TOKEN' ) && ! empty( NISJE_TWITTER_ACCESS_TOKEN ) &&
		defined( 'NISJE_TWITTER_ACCESS_SECRET' ) && ! empty( NISJE_TWITTER_ACCESS_SECRET )
	);
}

/**
 * Get tweets
 *
 * @param string $username Username to get tweets for.
 */
function get_tweets( $username ) {
	// If cached tweets for this username, return them.
	$data = get_transient( 'tweets_from_' . $username );
	if ( $data ) {
		return $data;
	}

	$connection = new TwitterOAuth(
		NISJE_TWITTER_CONSUMER_KEY,
		NISJE_TWITTER_CONSUMER_SECRET,
		NISJE_TWITTER_ACCESS_TOKEN,
		NISJE_TWITTER_ACCESS_SECRET
	);

	$data = $connection->get( 'statuses/user_timeline', [
		'screen_name' => $username,
		'count'       => 1,
	] );

	if ( $data && ! empty( $data ) ) {
		set_transient( 'tweets_' . $username, $data, 3 * 60 );
	}

	return $data;
}

/**
 * Renders the `nisje/card-twitter` block on server
 *
 * @param array $attributes The block attributes.
 *
 * @return string Returns the post content.
 */
function render_block( array $attributes ): string {
	$username = $attributes['username'] ?? get_option( 'nisje_twitter_username', '' );

	if ( empty( $username ) ) {
		return '';
	}

	$content = [];

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

	if ( isset( $attributes['backgroundColor'] ) ) {
		$content['className'] .= " has-{$attributes['backgroundColor']}-background-color";
	} elseif ( isset( $attributes['customBackgroundColor'] ) ) {
		$content['bg'] = $attributes['customBackgroundColor'];
	}

	$tweets = get_tweets( $username );

	if ( ! $tweets || empty( $tweets ) ) {
		return '';
	}

	$tweet = $tweets[0];

	$content['tweet'] = [
		'text'     => $tweet->text,
		'name'     => $tweet->user->name,
		'date'     => $tweet->created_at,
		'username' => $tweet->user->screen_name,
	];

	return \wp_json_encode( $content );
}

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