<?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;
use Nette\Utils\DateTime;


class ContactManager extends DatabaseManager {

	const
		TABLE_NAME = 'contacts',
		COLUMN_NAME = 'name',
		COLUMN_CREATED = 'created_at',
		COLUMN_ID = 'contact_id',
		COLUMN_MAIL = 'mail',
		COLUMN_ACTIVE = 'active',
		COLUMN_KEY = 'adress_id',
		COLUMN_TOKEN = 'token',
		COLUMN_SALT = 'salt';

	protected $token;

	public function getContacts($url) {

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

	public function getContactsAdmin($url) {

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

	public function getContact($url) {

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

	public function getContactAdmin($url) {

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

	public function removeContact($id) {

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

	}

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

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

			$salt = rand();

			$this->token = sha1($values->mail.$salt);

			$this->database->table(self::TABLE_NAME)->insert([
				'adress_id' => $adress_id,
				'name' => $values->name,
				'mail' => $values->mail,
				'active' => $values->active,
				'token' => $this->token,
				'salt' => $salt,
				'created_at' => date('Y-m-d H:i:s'),
			]);
		} else {
			$contact_id = $values['contact_id'];
			$this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $contact_id)->update($values);
		}
	}

	public function isActive($id) {

		$result = $this->database->table(self::TABLE_NAME)->where(self::COLUMN_ID, $id)->fetchField(self::COLUMN_ACTIVE);

		if ($result == 1) {
			return "Ano";
		} elseif ($result == 0) {
			return "Ne";
		}
	}

}
