<?php
namespace Medienreaktor\Energize\ViewHelpers;

use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
* @package Energize
* @subpackage ViewHelpers
*/
class RecruiteeViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper {

    /**
     * @var bool
     */
    protected $escapeOutput = false;

    /**
     * @var string
     */

    // old API Token
    //protected $authTocken = "dU812lbuUsY7eMAVcLYf";
    // new Api Token for company
//    protected $authTocken = "QS9wN0FvRWUyVXptcHhoZkRNK29yUT09";

    /**
     * @var string
     */
    protected $apiEndpoint = "https://api.recruitee.com";

	/**
	* Arguments Initialization
	*/
	public function initializeArguments(): void {
		$this->registerArgument('as', 'string', 'The variable name the video data should be saved', TRUE);
		$this->registerArgument('companyID', 'string', 'The recruitee Company ID', TRUE);
		$this->registerArgument('companyName', 'string', 'The recruitee Company Name', TRUE);
		$this->registerArgument('apiKey', 'string', 'The API-Key for sending requests to recruitee API', TRUE);
	}

     /**
     * Render method
     * @return string
     */
    public function render() {

    	$as = $this->arguments['as'];

    	$companyID = $this->arguments['companyID'];
    	$companyName = $this->arguments['companyName'];
    	$apiKey = $this->arguments['apiKey'];

    	$return = array();
//        $companys = $this->getCompanys();

        $departments = array();
        $citys = array();
        $employmentType = array();
        $filterCompanys = array();
        $allJobs = array();

        $companys = array(
            0 => array(
                'id' => $companyID,
                'name' => $companyName,
                'api_key' => $apiKey
            )
        );

        $companyId = $GLOBALS['TYPO3_REQUEST']->getParsedBody()['company_id'] ?? $GLOBALS['TYPO3_REQUEST']->getQueryParams()['company_id'] ?? null;
        $offerId = $GLOBALS['TYPO3_REQUEST']->getParsedBody()['offer_id'] ?? $GLOBALS['TYPO3_REQUEST']->getQueryParams()['offer_id'] ?? null;
        $i = 0;

        if ($companyId && $offerId) {
            $return['offerDetail'] = $this->getOffer($companyId, $offerId, $apiKey);
        } else {
            foreach ($companys as $key => $company) {
                $return['data'][$key]['company'] = $company;
                $jobsReduced = $this->getJobs($company['id'],$company['api_key']);
                $filterCompanys[] = $company['name'];
                $detailJobs = array();
                foreach ($jobsReduced->offers as $jobReduced) {
                    $detailJob = $this->getOffer($company['id'], $jobReduced->id, $company['api_key']);
                    if ($detailJob->location == "Jobstandort flexibel") {
                        $citys[$detailJob->location] = $detailJob->location;
                        $detailJob->city = $detailJob->location;
                    }
                    else if($detailJob->city) {
                        $citys[$detailJob->city] = $detailJob->city;
                    }
                    if($detailJob->department) {
                        $departments[$detailJob->department] = $detailJob->department;
                    }
                    if($detailJob->employment_type) {
                        $employmentType[$detailJob->employment_type] = $detailJob->employment_type;
                    }
                    $allJobs[$i] = $detailJob;
                    $allJobs[$i]->company = $company;
                    $i++;
                    $detailJobs[] = $detailJob;
                }

                $return['data'][$key]['jobs'] = $detailJobs;
            }

            array_multisort($filterCompanys,SORT_ASC,SORT_REGULAR);

            usort($allJobs, function ($a, $b) {
                return strcmp($a->title, $b->title);
            });

            $return['allJobs'] = $allJobs;
            // Disable company filter since there is only one company atm
            //$return['filter']['companys'] = $filterCompanys;
            $return['filter']['departments'] = $departments;
            $return['filter']['citys'] = $citys;
            $return['filter']['employmentType'] = $employmentType;
        }

		$this->templateVariableContainer->add($as,$return);
		$output = $this->renderChildren();
		$this->templateVariableContainer->remove($as);
		return $output;
    }

    private function getJobs($companyId,$apiKey) {
        $jobs = $this->rawApiCall('/c/'.$companyId.'/offers/',$apiKey);
        return $jobs;
    }

//    private function getCompanys() {
//        $user = $this->rawApiCall('/admin/');
//        return $user->admin->companies;
//    }

    private function getOffer($companyId,$offerId,$apiKey) {

        $offer = $this->rawApiCall('/c/'.$companyId.'/offers/'.$offerId,$apiKey);
        return $offer->offer;
    }

    private function rawApiCall($url,$apiKey) {
        $requestFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Http\RequestFactory::class);
        $url = $this->apiEndpoint.$url;

        $additionalOptions = [
            'headers' => ['Authorization' => 'Bearer '.$apiKey]
        ];

        $response = $requestFactory->request($url, 'GET', $additionalOptions);
        return json_decode($response->getBody()->getContents());
    }

}
?>
