<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;
use Nette\Application\Responses;

final class InstructorPresenter extends BasePresenter
{
    public function renderDefault() {}

	public function actionGetAllInstructors(): void
	{
		$this->checkUserAccess('instruktor', false);
		$data = $this->personManager->getAllInstructors();
		$json = array();
		foreach($data as $instructor){
			$row = array();
			foreach (INSTRUCTOR_BASIC_DATA_TRANSFER as $dbName => $jsonName) {
				$row[$jsonName] = $instructor[$dbName];
			}
			$json[] = $row;
		}
		$this->sendJson($json);	
	}

	public function actionChangeRole(): void
	{
		$this->checkUserAccess('zamestnanec', false);
		$httpRequest = $this->getHttpRequest();
		$body = $httpRequest->getRawBody();
		$data = json_decode($body, true);
		$this->saveLog('osoby', 'uprava', array('ID_osoby' => $data['ID'], 'role' => $data['role']));
		try {
			$this->personManager->changeRole($data['ID'], $data['role']);
		} catch (Nette\Security\AuthenticationException $e) {
			$this->error('nespravne prihlasovaci udaje', Nette\Http\Response::S403_FORBIDDEN);
		}
		$this->sendJson(array());	
	}

	public function actionSaveProfile(): void
	{
		$this->checkUserAccess('cekatel', false);

		$httpRequest = $this->getHttpRequest();
		$body = $httpRequest->getRawBody();
		$data = json_decode($body, true);

		// data transfer json->db
		$dbData = array();
		foreach (INSTRUCTOR_BASIC_DATA_TRANSFER as $dbName => $jsonName) {
			if($dbName != 'ID' && $jsonName != 'role' && $jsonName != 'notes') {
				$dbData[$dbName] = $data[$jsonName];
			}
		}
		// data transfer end

		if($this->roleIsAtLeast('zamestnanec') == false && $data['ID'] != $this->getUser()->getId()) {
			$this->error('nedostatecna opravneni pro zmenu tohoto uzivatele', Nette\Http\Response::S403_FORBIDDEN);
		}

		$this->saveLog('osoby', 'uprava', $dbData);
		try {
			$this->personManager->updateProfile($data['ID'], $dbData);
		} catch (Nette\Security\AuthenticationException $e) {
			$this->error('nespravne prihlasovaci udaje', Nette\Http\Response::S403_FORBIDDEN);
		}
		$this->sendJson(array());	
	}
}
