<?php
 namespace TCMS;
 use TCMS\Migration\MigrationDb;
 use TCMS\Migration\TableColumn;
 if(!function_exists("showLogInfo")) {
 function showLogInfo($text) {
 echo "\e[1;34m$text\e[0m\n";
 }
 function showLogError($text) {
 echo "\e[1;31m$text\e[0m\n";
 }
 function showLogSuccess($text) {
 echo "\e[1;32m$text\e[0m\n";
 }
 }
 if(!defined('ENVIRONMENT')) {
 define('ENVIRONMENT', 'dev');
 }
 abstract class Migration {
 public function __construct() {
 }
 public function run($db, $isRollback = false) {
 if($isRollback === false) {
 $db->__isOK = true;
 $this->up($db);
 if($db->__isOK == true) {
 if(!$db->_isMongodb) {
 $db->___insertToMigration();
 }
 $this->seed($db);
 }
 else {
 $_fileName = $db->__file_name;
 if(!$db->_isMongodb) {
 echo $_fileName . ": ";
 showLogInfo("Rollback");
 $this->down($db);
 }
 }
 }
 else {
 $_fileName = $db->__file_name;
 echo $_fileName . ": ";
 showLogSuccess("Rollback thành công!");
 $this->down($db);
 $this->reSeed($db);
 }
 }
 abstract protected function up(MigrationDb $db);
 public function seed() {
 }
 abstract protected function down(MigrationDb $db);
 public function reSeed() {
 }
 }
 class TCMSMigration extends Migration {
 public function createMigrationTable(MigrationDb $db) {
 if(!$db->isTableExist('migrations')) {
 $db->create('migrations', function(TableColumn $tableColumn) {
 $tableColumn->int('id')->autoIncrement()->primaryKey();
 $tableColumn->string('file_name')->unique();
 $tableColumn->int('version_index');
 }
);
 }
 }
 public function getNextMigrationVersionIndex(MigrationDb $db) {
 return ((int)\Db::table('migrations')->max('version_index')) + 1;
 }
 public function getAllFileInCurVersion(MigrationDb $db, $fileName = false) {
 try {
 if($fileName) {
 $files = \Db::table('migrations')->select('file_name')->where('file_name', $fileName)->toList();
 }
 else {
 $files = \Db::table('migrations')->select('file_name')->where('version_index', $db->__cur_version - 1)->toList();
 }
 $data = [];
 foreach ($files as $file) {
 $data[] = $file->file_name;
 }
 return $data;
 }
 catch (TException $ex) {
 }
 return [];
 }
 public function deleteAllFileInVersion(MigrationDb $db, $fileName = false) {
 try {
 if($fileName) {
 \Db::table('migrations')->where('file_name', $fileName)->delete();
 }
 else {
 \Db::table('migrations')->where('version_index', $db->__cur_version - 1)->delete();
 }
 }
 catch (TException $ex) {
 }
 }
 public function isExistFile(MigrationDb $db, string $fileName) {
 $count = (int)\Db::table('migrations')->where('file_name', $fileName)->count('id');
 return $count > 0;
 }
 public function up(\TCMS\Migration\MigrationDb $db) {
 }
 public function down(\TCMS\Migration\MigrationDb $db) {
 }
 }
 ?>