<?php

namespace Planaday\Entities;

use Planaday\Entities\Booking\BookingFormPostService;
use Planaday\Platform\PlatformAbstraction\DataHandler;
use Planaday\Utility\DataGrouping\LazyLoadingArray;
use Planaday\Utility\DataGrouping\PostFieldEnum;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\PluginData;

class PostEntities extends PostFieldEnum {
	use Logging;
	public const BOOKING_FORM = '-booking-form';
	public const SEARCH_FORM = '-search-form';
	public const GENERIC_POST = '-post';
	public const POST_ACTION = '-post-action';

	public static function getEnumArray(): array {
		return [
			'BOOKING_FORM' => self::BOOKING_FORM,
			'SEARCH_FORM'  => self::SEARCH_FORM,
			'GENERIC_POST'  => self::GENERIC_POST,
			'POST_ACTION' => self::POST_ACTION,
		];
	}
	protected LazyLoadingArray $error;

	public function __construct(
		protected PluginData $pluginData,
		protected Container $registry
	) {}

	/**
	 * @return LazyLoadingArray<string, mixed>
	 */
	public function getPostErrors(): LazyLoadingArray {
		if (!isset($this->error)){
			$this->error = new LazyLoadingArray();

			$this->error[$this->pluginData->getFullPrefix() . self::BOOKING_FORM] = function(){
				try {
					return $this->registry->getInstance(BookingFormPostService::class)->getError();
				} catch (InjectionImpossibleException $e){
					return $e->getMessage();
				}
			};
		}

		return $this->error;
	}

	/**
	 * @return string[]
	 */
	public function getActions(): array{
		try {
			$actions = $this->registry->getInstance(DataHandler::class)->getPostData()[ $this->pluginData->getFullPrefix() . self::POST_ACTION] ?? [];
			$this->logDebug('actions: ', $actions);
		} catch (InjectionImpossibleException ){
			$actions = [];
		}

		$output = [];

		foreach ($actions as $action){
			if (is_string($action)){
				$output[] = $action;
			}
		}

		return $output;
	}

	/**
	 * @return void
	 * @throws InjectionImpossibleException
	 */
	public function checkAndHandlePostRequest(): void
	{
		$this->logInfo('Checking request for post data');
		$data = $this->registry->getInstance(DataHandler::class);

		if (!$data->isPostDataSet()) return;
		$postData = $data->getPostData();

		$this->logDebug('Post data found', $postData);
		if (isset($postData[$this->pluginData->getFullPrefix() . self::BOOKING_FORM]) && $data->verifyNonce(self::BOOKING_FORM)){
			$this->logInfo('Booking form data found');
			$this->registry->getInstance(BookingFormPostService::class)
			               ->checkAndHandlePostData($data->getPostField(self::BOOKING_FORM));
		}
	}
}