<?php

namespace App\Controller;

use App\Form\ContactFormType;
use App\Model\DataObject\News;
use App\Service\MailManager;
use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
use Knp\Component\Pager\PaginatorInterface;
use Pimcore\File;
use Pimcore\Logger;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\ContactForm;
use Pimcore\Request\Attribute\DataObjectParam;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\FormInterface;

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

	public function templateSimpleAction(): Response
	{
		return $this->render('cms/templateSimple.html.twig');
	}

	public function simpleMailAction(): Response
	{
		return $this->render('cms/simpleMail.html.twig');
	}

	public function sitemapAction(): Response
	{
		return $this->render('cms/sitemap.html.twig');
	}

	public function contactUsAction(Request $request, MailManager $mailManager): Response
	{
		$form = $this->createForm(ContactFormType::class);
		$form->handleRequest($request);

		if ($form->isSubmitted()) {
			if ($this->handleContactForm($form, $mailManager, ContactFormType::FIELD_HONEYPOT)) {
				return $this->gotoUrl($this->docUrl('/kontakt'));
			}
		}

		return $this->render('cms/contactUs.html.twig', [
			'contactForm' => $form->createView(),
		]);
	}

	public function newsAction(Request $request, PaginatorInterface $paginator): Response
	{
		$page = $request->get('page', 1);

		$list = new News\Listing();
		$list->setOrder('desc');
		$list->setOrderKey('createdOn');
		$list->setCondition("createdOn < ? AND name IS NOT NULL AND name <> ''", [time()]);

		$paginate = $paginator->paginate(
			$list,
			$page,
			6
		);

		$paginationData = $paginate instanceof SlidingPagination ? $paginate->getPaginationData() : [];
		$paginationData['urlprefix'] = $this->docUrl($this->document->getFullPath()) . '?page=';

		return $this->render('cms/news.html.twig', [
			'news' => $paginator,
			'paginationData' => $paginationData
		]);
	}

	/* 						STATIC-ROUTE ROUTED ACTIONS						 */

	/*public function newsDetailAction(#[DataObjectParam(unpublished: false)] News $news): Response
	{
		if (!$news) {
			throw $this->createNotFoundException($this->translate('system_page_not_found'));
		}

		//get sibblings (next and previous news)
		$list = new News\Listing();
		$list->setOrder('desc');
		$list->setOrderKey('createdOn');
		$list->setCondition("createdOn < ? AND name IS NOT NULL AND name <> ''", [time()]);
		$list->load();
		list($previousNews, $nextNews) = $this->getSiblings($list, $news, 'createdOn');

		//extend breadcrumbs
		$this->addToBreadcrumbs[] = [
			'label' => $news->getName(),
			'url' => $news->getUrl(),
		];

		//explicit language switch
		$this->languageSwitch = $this->buildLanguageSwitchFromObject($news);

		//explicit seo stuff
		$this->headTitle->set($news->getName());
		if ($news->getSeoDescription()) {
			$this->headMeta->setName('description', $news->getSeoDescription());
		}

		return $this->render('cms/newsDetail.html.twig', [
			'news' => $news,
			'previousNews' => $previousNews,
			'nextNews' => $nextNews,
			'dataObject' => $news
		]);
	}*/

	/*				VIEW-LESS ACTIONS (ALWAYS REDIRECT)					*/

	/*							FORM HANDLERS								*/

	private function handleContactForm(FormInterface $form, MailManager $mailManager, string $honeypot): bool
	{
		if ($form->isValid()) {
			$data = $form->getData();

			// test honeypot field to not be empty
			if($honeypot && !empty($data[$honeypot])) {
				$this->addErrorMsg($this->translate('msg_form_invalid'), true);
				return false;
			}

			$data['lang'] = $this->language;

			$contactForm = ContactForm::create($data);
			$contactForm->setCreationDate(time());
			$key = File::getValidFilename($data['fullName'].'_'.date('Y-m-d-H:i:s', time()));
			$contactForm->setKey($key);
			$contactForm->setParentId(DataObject\Folder::getByPath('/kontakt/kontaktni-formulare')->getId());
			$contactForm->setPublished(true);

			try {
				$contactForm->save();

				//send email to admin
				$mailManager->sendMail('/notifikace/pro-administratora-novy-kontaktni-formular', $this->language, null, null, [
					'deeplink' => $this->getRequest()->getSchemeAndHttpHost().'/admin/login/deeplink?object_'.$contactForm->getId().'_object',
					'form' => $contactForm,
				]);

				$this->addSuccessMsg($this->translate('msg_contact_form_success'));

				return true;
			} catch (\Exception $e) {
				Logger::error('CONTACT FORM - '.$e->getMessage()."\n".$e->getTraceAsString());
				$this->addErrorMsg($this->translate('msg_unknown_error'));
			}
		} else {
			$this->addErrorMsg($this->translate('msg_form_invalid'));
		}

		return false;
	}
}
