<?php

namespace Planaday\Html\Tags\Admin\Pages\Support;

use Planaday\Api\ApiException\InvalidResponseException;
use Planaday\Database\Abstraction\DatabaseHandler;
use Planaday\Entities\Course\CourseController;
use Planaday\Entities\PostEntities;
use Planaday\Html\Tags\Tag;
use Planaday\Platform\PlatformAbstraction\DataHandler;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\PluginData;

class Support extends Tag {
	const TAG = 'admin-page-support';
	const DEFAULT_TEMPLATE = 'support';

	protected PostEntities $postEntities;
	protected UrlHandler $urlHandler;
	protected CourseController $courseController;
	protected PluginData $pluginData;
	protected DataHandler $dataHandler;
	protected DatabaseHandler $databaseHandler;

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct(Container $registry) {
		$this->postEntities = $registry->getInstance(PostEntities::class);
		$this->pluginData = $registry->getInstance(PluginData::class);
		$this->urlHandler = $registry->getInstance(UrlHandler::class);
		$this->dataHandler = $registry->getInstance(DataHandler::class);
		$this->courseController = $registry->getInstance(CourseController::class);
		$this->databaseHandler = $registry->getInstance(DatabaseHandler::class);
		parent::__construct(__DIR__, self::DEFAULT_TEMPLATE, $registry);
	}

	public function buildTag(): string {
		if (in_array('flush-permalinks', $this->postEntities->getActions())) $this->urlHandler->flushRewriteRules();
		if (in_array('rebuild-pad-databases', $this->postEntities->getActions())) $this->databaseHandler->rebuildDatabases();

		$parser = $this->getNewParser();

		$parser->setCondition('cssConverterFirst', in_array('CSS Converter', $this->postEntities->getActions()));
		$parser->setData("prefix", $this->pluginData->getShortPrefix());
		$parser->setData("supportString", $this->dataHandler->getSupportString());
		$parser->setData('sqlQuery', $this->databaseHandler->getCreateDatabaseQueries(true));

		$templateRows = '';
		try{
			$templates = $this->courseController->getCourseTemplateList();
			foreach ($templates as $template) {
				$templateRows .= "<tr><td> " . $template->getName() . "</td><td class='pad-copy-this' style='cursor:pointer'>templateid=" . $template->getId() ." </td></tr>";
			}
			$parser->setUnsafeData('templateList', $templateRows);
		} catch (InvalidResponseException $e){
			$this->logError("Unable to fetch course templates: " . $e->getMessage(), $e);
			$parser->setUnsafeData('templateList', '<tr><td>No templates found</td><td>-</td></tr>');
		}

		return $parser->parse($this->getTemplate());
	}
}