<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;
use Nette\Utils\DateTime;

define("MINIMAL_DAYS_TO_COURSE", 14);

define("DEFAULT_CAPACITY", 2);

final class FreeScopesPresenter extends BasePresenter
{
    public function renderDefault() {

    }

	public function actionGetFreeScopes(): void
	{
		$this->checkUserAccess('zamestnanec', true);
		// $httpRequest = $this->getHttpRequest();
		$scopes = $this->generateAllScopes();
		$scopes = $this->checkScopesCapacity($scopes);
		$this->sendJson($scopes);
		$this->error('pozadovana data se nepovedlo nacist', Nette\Http\Response::S500_INTERNAL_SERVER_ERROR);
	}

	public function generateAllScopes()
	{
		$scopes = array();
		$actualDate = DateTime::from(MINIMAL_DAYS_TO_COURSE * 24 * 60 * 60);
		$dateLimit = DateTime::from(MINIMAL_DAYS_TO_COURSE * 24 * 60 * 60 * 3);
		while($actualDate < $dateLimit) {
			$dayOfWeek = $actualDate->format('w');
			// kurzy zacinaji od pondeli nebo stredy
			if($dayOfWeek == 1 || $dayOfWeek == 3) {
				$endDate = clone $actualDate;
				$endDate->modify('+2 days');
				$scopes[] = array( 'from' => $actualDate->format('Y-m-d'), 'to' => $endDate->format('Y-m-d'), 'capacity' => 2 );
			}
			$actualDate->modify('+1 day');
		}
		return $scopes;
	}

	public function checkScopesCapacity($scopes)
	{
		$result = array();
		foreach ($scopes as $index => $scope) {
			$occupied = $this->freeScopesManager->getOccupiedCapacity($scope['from'], $scope['to']);
			$available = DEFAULT_CAPACITY - $occupied;
			if($available > 0) {
				$scope['capacity'] = $available;	
				$result[] = $scope;
			}
		}
		return $result;
	}

}
