<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Controller;

use StevenBuehner\sbChurchtoolsGrouphomepage\Always\MyContainer;
use StevenBuehner\sbChurchtoolsGrouphomepage\Controller\AbstractController;
use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Exceptions\InvalidArgumentException;


/**
 * The public-facing functionality of the plugin.
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    sbChurchtoolsGrouphomepage
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @author     Steven Buehner <buehner@me.com>
 */
class EventMetaDataFrontendController extends AbstractController {

	function init(): void {
		$this->setUpHooks(
			FALSE,
			FALSE,
			FALSE,
			TRUE,
			FALSE,
			TRUE,
			TRUE
		);

		$this->domain = 'sb-ct-blocks';
	}


	public function registerGutenbergBlocksAndCategories() {
		parent::registerGutenbergBlocksAndCategories();

		$this->registerBlockJson(__DIR__ . '/../../build/EventMetaData', TRUE, FALSE);

	}

	public function renderHtml($attributes = [], $content = '') {

		if (is_admin()) {
			// Only render in frontend!
			return $content;
		}

		try {
			$responseObjects = $this->transformQueryToJsonLd($attributes);
			return '<script type="application/ld+json">' . json_encode($responseObjects, JSON_HEX_APOS | JSON_UNESCAPED_UNICODE) . '</script>';
		} catch (InvalidArgumentException $e) {
		}

		// Fail silently
		return $content;
	}

	public function renderAsRest(\WP_REST_Request $request, $data = '') {
		$attributes = $request['attributes'];
		return $this->transformQueryToJsonLd($attributes);
	}

	/**
	 * @param array $attributes
	 * @return array
	 * @throws InvalidArgumentException
	 */
	protected function transformQueryToJsonLd($attributes = []) {
		$calService = MyContainer::getCtCalendarService();

		$events = $calService->getFilteredEventsFromCalendar(
			$attributes['event_calendar'],
			$attributes['event_max_count'],
			$attributes['event_title_regexp'],
			$attributes['event_description_regexp']
		);

		$responseObjects = [];
		$additionalData  = [
			'eventStatus' => $attributes['event_status']
		];

		$orgName   = trim($attributes['org_name']);
		$orgUrl    = trim($attributes['org_url']);
		$organizer = [];
		if (!empty($orgName)) {
			$organizer['name'] = $orgName;
		}
		if (!empty($orgUrl)) {
			$organizer['url'] = $orgUrl;
		}

		if (count($organizer) > 0) {
			$additionalData['organizer'] = $organizer;
		}

		$eventAttendenceMode = trim($attributes['event_attendence_mode']);
		if (!empty($eventAttendenceMode)) {
			$additionalData['eventAttendanceMode'] = $eventAttendenceMode;
		}

		foreach ($events as $e) {

			if ($attributes['event_trim_title']) {
				$e->setTitle(trim($e->getTitle(), "\t\n\r\0\x0B,_- "));
			}
			$e->setTitle(
				str_replace(
					['[title]', '[description]', '[location]'],
					[$e->getTitle(), $e->getDescription(), $e->getLocation()],
					$attributes['event_name'])
			);

			if ($attributes['event_trim_description']) {
				$e->setDescription(trim($e->getDescription(), "\t\n\r\0\x0B,_- "));
			}
			$e->setDescription(
				str_replace(
					['[title]', '[description]', '[location]'],
					[$e->getTitle(), $e->getDescription(), $e->getLocation()],
					$attributes['event_description'])
			);

			$e->setLocation(
				str_replace(
					['[title]', '[description]', '[location]'],
					[$e->getTitle(), $e->getDescription(), $e->getLocation()],
					$attributes['event_location'])
			);

			$e->setUrl(
				str_replace(
					['[url]'],
					[$e->getUrl()],
					$attributes['event_url'])
			);
			$e->setUrl(trim($e->getUrl(), "\t\n\r\0\x0B,_- "));

			$responseObjects[] = $calService->transformEventToJsonoLd($e, $additionalData);

		}

		return $responseObjects;

	}

	public function registerRestRequests() {
		parent::registerRestRequests();

		register_rest_route('churchtools/event-meta-data/v1', '/rendered', [
			'methods'             => \WP_REST_Server::READABLE,
			'callback'            => [$this, 'renderAsRest'],
			'args'                => array(
				'attributes' => [
					'description'       => 'Rendering Attributes',
					'type'              => 'string',
					'sanitize_callback' => function ($param) {
						return $this->registeredBlocks[0]->prepare_attributes_for_render($param);
					},
					'required'          => TRUE
				]
			),
			'permission_callback' => function () {
				// https://wordpress.org/support/article/roles-and-capabilities/#edit_posts
				return current_user_can('edit_posts') && count($this->registeredBlocks) === 1;
			},
		]);
	}

}
