<?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 InvitationManager extends DatabaseManager {

	const
		TABLE_NAME = 'invitations',
		TABLE_KEY = 'events',
		COLUMN_KEY_URL = 'url',
		COLUMN_NAME = 'name',
		COLUMN_ID = 'invitation_id',
		COLUMN_BODY = 'body',
		COLUMN_KEY_ID = 'event_id',
		COLUMN_CREATED = 'created_at',
		COLUMN_EDITED = 'edited_at';
		
	public $invitation_id;
	
	public function getInvitations() {

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

	public function getInvitation($id) {

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

	public function getInvitationKey($url) {

		$event_id = $this->urlToID($url);

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

	public function removeInvitation($id) {

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


	public function urlToID($url) {

		return $this->database->table(self::TABLE_KEY)->where(self::COLUMN_KEY_URL, $url)->fetch(self::COLUMN_KEY_ID);
	}

	public function idToURL($id) {

		return $this->database->table(self::TABLE_KEY)->where(self::COLUMN_KEY_ID, $id)->fetch(self::COLUMN_KEY_URL);
	}

	public function nazevAkce($id) {

		return $this->database->table(self::TABLE_KEY)->where(self::COLUMN_KEY_ID, $id)->fetch(self::COLUMN_NAME);
	}

	public function provedZapis($form, $event_url, $values) {

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

		$this->database->table(self::TABLE_NAME)->insert([
			'event_id' => $this->urlToID($event_url),
			'name' => $values->name,
			'body' => ($values->body),
			'edited_at' => date('Y-m-d H:i:s'),
			'created_at' => date('Y-m-d H:i:s'),
		]);
	} else 
		$this->invitation_id = $values['invitation_id'];
		$values['edited_at'] = date('Y-m-d H:i:s');
		$this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $this->invitation_id)->update($values);
	}


}
