<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Controller;

use StevenBuehner\sbChurchtoolsGrouphomepage\Vendor\GuzzleHttp\Exception\RequestException;
use StevenBuehner\ChurchTools\ApiException;
use StevenBuehner\sbChurchtoolsGrouphomepage\Always\MyContainer;
use WP_REST_Request;

class GlobalRestController extends AbstractController {

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

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

		if (current_user_can('edit_posts')) {
			register_rest_route('churchtools/calendar/v1', '/events', [
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => [$this, 'action_show_filterd_events'],
				'args'                => array(
					'calendar'          => [
						'description'       => 'ChurchTools Calendar-ID or comma-separated list of calendar IDs',
						'type'              => 'string',
						'validate_callback' => function ($param, $request, $key) {
							return preg_match('~^([1-9][0-9,]*)+$~', $param) === 1 || $param === '';
						},
						'sanitize_callback' => function ($param) {
							// Ein Array mit Integers
							$values = preg_split('~,~', $param);

							if ($values === FALSE) {
								$values = [$param];
							}

							foreach ($values as $key => $v) {
								$values[$key] = absint($v);
							}

							return $values;
						},
						'required'          => TRUE
					],
					'descriptionRegExp' => [
						'description'       => 'Regular Expression for filtering the event\'s description',
						'type'              => 'string',
						'validate_callback' => '__return_true',
						'required'          => FALSE
					],
					'titleRegExp'       => [
						'description'       => 'Regular expression for filtering event\'s title',
						'type'              => 'string',
						'validate_callback' => '__return_true',
						'required'          => FALSE
					],
					'maxCount'          => [
						'description'       => 'Max Events to return',
						'type'              => 'number',
						'default'           => 5,
						'sanitize_callback' => function ($param) {
							return absint($param);
						},
						'validate_callback' => function ($param, $request, $key) {
							return is_numeric($param) && $param > 0 && $param <= 50;
						},
						'required'          => FALSE
					]
				),
				'permission_callback' => function () {
					// https://wordpress.org/support/article/roles-and-capabilities/#edit_posts
					return current_user_can('edit_posts');
				},
			]);
		}


		if (current_user_can('edit_posts')) {
			register_rest_route('churchtools/calendar/v1', '/calendars', [
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => [$this, 'action_show_available_calendars'],
				'args'                => [],
				'permission_callback' => function () {
					// https://wordpress.org/support/article/roles-and-capabilities/#edit_posts
					return current_user_can('edit_posts');
				},
			]);
		}


		if (current_user_can('edit_posts')) {
			register_rest_route('churchtools/groups/v1', '/all', [
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => [$this, 'action_get_all_groups'],
				'args'                => [],
				'permission_callback' => function ($request) {
					// Nur eingeloggte Nutzer
					// Funktioniert nur mit mitgesendeter Wordpress nonce
					return is_user_logged_in() && current_user_can('edit_posts');
				},
			]);
		}

	}

	public function action_show_filterd_events(WP_REST_Request $request) {

		$calendarIds       = $request->get_param('calendar');
		$titleRegExp       = $request->get_param('titleRegExp');
		$descriptionRegExp = $request->get_param('descriptionRegExp');
		$maxCount          = $request->get_param('maxCount');

		$calService = MyContainer::getCtCalendarService();
		$clearCache = $this->debugMode === is_admin(); // Für eingeloggte Benutzer
		$events     = $calService->getFilteredEventsFromMultipleCalendars($calendarIds, $maxCount, $titleRegExp, $descriptionRegExp, NULL, $clearCache);

		return $events;

	}

	public function action_show_available_calendars() {

		try {
			$calendars = MyContainer::getCtCalendarService()->getChurchToolsCalendarsCached();
			$campuses  = MyContainer::getCtCampusService()->getChurchToolsCampusesCached();
		} catch (ApiException $e) {
			$response = [
				'success' => FALSE,
				'error'   => __('Not able to load Calendars', $this->domain) . ' (' . substr($e->getMessage(), 0, 100) . ')',
			];
			return $response;
		} catch (RequestException $e) {
			$response = [
				'success' => FALSE,
				'error'   => __('Not able to load Calendars - Churchtools might not be configured in the backend yet', $this->domain)
			];
			return $response;
		}

		// Transform Data
		$responseData = [];
		foreach ($calendars as $cal) {

			$r = [
				'id'       => $cal->getId(),
				'color'    => $cal->getColor(),
				'name'     => $cal->getName(),
				'sortKey'  => $cal->getSortKey(),
				'isPublic' => $cal->getIsPublic(),
				'campus'   => NULL
			];

			foreach ($campuses as $campus) {
				if ($campus->getId() === $cal->getCampusId()) {
					$r['campus'] = $campus->getName();
				}
			}

			$responseData[] = $r;

		}

		return [
			'success' => TRUE,
			'data'    => $responseData
		];

	}


	public function action_get_all_groups(\WP_REST_Request $request) {

		$result = [];

		try {
			$result['success'] = TRUE;
			$result['data']    = MyContainer::getCtGroupService()->getAllGroups();
		} catch (\Exception $e) {
			$result['success'] = FALSE;
			$result['error']   = __('Not able to load groups from ChurchTools', $this->domain);
		}

		return $result;

	}


}
