<?php

declare(strict_types=1);

namespace App\CoreModule\Model;

use Nette;
use App\Model\DatabaseManager;
use Nette\Database\Table\ActiveRow;
use Nette\Database\Table\Selection;
use Nette\Utils\ArrayHash;


class EventManager extends DatabaseManager {

	const
		TABLE_NAME = 'events',
		COLUMN_NAME = 'name',
		COLUMN_ID = 'event_id',
		COLUMN_INFO = 'popis',
		COLUMN_OPEN = 'otevreno',
		COLUMN_URL = 'url',
		COLUMN_CREATED = 'created_at';

	public function getEvents() {

		return $this->database->table(self::TABLE_NAME)->order(self::COLUMN_ID . ' DESC')->where(self::COLUMN_OPEN, 1);
	}

	public function getEventsAdmin() {

		return $this->database->table(self::TABLE_NAME)->order(self::COLUMN_ID . ' DESC');
	}

	public function getEvent($url) {

		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_URL, $url)->where(self::COLUMN_OPEN, 1)->fetch();
	}

	public function getEventAdmin($url) {

		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_URL, $url)->fetch();
	}

	public function idToURL($id) {

		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $id)->where(self::COLUMN_OPEN, 1)->fetch(self::COLUMN_URL);
	}

	public function idToURLAdmin($id) {

		return $this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $id)->fetch(self::COLUMN_URL);
	}

	public function saveEvent($event) {

		if (empty($event[self::COLUMN_ID])) {
			unset($event[self::COLUMN_ID]);	

			$event['created_at'] = date('Y-m-d H:i:s');
			$this->database->table(self::TABLE_NAME)->insert($event);	
		} else
			$this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $event[self::COLUMN_ID])->update($event);
	}

	public function removeEvent($url) {

		$this->database->table(self::TABLE_NAME)->where(self::COLUMN_URL, $url)->delete();

	}

	public function getAllEvents() {

	    $this->database->table(self::TABLE_NAME)->fetchAll();

	}

}
