<?php

use craft\base\Element;
use craft\elements\User;
use craft\elements\Entry;
use craft\elements\MatrixBlock;
use craft\elements\Category;
use craft\elements\GlobalSet;
use craft\helpers\App;
use craft\helpers\UrlHelper;
use craft\helpers\ElementHelper;
use craft\mail\Message;

use verbb\supertable\SuperTable;
use verbb\supertable\elements\SuperTableBlockElement;

use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;

/**
 * @param string							$html
 * @param string							$subject
 * @param array|string|\craft\elements\User $mail
 *
 * @return bool
 */
function sendMail (string $html, string $subject, $mail): bool
{
	return Craft::$app
		->getMailer()
		->compose()
		->setTo($mail)
		->setSubject($subject)
		->setHtmlBody($html)
		->send();
}

function parseCraftImage ($image, $transform = null) {
	$image = $image->one();
	if ($image) {
		return [
			"w" => intval($image->getWidth($transform)),
			"h" => intval($image->getHeight($transform)),
			"u" => $image->getUrl($transform),
			"t" => $image->title
		];
	}
	return null;
}

function parseCraftLinkField ($link, $params = []) {
	if ($link->getCustomText()) {
		$params['text'] = $link->getCustomText();
	}
	return $link ? [
		'html' => $link->getLink($params),
		'link' => $link,
		'customText' => $link->getCustomText(),
		'url' => $link->getUrl(),
		'type' => $link->getType(),
	] : null;
}

function parseUser ($user) {

	return [
		'id' => $user['id'],
		'username' => $user['username']
	];

}

return [
	'endpoints' => [

		'api/v1/token' => function () {

			$result = [
				'csrfTokenValue' => Craft::$app->getRequest()->csrfToken
			];
			die (json_encode($result));

		},

		'api/v1/logout' => function () {

			$request = Craft::$app->request;

			if (!$request->isPost) {
				throw new BadRequestHttpException();
			}

			if (
				App::env('CRAFT_ENABLE_CSRF_PROTECTION') !== false &&
				(!$request->getBodyParam('CRAFT_CSRF_TOKEN') || !$request->validateCsrfToken($request->getBodyParam('CRAFT_CSRF_TOKEN')))
			) {
				throw new BadRequestHttpException();
			}

			$currentUser = Craft::$app->getUser()->getIdentity();
			if (!$currentUser) {
				throw new ForbiddenHttpException();
			}

			Craft::$app->getUser()->logout();

			header('Content-Type: application/json; charset=utf-8');
			die (json_encode([
				'success' => true,
				'csrfTokenValue' => $request->getCsrfToken(),
			]));

		},

		'api/v1/me' => function () {

			$currentUser = Craft::$app->getUser()->getIdentity();
			if (!$currentUser) {
				throw new ForbiddenHttpException('');
			}

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => User::class,
				'criteria' => [
					'id' => $currentUser->id,
					'groupId' => getenv('HJHS_APP_GROUP_ID')
				],
				'one' => true,
				'transformer' => function(User $user) {
					return [
						'id' => $user->id,
						'username' => $user->username,
						'firstName' => $user->firstName,
						'lastName' => $user->lastName,
						'email' => $user->email,
						// 'fields' => [
						// 	'dontShowPostLoginModal' => (int) $user->dontShowPostLoginModal
						// ],
						'dontShowPostLoginModal' => $user->dontShowPostLoginModal,
						'token' => Craft::$app->getRequest()->csrfToken,
						'lastLoginDate' => $user->lastLoginDate,
					];
				}
			];
		},

		'json/v1/home' => function () {

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => Entry::class,
				'criteria' => [
					'section' => 'home'
				],
				'one' => true,
				'transformer' => function (Entry $entry) {

					$postLogin = null;
					$globalSet = \Craft::$app->getGlobals()->getSetByHandle('modals');
					if ($globalSet) {
						$postLogin = [
							'postLoginHeading' => $globalSet->postLoginHeading,
							'postLoginBody' => $globalSet->postLoginBody,
							'postLoginBoxBody' => $globalSet->postLoginBoxBody,
							'postLoginDontShowModalLabel' => $globalSet->postLoginDontShowModalLabel,
							'postLoginDoneButtonLabel' => $globalSet->postLoginDoneButtonLabel,
						];
					}

					return [
						'id' => intval($entry->id),
						'slug' => $entry->slug,
						'title' => $entry->title,
						'introHeading' => $entry->introHeading,
						'introBody' => $entry->introBody,
						'signUpBody' => $entry->signUpBody,
						'postLogin' => $postLogin
					];
				}
			];
		},

		'json/v1/privacy-policy' => function () {

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => Entry::class,
				'criteria' => [
					'section' => 'privacyPolicy'
				],
				'one' => true,
				'transformer' => function (Entry $entry) {

					return [
						'id' => intval($entry->id),
						'slug' => $entry->slug,
						'title' => $entry->title,
						'url' => $entry->url,
						'body' => $entry->body,
					];
				}
			];
		},

		'json/v1/terms-conditions' => function () {

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => Entry::class,
				'criteria' => [
					'section' => 'termsConditions'
				],
				'one' => true,
				'transformer' => function (Entry $entry) {

					return [
						'id' => intval($entry->id),
						'slug' => $entry->slug,
						'title' => $entry->title,
						'url' => $entry->url,
						'body' => $entry->body,
					];
				}
			];
		},

		'json/v1/modals' => function () {

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => GlobalSet::class,
				'criteria' => [
					'handle' => 'modals'
				],
				'one' => true,
				'transformer' => function (GlobalSet $globalSet) {

					return [
						'postLoginHeading' => $globalSet->postLoginHeading,
						'postLoginBody' => $globalSet->postLoginBody,
						'postLoginBoxBody' => $globalSet->postLoginBoxBody,
						'postLoginDontShowModalLabel' => $globalSet->postLoginDontShowModalLabel,
						'postLoginDoneButtonLabel' => $globalSet->postLoginDoneButtonLabel,

						'recentJointOrMuscleBleedsLinkLabel' => $globalSet->recentJointOrMuscleBleedsLinkLabel,
						'recentJointOrMuscleBleedsHeading' => $globalSet->recentJointOrMuscleBleedsHeading,
						'recentJointOrMuscleBleedsBody' => $globalSet->recentJointOrMuscleBleedsBody,

						'missingScoresHeading' => $globalSet->missingScoresHeading,
						'missingScoresBody' => $globalSet->missingScoresBody,

						'helpHeading' => $globalSet->helpHeading,
						'helpBody' => $globalSet->helpBody,

						// 'minimumAgeNotMetHeading' => $globalSet->minimumAgeNotMetHeading,
						// 'minimumAgeNotMetBody' => $globalSet->minimumAgeNotMetBody,
					];
				}
			];
		},

		'json/v1/info' => function () {

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => GlobalSet::class,
				'criteria' => [
					'handle' => 'info'
				],
				'one' => true,
				'transformer' => function (GlobalSet $globalSet) {

					return [
						'swelling' => [
							'enabled' => $globalSet->swellingEnabled,
							'heading' => $globalSet->swellingHeading,
							'body' => $globalSet->swellingBody,
							'notes' => [
								'base' => $globalSet->swellingBaseNotes,
								'landmarks' => $globalSet->swellingLandmarksNotes,
								'location' => $globalSet->swellingLocationNotes,
								'severity' => $globalSet->swellingSeverityNotes,
								'duration' => $globalSet->swellingDurationNotes,
							],
						],

						'muscle-atrophy' => [
							'enabled' => $globalSet->muscleAtrophyEnabled,
							'heading' => $globalSet->muscleAtrophyHeading,
							'body' => $globalSet->muscleAtrophyBody,
							'notes' => [
								'base' => $globalSet->muscleAtrophyBaseNotes,
							]
						],

						'crepitus-on-motion' => [
							'enabled' => $globalSet->crepitusOnMotionEnabled,
							'heading' => $globalSet->crepitusOnMotionHeading,
							'body' => $globalSet->crepitusOnMotionBody,
							'notes' => [
								'base' => $globalSet->crepitusOnMotionBaseNotes,
								'severity' => $globalSet->crepitusOnMotionSeverityNotes,
							]
						],

						// 'range-of-motion' => [
						// 	'enabled' => $globalSet->rangeOfMotionEnabled,
						// 	'heading' => $globalSet->rangeOfMotionHeading,
						// 	'body' => $globalSet->rangeOfMotionBody,
						// 	'notes' => [
						// 		'base' => $globalSet->rangeOfMotionBaseNotes,
						// 	]
						// ],

						'flexion' => [
							'enabled' => $globalSet->flexionEnabled,
							'heading' => $globalSet->flexionHeading,
							'body' => $globalSet->flexionBody,
							'notes' => [
								'base' => $globalSet->flexionBaseNotes,
								'base-ankle' => $globalSet->flexionBaseNotesAnkle,
							]
						],

						'extension' => [
							'enabled' => $globalSet->extensionEnabled,
							'heading' => $globalSet->extensionHeading,
							'body' => $globalSet->extensionBody,
							'notes' => [
								'base' => $globalSet->extensionBaseNotes,
								'base-ankle' => $globalSet->extensionBaseNotesAnkle,
							]
						],

						'joint-pain' => [
							'enabled' => $globalSet->jointPainEnabled,
							'heading' => $globalSet->jointPainHeading,
							'body' => $globalSet->jointPainBody,
							'notes' => [
								'base' => $globalSet->jointPainBaseNotes,
							]
						],

						'strength' => [
							'enabled' => $globalSet->strengthEnabled,
							'heading' => $globalSet->strengthHeading,
							'body' => $globalSet->strengthBody,
							'notes' => [
								'base' => $globalSet->strengthBaseNotes,
							],
							'modal' => [
								'ankle' => [
									'plantar-flexion' => $globalSet->strengthAnklePlantarFlexionModalDescription,
									'dorsiflexion' => $globalSet->strengthAnkleDorsiflexionModalDescription,
								]
							]
						],

						'gait' => [
							'enabled' => $globalSet->gaitEnabled,
							'heading' => $globalSet->gaitHeading,
							'body' => $globalSet->gaitBody,
							'notes' => [
								'base' => $globalSet->gaitBaseNotes,
							]
						],

						'axial-alignment' => [
							'enabled' => $globalSet->axialAlignmentEnabled,
							'heading' => $globalSet->axialAlignmentHeading,
							'body' => $globalSet->axialAlignmentBody,
							'notes' => [
								'degrees' => $globalSet->axialAlignmentDegreesNotes,
								'alignment' => $globalSet->axialAlignmentAlignmentNotes,
							]
						],
					];
				}
			];
		},

		'json/v1/footer' => function () {

			return [
				'cache' => false,
				'pretty' => false,
				'elementType' => GlobalSet::class,
				'criteria' => [
					'handle' => 'footer'
				],
				'one' => true,
				'transformer' => function (GlobalSet $globalSet) {

					return [
						'contactLink' => parseCraftLinkField($globalSet->contactLink, ['class' => 'text-link']),
					];
				}
			];
		},

	]
];