<?php

declare(strict_types=1);

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

namespace vossmedien\DacoreBundle\Controller\Frontend\Module;

use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
use Contao\CoreBundle\ServiceAnnotation\FrontendModule;
use Contao\ModuleModel;
use Contao\PageModel;
use Contao\Template;
use Haste\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use vossmedien\DacoreBundle\API\Softgarden;

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

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

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


    protected function getResponse(Template $template, ModuleModel $model, Request $request): ?Response
    {
        if (($userToken = $this->api->getUserAccessToken('bewerber@dacore.api','Aebekai2ail4coum')) === null)
        {
            return new Response();
        }

        if (!$this->api->hasApplied(32630195,$userToken->token_type,$userToken->access_token))
        {
            $applicationId = $this->api->startApplication(32630195,$userToken->token_type,$userToken->access_token);
        } else {
            $applicationId = $this->api->getApplicationId(32630195,$userToken->token_type,$userToken->access_token);
        }

        $application = $this->api->getApplication($applicationId,$userToken->token_type,$userToken->access_token);

        if ($application !== null && isset($application->applicationEditable) && !$application->applicationEditable)
        {
            return new Response('Already applied');
        }
        elseif ($application === null || !isset($application->applicationId))
        {
            return new Response('Bewerbung derzeit nicht möglich');
        }


        $strFormId = 'jobapplication-form';

        $Form = new Form($strFormId,'POST', function($objHaste) {
            return \Input::post('FORM_SUBMIT') === $objHaste->getFormId();
        });

        $Form->addFieldsFromFormGenerator($model->form, function(&$strField, &$arrDca) {
            return true;
        });

        $template->form = $Form->generate();

        return $template->getResponse();
    }

}