<?php
include_once dirname(dirname(__DIR__)) . '/bootstrap/autoload.php';

sanitize();

$models = [
		'User',
		'Location',
		'Role',
		'UserRole',
		'Permission',
		'Auth'
];

$location = realpath(dirname(dirname(__DIR__)) . '/src/common');

function extractColumn($table, $info, &$keys, &$foreigns) {
	$column = [];
	switch ($info[0]) {
		case 'string';
			$column['type'] = 'VARCHAR';
			break;
		default:
			$column['type'] = strtoupper($info[0]);
	}
	$column['name'] = '`' . str_replace('$', '', $info[1]) . '`';
	if ($column['name'] == '`id`') {
		$column['attr']['unsigned'] = 'UNSIGNED';
		$column['attr']['autoincrement'] = 'AUTO_INCREMENT';
		$keys []= $column['name'];
	}
	array_shift($info);
	array_shift($info);
	foreach ($info as $data) {
		if (strpos($data, '=') !== false) {
			list($attr, $val) = explode('=', $data);
			switch ($attr) {
				case 'length':
					$column['type'] .= '(' . $val . ')';
					break;
				case 'foreign':
					list($ftable, $fk) = explode('.', $val);
					$foreigns []= 'fk_' . $table . '_' . $ftable . ' FOREIGN KEY (' . $column['name'] . ') REFERENCES ' . $ftable . '(' . $fk . ')';
					$column['attr']['unsigned'] = 'UNSIGNED';
					break;
				default:
					$column['attr'][$attr] = strtoupper($attr . ' ' . $val);
			}
		} else {
			$column['attr'][$data] = strtoupper($data);
		}
	}

	if ($column['type'] == 'VARCHAR') {
		$column['type'] .= '(255)';
	}
	if (!isset($column['attr']['null'])) {
		$column['attr']['null'] = 'NOT NULL';
	}

	$attrs = ['unsigned', 'zerofill', 'null', 'default', 'autoincrement'];
	$reordered = [];
	foreach ($attrs as $attr) {
		if (isset($column['attr'][$attr])) {
			$reordered[$attr] = $column['attr'][$attr];
		}
	}
	$column['attr'] = $reordered;

	return $column;
}
function columnQuery($column) {
	$q = $column['name'] . ' ' . $column['type'];
	foreach ($column['attr'] as $attr) {
		$q .= ' ' . $attr;
	}
	return $q;
}
function tableQuery($table, $columns, $keys, $foreigns) {
	$q = 'CREATE TABLE `' . $table . '` (' . implode(', ', $columns);
	if (count($keys) > 0) {
		$q .= ', PRIMARY KEY (' . implode(', ', $keys) . ')';
	}
	if (count($foreigns) > 0) {
		$q .= ', CONSTRAINT ' . implode(', CONSTRAINT ', $foreigns);
	}
	$q .= ') ENGINE=InnoDB DEFAULT CHARSET=utf8;';

	return $q;
}

$cnt = 0;
$queries = [];
foreach ($models as $model) {
	$class = '\\Incoviba\\common\\' . $model;
	$ref = new ReflectionClass($class);

	$table = $ref->getProperty('_table')->getValue();
	$comments = explode(PHP_EOL, $ref->getDocComment());

	$columns = [];
	$keys = [];
	$foreigns = [];
	foreach ($comments as $comment) {
		if (strpos($comment, '@property') === false) {
			continue;
		}
		$info = explode(' ', substr($comment, strpos($comment, '@property') + strlen('@property ')));
		$column = extractColumn($table, $info, $keys, $foreigns);

		$columns []= columnQuery($column);
	}

	$q = tableQuery($table, $columns, $keys, $foreigns);
	$queries []= $q;
}
try {
	\ORM::getDb()->beginTransaction();
	foreach ($queries as $q) {
		\ORM::getDb()->query($q);
	}
	\ORM::getDb()->commit();
	header('Location: next_step.php?step=create_user_base');
} catch (Exception $e) {
	\ORM::getDb()->rollBack();
	throw $e;
}
?>
