<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;
use Exception;

final class SchoolPresenter extends BasePresenter
{

	public function renderDefault() {}

	public function actionGetAllSchools()
	{
		$this->checkUserAccess('instruktor');
		$data = $this->schoolManager->getAllSchools();
		$json = $this->applyTransfer($data, SCHOOL_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON);
		$this->sendJson($json);	
	}

	public function actionGetById(): void
	{
		$this->checkUserAccess('instruktor');
		$httpRequest = $this->getHttpRequest();
		$id = $httpRequest->getQuery('schoolId');
		if($id) {
			$data = $this->schoolManager->getById($id);
			if($data != null) {
				$json = $this->applyTransfer($data, SCHOOL_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON, DATA_OBJECT);
				$this->sendJson($json);
			}
			$this->error('pozadovana data se nepovedlo nacist', Nette\Http\Response::S500_INTERNAL_SERVER_ERROR);
		} else {
			$this->error('nebyl vlozen parametr id', Nette\Http\Response::S400_BAD_REQUEST);
		}
	}

	public function actionUpdateSchool(): void
	{
		$this->checkUserAccess('zamestnanec', true);
		$httpRequest = $this->getHttpRequest();
		$body = $httpRequest->getRawBody();
		$json = json_decode($body);	
		$data = $this->applyTransfer($json, SCHOOL_BASIC_DATA_TRANSFER, TRANSFER_TO_DB, DATA_OBJECT);
		
		$this->saveLog('skoly', 'uprava', $data);
		try {
			$result = $this->schoolManager->update($data);
		} catch (Exception $e) {
			$this->error('data se nepovedlo ulozit', Nette\Http\Response::S500_INTERNAL_SERVER_ERROR);
		}

		$data = $this->schoolManager->getById($json->ID);
		$json = $this->applyTransfer($data, SCHOOL_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON, DATA_OBJECT);
		$this->sendJson($json);		
	}
}
