<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Service\Models;

use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Exceptions\InvalidArgumentException;
use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Exceptions\InvalidBlockIdException;

class NewsletterBlockSettings {

	protected int     $postId;
	protected ?string $blockId;

	protected $blockObject = NULL;

	const BLOCK_NAME = 'sb-churchtools/newsletter';

	public function __construct(int $postId, $blockId = NULL) {
		$this->postId  = $postId;
		$this->blockId = $blockId;
	}

	protected function initBlockObjectOnce() {

		if ($this->blockObject !== NULL)
			return $this->blockObject;

		// Default Inititalisation
		$this->blockObject = FALSE;

		$post = get_post($this->postId);

		if (!has_blocks($post)) {
			// The Token does not match against this post or block-id
			throw new InvalidArgumentException('Invalid token');
		}

		$blocks           = parse_blocks($post->post_content);
		$newsletterBlocks = $this->findBlocksByName($blocks, self::BLOCK_NAME);

		if (!empty($this->blockId)) {
			foreach ($newsletterBlocks as $block) {
				if (isset($block['attrs']['uid']) && $block['attrs']['uid'] === $this->blockId) {
					$this->blockObject = $block;
					return $this->blockObject;
				}
			}
		} else if (count($blocks) > 0) {
			// Nimm den erstbesten Block
			$this->blockObject = array_pop($newsletterBlocks);
		}

		if (empty($this->blockObject)) {
			throw new InvalidBlockIdException(__('Security Exception: No Block-ID Match for this Newsletter-Block', 'sb-churchtools-grouphomepage'));
		}

		return $this->blockObject;

	}

	protected function findBlocksByName(array $blocks, string $name): array {

		$result = [];

		foreach ($blocks as $block) {

			if (isset($block['blockName']) && $block['blockName'] === $name) {
				$result[] = $block;
			}

			if (is_array($block['innerBlocks'])) {
				$result = array_merge($this->findBlocksByName($block['innerBlocks'], $name), $result);
			}

		}

		return $result;

	}


	protected function getBlockAttribute($attributeName, $jsonDecode = FALSE, $default = FALSE) {
		$block    = $this->initBlockObjectOnce();
		$response = $default;

		if ($block !== FALSE) {

			if (isset($block['attrs'][$attributeName])) {
				$response = $block['attrs'][$attributeName];

				if ($jsonDecode === TRUE) {
					$response = json_decode($response, TRUE, 16);
				}

			}

		}

		return $response;

	}


	public function getGroups(): array {
		$this->initBlockObjectOnce();
		return $this->getBlockAttribute('newsletter_group_ids', TRUE, []);
	}

	public function getGroupsIds(): array {
		$groups   = $this->getGroups();
		$response = [];

		foreach ($groups as $group) {
			if (is_array($group) && isset($group['value'])) {
				$response[] = (int)$group['value'];
			}
		}

		return $response;
	}


	public function getDefaultGroupRoleId() {
		$this->initBlockObjectOnce();
		$obj = $this->getBlockAttribute('newsletter_group_role_default', TRUE, []);

		if (is_array($obj) && isset($obj['value'])) {
			return (int)$obj['value'];
		} else {
			return NULL;
		}

	}


	/**
	 * @return bool
	 */
	public function isMembershipWithoutConfirmation() {
		return $this->getBlockAttribute('newsletter_membership_without_confirmation', FALSE, 'yes') === 'yes';
	}


	public function getGroupRolesSelected(): array {
		$this->initBlockObjectOnce();
		return $this->getBlockAttribute('newsletter_group_roles_selected', TRUE, []);
	}

	public function getGroupRoleIdsSelected(): array {
		$gRoles   = $this->getGroupRolesSelected();
		$response = [];

		foreach ($gRoles as $role) {
			if (is_array($role) && isset($role['value'])) {
				$response[] = (int)$role['value'];
			}
		}

		return $response;
	}


	public function getThemecolor() {
		return $this->getBlockAttribute('themecolor', FALSE, '#0696D7');
	}

	public function getLogoPath() {
		return $this->getBlockAttribute('logo_path', FALSE, 'https://teambb.church.tools/?q=public/filedownload&id=918&filename=19c6a6d59926517e79f05ccbf30d5f76ec8d773e971476503cfe1036e830811f');
	}

	public function getPostId() {
		return $this->postId;
	}

	public function getBlockId() {
		return $this->getBlockAttribute('uid', FALSE, NULL);
	}

	public function getVerifyMailText() {
		return $this->getBlockAttribute('verify_mail_body', FALSE, 'Bitte bestätige, mit dem nachfolgenden Link, dass du der Eigentümer der E-Mailadresse {{ email }} bist.');
	}

	public function getVerifyMailSubject() {
		return $this->getBlockAttribute('verify_mail_subject', FALSE, 'Newsletter Bestätigungsmail');
	}

	public function getVerifyMailSender() {
		return $this->getBlockAttribute('verify_mail_sender', FALSE, 'No Reply');
	}


}
