<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Controller;

use StevenBuehner\sbChurchtoolsGrouphomepage\Always\MyContainer;
use StevenBuehner\sbChurchtoolsGrouphomepage\Controller\AbstractController;
use StevenBuehner\sbChurchtoolsGrouphomepage\Helper\ArrayHelper;
use StevenBuehner\sbChurchtoolsGrouphomepage\Helper\FilteredMultiSelectControlHelper;
use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Models\Event;

class AppointmentListController extends AbstractController {


	protected function init(): void {

		$this->setUpHooks(
			FALSE,
			FALSE,
			FALSE,
			TRUE,
			FALSE,
			FALSE,
			TRUE
		);

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

	}


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

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

	}


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

		if (is_admin()) {
			// Nur mit Caching rendern, wenn es im Frontend angezeigt wird
			return $content;
		}

		try {
			/** @var Event $event */
			$calService = MyContainer::getCtCalendarService();

			// Parse Calendar
			$calendarIds = FilteredMultiSelectControlHelper::parseStrValueToArray($attributes['calendar']);

			$events = $calService->getFilteredEventsFromMultipleCalendars($calendarIds, absint($attributes['max_count']), $attributes['title_reg_exp'], $attributes['description_reg_exp']);

		} catch (\Exception $e) {
			return $content;
		}

		$componentProps          = ArrayHelper::onlyKeys($attributes, ['className', 'color_override', 'bg_color_override', 'design', 'title_format', 'location_format', 'description_format', 'description_clamp', 'headline', 'link_label', 'text_alignment', 'size', 'horizontal_margin', 'show_image']);
		$componentProps['class'] = 'sb-ct-appointmentlist';
		$componentProps['data']  = $events;


		return $this->modifyHtmlElement($content, $componentProps);

	}


}
