<?php

namespace GravityKit\GravityCalendar\Gutenberg\Blocks\Block;

use GV_Extension_Calendar_Feed;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Calendar copy button block.
 *
 * @since 2.0
 */
class Buttons extends Block {

	const BLOCK_NAME = 'buttons';

	/**
	 * Generates `[gv_calendar_export_button]` and/or `[gv_calendar_copy_button]` shortcodes.
	 *
	 * @since 2.0
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string $output Rendered shortcode.
	 */
	static function render( $attributes = [] ): string {
		$feed = GV_Extension_Calendar_Feed::get_instance()->get_feed( $attributes['att_id'] ?? 0 );

		if ( ! $feed ) {
			return esc_html__( 'Calendar feed does not exist.', 'gk-gravitycalendar' );
		}

		$rendered_shortcodes = [];

		if ( ! empty( $attributes['att_export'] ) ) {
			$shortcode_attributes = array(
				'id'     => (int) rgar( $attributes, 'att_id' ),
				'text'   => rgar( $attributes, 'att_export_text' ),
				'webcal' => rgar( $attributes, 'att_export_webcal' ),
				'target' => rgar( $attributes, 'att_export_target_new_window' ),
				'secret' => rgar( $attributes, 'att_secret' ),
			);

			if ( ! empty( $shortcode_attributes['target'] ) ) {
				$shortcode_attributes['target'] = '_blank';
			}

			$rendered_shortcodes[] = gv_calendar_export_button_shortcode_handler( $shortcode_attributes );
		}

		if ( ! empty( $attributes['att_copy'] ) &&
		     ( isset( $feed['meta']['enable-ics-feed'] ) || (int) ( $feed['meta']['enable-ics-feed'] ) === 1 )
		) {
			$shortcode_attributes = array(
				'id'     => (int) rgar( $attributes, 'att_id' ),
				'text'   => rgar( $attributes, 'att_copy_text' ),
				'webcal' => rgar( $attributes, 'att_copy_webcal' ),
				'secret' => rgar( $attributes, 'att_secret' ),
			);

			$rendered_shortcodes[] = gv_calendar_copy_button_shortcode_handler( $shortcode_attributes );
		}

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

		$style = 'assets/css/gk-gravitycalendar-blocks.css';

		wp_enqueue_style( 'gk-gravitycalendar-blocks', GV_CALENDAR_URL . $style, [], filemtime( GV_CALENDAR_PATH . $style ) );

		$output = implode( '', $rendered_shortcodes );

		// Make button render in Gutenberg editor as it would in the frontend.
		$output = str_replace( 'class="button', 'class="button wp-block-button__link', $output );

		$block_class = rgar( $attributes, 'className', '' );

		return sprintf( '<div class="gv-calendar-buttons %s">%s</div>', esc_attr( $block_class ), $output );
	}
}
