<?php

namespace App\Controller;

use App\Service\ElasticSearch;
use App\Tool;
use App\Tool\Utils;
use App\Service\FeedManager;
use Pimcore\Model\Asset;
use Pimcore\Tool\Admin;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class DefaultController extends BaseController
{
	/*						DOCUMENT ROUTED ACTIONS							*/

	/**
	 * @return Response
	 */
	public function indexAction()
	{
		return $this->render('default/index.html.twig');
	}

	/**
	 * @return Response
	 */
	public function defaultAction()
	{
		return $this->render('default/default.html.twig');
	}

	/**
	 * @return Response
	 */
	public function errorPageAction()
	{
		return $this->render('default/errorPage.html.twig');
	}

	/**
	 * @return Response
	 */
	public function emptyPageAction()
	{
		if (!$this->editmode && !\Pimcore\Tool::isFrontendRequestByAdmin() && !($this->getRequest()->get('elastic_document_indexing'))) {
			$childs = $this->document->getChildren();
			if (empty($childs)) {
				throw $this->createNotFoundException($this->translate('system_page_not_found'));
			} else {
				return $this->gotoUrl(current($childs)->getFullPath());
			}
		}

		return $this->render('default/emptyPage.html.twig');
	}

	/* 						STATIC-ROUTE ROUTED ACTIONS						 */

	/*							VIEW-LESS ACTIONS							*/

	#[Route('/admin/plugin/backend/is-elastic-search-enabled')]
	public function isElasticSearchEnabledAction()
	{
		$jsonResponse = new JsonResponse([
			'status' => true,
			'ese' => (Utils::elasticSearchEnabled() && Admin::getCurrentUser()->isAdmin()),
		]);

		return $jsonResponse;
	}

	#[Route("/plugin/backend/reindex-elastic-search")]
	public function reindexElasticAction()
	{
		$responseData = ['status' => false];

		if (Utils::elasticSearchEnabled() && Admin::getCurrentUser()->isAdmin()) {
			Tool\ElasticSearch::updateIndicesAndReindexContent(true, true);
			$responseData = ['status' => true];
		}

		$jsonResponse = new JsonResponse($responseData);

		return $jsonResponse;
	}

	#[Route("/api/search/{query}")]
	public function searchAction(ElasticSearch $elastic, string $query): JsonResponse
	{
		$responseData = [];
		if (Utils::elasticSearchEnabled()) {
			$responseData = $elastic->fulltextSearch(['query' => $query]);
			//$responseData = $elastic->getNews(['query' => $query]);
		}

		$jsonResponse = new JsonResponse($responseData);

		return $jsonResponse;
	}

	/**
	 * @param int $id
	 *
	 * @return BinaryFileResponse
	 */
	public function downloadAssetAction($id)
	{
		$asset = Asset::getById($id);
		if (!$asset) {
			$this->addErrorMsg($this->translate('msg_invalid_request'));

			return $this->gotoUrl($this->docUrl('/'));
		}

		$filename = substr(basename($asset->getFilename()), (stripos($asset->getFilename(), '_')) ? stripos($asset->getFilename(), '_') + 1 : 0);

		$fileResponse = BinaryFileResponse::create($asset->getFileSystemPath());
		$fileResponse->setContentDisposition('attachment', $filename);

		return $fileResponse;
	}

	/**
	 * @param FeedManager $feedManager
	 *
	 * @return Response XML file
	 */
	public function sitemapXmlAction(FeedManager $feedManager)
	{
		// since v10.5 use of @PrestaSitemapBundle is possible

		$xml = $feedManager->generateSitemapXml();

		$xmlResponse = new Response($xml);
		$xmlResponse->headers->set('Content-Type', 'application/xml');

		return $xmlResponse;
	}

	/*							FORM HANDLERS								*/
}
