<?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\Controller;
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\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use vossmedien\DacoreBundle\API\Softgarden;
use vossmedien\DacoreBundle\Generator\CodeGenerator;
use vossmedien\DacoreBundle\Model\VrApiUserCounterModel;

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

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

    /**
     * @var RequestStack
     */
    protected $requestStack;

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


    protected function getResponse(Template $template, ModuleModel $model, Request $request): ?Response
    {
        $session = $this->requestStack->getSession();
        $arrApiUser = [];


        if (!$session->has('vr_api_user'))
        {
            $time = time();

            $NewApiUser = new VrApiUserCounterModel();
            $NewApiUser->setRow(['tstamp'=>$time,'created'=>$time]);
            $NewApiUser->save()->refresh();

            $arrApiUser = [
                'username' => 'bewerber' . $NewApiUser->id . '@dacore.api',
                'password' => $this->generatePassword()
            ];

            if ($this->api->createApplicantUser($arrApiUser['username'],$arrApiUser['password']))
            {
                $session->set('vr_api_user',$arrApiUser);
            }
        } else {
            $arrApiUser = $session->get('vr_api_user');
        }

        if (($userToken = $this->api->getUserAccessToken($arrApiUser['username'],$arrApiUser['password'])) === 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);
dump($application);
        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();
    }

    protected function generatePassword()
    {
        $digits    = array_flip(range('0', '9'));
        $lowercase = array_flip(range('a', 'z'));
        $uppercase = array_flip(range('A', 'Z'));
        $special   = array_flip(str_split('!@#$%^&*()_+=-}{[}]\|;:<>?/'));
        $combined  = array_merge($digits, $lowercase, $uppercase, $special);

        $password  = str_shuffle(array_rand($digits) .
            array_rand($lowercase) .
            array_rand($uppercase) .
            array_rand($special) .
            implode(array_rand($combined, 8)));

        return $password;
    }

}