<?php

declare(strict_types=1);

/*
 * This file is part of alox bundle for Contao.
 *
 * (c) Benjamin Roth
 *
 * @license commercial
 */

namespace vossmedien\AloxBundle\Controller\Frontend\Module;

use Contao\Config;
use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
use Contao\CoreBundle\ServiceAnnotation\FrontendModule;
use Contao\Input;
use Contao\ModuleModel;
use Contao\PageModel;
use Contao\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use vossmedien\AloxBundle\API\Zvoove;

/**
 * @FrontendModule(JoblistModuleController::TYPE, category="miscellaneous")
 */
class JoblistModuleController extends AbstractFrontendModuleController
{
    public const TYPE = 'alox_joblist';

    /**
     * @var Zvoove
     */
    protected $api;

    public function __construct(Zvoove $api)
    {
        $this->api = $api;
    }


    protected function getResponse(Template $template, ModuleModel $model, Request $request): ?Response
    {
        $limit = null;
        $offset = 0;

        $strFormId = 'joblist-form';
        $arrSearchParams = [];
        $arrSetFilters = [
            'filter_keywords' => null,
            'filter_city' => null,
            'filter_city_label' => null,
            'filter_radius' => null,
            'filter_vertragsart' => null,
            'filter_abteilung' => null
        ];

        // Prepare search parameters
        if (Input::get('FORM_SUBMIT') == $strFormId)
        {
            if (Input::get('filter_keywords'))
            {
                $arrSearchParams['keywords'] = Input::get('filter_keywords');
                $arrSetFilters['filter_keywords'] = Input::get('filter_keywords');
            }

            if (Input::get('filter_city'))
            {
                list($lat,$lon) = explode(',',Input::get('filter_city'));
                $arrSearchParams['lat'] = floatval($lat);
                $arrSearchParams['lon'] = floatval($lon);
                $arrSearchParams['radius'] = max((intval(Input::get('filter_radius')) ?: 25),5);

                $arrSetFilters['filter_city'] = Input::get('filter_city');
                $arrSetFilters['filter_city_label'] = Input::get('filter_city_label');
                $arrSetFilters['filter_radius'] = Input::get('filter_radius');
            }

            if (Input::get('filter_vertragsart'))
            {
                $value = Input::get('filter_vertragsart');
                if (\is_array($value))
                {
                    $value = implode(',',$value);
                }
                $arrSearchParams['vaUuids'] = $value;
                $arrSetFilters['filter_vertragsart'] = Input::get('filter_vertragsart');
            }

            if (Input::get('filter_abteilung'))
            {
                $value = Input::get('filter_abteilung');
                if (\is_array($value))
                {
                    $value = implode(',',$value);
                }
                $arrSearchParams['abtUuids'] = $value;
                $arrSetFilters['filter_abteilung'] = Input::get('filter_abteilung');
            }
        }

        // Get (filtered) jobs
        $jobs = $this->api->getStellenFiltered($arrSearchParams);

        // Get the total number of items
        $intTotal = $jobs->TotalItems;
        $total = $intTotal;
        $pagination = '';

        if ($model->perPage > 0)
        {
            // Adjust the overall limit
            if (isset($limit))
            {
                $total = min($limit, $total);
            }

            // Get the current page
            $id = 'list_page' . $model->id;
            $page = Input::get($id) ?? 1;

            // Do not index or cache the page if the page number is outside the range
            if ($page < 1 || $page > max(ceil($total / $model->perPage), 1))
            {
                throw new \PageNotFoundException('Page not found: ' . \Environment::get('uri'));
            }

            // Set limit and offset
            $limit = $model->perPage;
            $offset += (max($page, 1) - 1) * $model->perPage;

            // Overall limit
            if ($offset + $limit > $total)
            {
                $limit = $total - $offset;
            }

            // Add the pagination menu
            $objPagination = new \Pagination($total, $model->perPage, Config::get('maxPaginationLinks'), $id);
            $pagination = $objPagination->generate("\n  ");

            $arrSearchParams['pageNo'] = $page;
            $arrSearchParams['pageSize'] = $limit;
            $jobs = $this->api->getStellenFiltered($arrSearchParams);

        }


        // Get filter options
        $filterVertragsarten = $this->api->getKatalogByRelationName('StelleVertragsart','ChildEntity');
        $filterAbteilung = $this->api->getKatalogByRelationName('StelleAbteilung','Abteilung');


        // Populate template vars
        if ($jobs !== null && $jobs->TotalItems > 0)
        {
            $template->jobs = $jobs;
        }

        if ($filterVertragsarten !== null && $filterVertragsarten->TotalItems > 0)
        {
            $template->filterVertragsarten = $filterVertragsarten;
        }

        if ($filterAbteilung !== null && $filterAbteilung->TotalItems > 0)
        {
            $template->filterAbteilung = $filterAbteilung;
        }

        // Details link if jumpto page is defined
        if ($model->jumpTo && ($jumpTo = PageModel::findByPk($model->jumpTo)) !== null)
        {
            $template->detailsLink = $jumpTo->getFrontendUrl();
        }

        $template->formSubmit = $strFormId;
        $template->formSetFilters = $arrSetFilters;
        $template->pagination = $pagination;


        // Add scripts
        $GLOBALS['TL_BODY']['tomselect'] = Template::generateScriptTag('bundles/vossmedienalox/lib/tomselect/js/tom-select.base.js',false,null);
        $GLOBALS['TL_CSS']['tomselect'] = 'bundles/vossmedienalox/lib/tomselect/css/tom-select.min.css';

        return $template->getResponse();
    }

}