<?php

/***************************************************************
 *  Copyright notice
 *
 *  (c) sgalinski Internet Services (https://www.sgalinski.de)
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

namespace SGalinski\SgJobs\Controller;

use Doctrine\DBAL\Exception;
use Psr\Http\Message\ResponseInterface;
use SGalinski\SgJobs\Domain\Repository\CompanyRepository;
use SGalinski\SgJobs\Domain\Repository\JobRepository;
use SGalinski\SgJobs\Pagination\Pagination;
use SGalinski\SgJobs\Service\BackendService;
use TYPO3\CMS\Backend\Template\Components\DocHeaderComponent;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;

/**
 * The backend module controller
 */
class BackendController extends ActionController {
	/**
	 * DocHeaderComponent
	 *
	 * @var DocHeaderComponent
	 */
	protected DocHeaderComponent $docHeaderComponent;

	/**
	 * @var CompanyRepository
	 *
	 */
	protected CompanyRepository $companyRepository;

	/**
	 * @var JobRepository
	 *
	 */
	protected JobRepository $jobRepository;

	/**
	 * @var ModuleTemplateFactory
	 */
	protected ModuleTemplateFactory $moduleTemplateFactory;

	/**
	 * @var ModuleTemplate
	 */
	protected ModuleTemplate $moduleTemplate;

	public function __construct(
		CompanyRepository $companyRepository,
		JobRepository $jobRepository,
		ModuleTemplateFactory $moduleTemplateFactory
	) {
		$this->companyRepository = $companyRepository;
		$this->jobRepository = $jobRepository;
		$this->moduleTemplateFactory = $moduleTemplateFactory;
	}

	public function initializeAction(): void {
		parent::initializeAction();
		$this->moduleTemplate = $this->moduleTemplateFactory->create($this->request);
	}

	/**
	 * Show all job offers and options to manage them
	 *
	 * @param array $filters
	 * @param int $currentPage
	 * @return ResponseInterface
	 * @throws InvalidQueryException
	 * @throws Exception
	 */
	public function indexAction(array $filters = [], int $currentPage = 1): ResponseInterface {
		$pageUid = $this->request->getQueryParams()['id'] ?? 0;
		$itemsPerPage = 10;
		/** @var BackendUserAuthentication $backendUser */
		$backendUser = $GLOBALS['BE_USER'];
		if ($filters === []) {
			$filters = $backendUser->getModuleData('web_SgJobsBackend_filters', 'ses') ?: [];
		} else {
			$backendUser->pushModuleData('web_SgJobsBackend_filters', $filters);
		}

		// create docheader + buttons
		$pageInfo = BackendUtility::readPageAccess($pageUid, $GLOBALS['BE_USER']->getPagePermsClause(1));
		if ($pageInfo === FALSE) {
			$pageInfo = ['uid' => $pageUid];
		}

		$this->docHeaderComponent = GeneralUtility::makeInstance(DocHeaderComponent::class);
		$this->docHeaderComponent->setMetaInformation($pageInfo);
		BackendService::makeButtons($this->docHeaderComponent, $this->request);
		$this->moduleTemplate->assign('docHeader', $this->docHeaderComponent->docHeaderContent());

		$this->moduleTemplate->assign('pageUid', $pageUid);
		$this->moduleTemplate->assign('pages', BackendService::getPagesWithJobRecords());

		$jobsQueryResult = $this->jobRepository->findBackendJobs($pageUid, $filters, $itemsPerPage);
		$pagination = GeneralUtility::makeInstance(Pagination::class, $jobsQueryResult, $currentPage, $itemsPerPage);
		$this->moduleTemplate->assign('pagination', $pagination);

		$totalJobCount = $pagination->getTotalItems();
		$this->moduleTemplate->assign('totalJobCount', $totalJobCount);
		// get all Locations
		/** @noinspection PhpUndefinedMethodInspection */
		/** @var QueryResultInterface $companies */
		$companies = $this->companyRepository->findByPid($pageUid);
		$this->moduleTemplate->assign('locationOptions', $companies);

		$this->moduleTemplate->assign('isAdmin', $GLOBALS['BE_USER']->isAdmin());
		$this->moduleTemplate->assign('filters', $filters);
		if (!$totalJobCount && $pageUid) {
			$this->addFlashMessage(
				LocalizationUtility::translate('backend.notice.noRecords', 'SgJobs'),
				'',
				ContextualFeedbackSeverity::INFO
			);
		}

		return $this->moduleTemplate->renderResponse('Index');
	}
}