<?php

namespace TPsoft\BugreportBackend;

class Maintenance extends \TPsoft\DBmodel\Maintenance
{

	public function database()
	{
		if (!$this->existsTable('options')) {
			$this->checkDBTable('options', '
				`key` VARCHAR(255) NOT NULL PRIMARY KEY,
				`value` VARCHAR(255) NOT NULL
			');
			$this->dbver(1);
		}
		$dbver = $this->dbver();
		if ($dbver == 1) {
			$this->checkDBTable('reports', '
				`report_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
				`report_title` varchar(255) DEFAULT NULL,
				`report_description` text DEFAULT NULL,
				`report_status` int(11) DEFAULT NULL,
				`report_group` varchar(255) NOT NULL,
				`report_priority` int(11) DEFAULT NULL,
				`ordnum` int(11) DEFAULT NULL,
				`created_dt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
			');
			$this->dbver(2);
			$dbver = 2;
		}
		if ($dbver == 2) {
			$this->checkDBTable('attachments', '
				`attachment_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
				`report_id` int(11) NOT NULL,
				`attachment_type` varchar(255) DEFAULT NULL,
				`attachment_content` text DEFAULT NULL,
				`created_dt` datetime DEFAULT NULL,
				`updated_dt` datetime DEFAULT NULL
			');
			$this->dbver(3);
			$dbver = 3;
		}
	}

	protected function settings(string $key, ?string $value = null): string|false
	{
		if (is_null($value)) {
			return $this->dbh->getOne(sprintf('SELECT `value` FROM `options` WHERE `key` = %s', $this->dbh->quote($key)));
		} else {
			$db_type = $this->dbh->getDBtype();
			switch ($db_type) {
				case 'mysql':
					return $this->dbh->query(sprintf(
						'INSERT INTO `options` (`key`, `value`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE `value` = %s',
						$this->dbh->quote($key),
						$this->dbh->quote($value),
						$this->dbh->quote($value)
					)) !== false;
					break;
				case 'sqlite':
					return $this->dbh->query(sprintf(
						'INSERT INTO `options` (`key`, `value`) VALUES (%s, %s) ON CONFLICT(`key`) DO UPDATE SET `value` = %s',
						$this->dbh->quote($key),
						$this->dbh->quote($value),
						$this->dbh->quote($value)
					)) !== false;
					break;
				default:
					new \Exception('Unknown DB type: ' . $db_type);
					return false;
					break;
			}
		}
	}

	protected function dbver(?string $ver = null)
	{
		return $this->settings('version', $ver);
	}
}
