<?php

CLASS dbAccess extends RasioProject
{
	protected $layout = 'loginDb/index';
	protected $set;
	protected $enableCk = false;
	protected $idAccesAdmin = 'loginDBAccesRasioProject';

	public function __construct($config)
	{
		$this->getConfig($config);
		$this->set();
	}

	protected function set()
	{
		$folder = $this->basePath.'config/domain/';
		$dir = opendir($folder);
		$app = array();
		$ctr = array();
		while($file = readdir($dir)){
			if ($file == "." or $file == "..")continue;
				$jum = explode('.', $file);
				if(count($jum) == 1){
					$folder2 = $folder.'/'.$file;
					$dir2 = opendir($folder2);
					while($file2 = readdir($dir2)){
						if ($file2 == "." or $file2 == "..")continue;
						
						if($file2 != 'func.php'){
							$app[] = $folder2.'/'.$file2;
						}
						
						$modul = strtolower(str_ireplace(".php", "", $file2));
						$ctr[$modul]->modul = $file;
					}
				}
		}

		foreach($app as $row){
			require_once($row);
		}
	
		$this->set->em 	= $this->em;
		return $this->set;
	}

	public function Index()
	{
		$this->data = $this->set;
		$this->view = "default/dbAccess";
	}
	
	public function login()
	{
		if($_POST){
			$id = $this->idAccesAdmin;
			
			$user = $_POST['user_name_login'];
			$pass = $_POST['password_login'];
			
			if($user == strtoupper('RASIO.1') and $pass = md5('secRasio5758')){
				echo "<font color='green'>Login Sukses...Silahkan Menunggu</font>";
				$_SESSION[$id] = true;
			}else{
				echo "<font color='red'>Login Gagal</font>";
				$_SESSION[$id] = false;
			}
		}
		
		if($_SESSION[$id] == true){
			$ajax  = $this->getPlugin('Ajax');
			$ajax->getAjaxValStart();
			$ajax->getWrite("window.location = '".$this->baseUrl."dbAccess/getDbRead';");
			$ajax->getAjaxValEnd();
			return;
		}
	
		$this->layout = "null";
	}
	public function getDefaultMenu()
	{
		$id = 'a';
		$res[$id]->no 		= $id;
		$res[$id]->induk 	= '';
		$res[$id]->nama 	= 'master';
		$res[$id]->url 		= '';
		$res[$id]->logo 	= '';
		$res[$id]->ket 		= '';
		$res[$id]->kode 	= '';
		$res[$id]->jenis 	= 1;
		
		$id = 'a.1';
		$res[$id]->no 		= $id;
		$res[$id]->induk 	= 'a';
		$res[$id]->nama 	= 'management-user';
		$res[$id]->url 		= '';
		$res[$id]->logo 	= '';
		$res[$id]->ket 		= '';
		$res[$id]->kode 	= '';
		$res[$id]->jenis 	= 1;
		
		$id = 'a.1.1';
		$res[$id]->no 		= $id;
		$res[$id]->induk 	= 'a.1';
		$res[$id]->nama 	= 'group';
		$res[$id]->url 		= 'basic-group';
		$res[$id]->logo 	= '';
		$res[$id]->ket 		= '';
		$res[$id]->kode 	= '';
		$res[$id]->jenis 	= 1;
		
		$id = 'a.1.2';
		$res[$id]->no 		= $id;
		$res[$id]->induk 	= 'a.1';
		$res[$id]->nama 	= 'user';
		$res[$id]->url 		= 'basic-user';
		$res[$id]->logo 	= '';
		$res[$id]->ket 		= '';
		$res[$id]->kode 	= '';
		$res[$id]->jenis 	= 1;
		
		$id = 'a.1.3';
		$res[$id]->no 		= $id;
		$res[$id]->induk 	= 'a.1';
		$res[$id]->nama 	= 'password';
		$res[$id]->url 		= 'basic-password';
		$res[$id]->logo 	= '';
		$res[$id]->ket 		= '';
		$res[$id]->kode 	= '';
		$res[$id]->jenis 	= 1;
		
		$id = 'a.1.4';
		$res[$id]->no 		= $id;
		$res[$id]->induk 	= 'a.1';
		$res[$id]->nama 	= 'setting';
		$res[$id]->url 		= 'basic-setting';
		$res[$id]->logo 	= '';
		$res[$id]->ket 		= '';
		$res[$id]->kode 	= '';
		$res[$id]->jenis 	= 1;
		
		return $res;
	}
	
	protected function getDbRead()
	{
		$_table  = $this->getTabInDb();
		$_SESSION[__CLASS__]->menu = $this->getDefaultMenu();
		
		$this->view = 'db/db';
		$this->data->table = $this->em->getDb();
		$this->layout = 'basic';
	}
	
	public function det()
	{
		$this->data->menu = $_SESSION[__CLASS__]->menu;
		$this->view = 'db/det';
		$this->layout = 'other/view';
	}
	
	public function del()
	{
		$key = $this->getParam[0];
		$data  = $_SESSION[__CLASS__]->menu;
		unset($data[$key]);
		$_SESSION[__CLASS__]->menu = $data;
		$this->det();
	}
	
	public function tambah()
	{
		$data = $_SESSION[__CLASS__]->menu;
		$id = strtolower($_POST['no']);
		$data[$id]->no 	= $id;
		$data[$id]->induk = strtolower($_POST['induk']);
		$data[$id]->nama = strtolower($_POST['nama']);
		$data[$id]->url = strtolower($_POST['url']);
		$data[$id]->logo = strtolower($_POST['logo']);
		$data[$id]->ket = strtolower($_POST['ket']);
		$data[$id]->kode = strtolower($_POST['kode']);
		$_SESSION[__CLASS__]->menu = $data;
		
		$ajax  = $this->getPlugin('Ajax');
		$ajax->getAjaxValStart();
		$ajax->getWrite("makeLoadDet()");
		$ajax->getAjaxValEnd();
		$this->layout = 'null';
	}
	
	protected function getTabInDb()
	{
		$res = array();
		foreach($this->em->getShowTable() as $r){
			$k = $r->tab;
			$res[$k] = $k;
		}
		return $res;
	}
	
	protected function getCreate()
	{
		$cu = $_POST['cu'];
		$_alias  = $this->em->getDb();
		$_table  = $this->getTabInDb();

		if(count($cu) > 0){
			foreach($cu as $k => $r){
				if(empty($_table[$k])){
					$qb[] = $this->em->getCreateTable($k);
				}
			}
		}

		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	protected function getAlias()
	{
		$res = array();
		foreach($this->em->getDb() as $k => $r){
			$res[$r] = $k;
		}
		return $res;
	}
	
	protected function getStructure($table)
	{
		$res = array();
		foreach($this->em->getStructure($table) as $r){
			$id = $r->name;
			$res[$id] = $id;
		}
		return $res;
	}
	
	protected function getClass($_alias, $k)
	{
		$alias = $_alias[$k];
		$clStr = 'TB_'.str_ireplace('.', '_', strtoupper($alias));
		return new $clStr;
	}
	
	public function getStrcutureConfig()
	{
		$db = new DB;
		foreach($db->getStructure() as $key => $row){
			$res->$key->name = $row['name'];
			$res->$key->type = $row['type'];
			$res->$key->size = $row['size'];
		}

		return $res;
	}
	
	protected function getUpTable()
	{
		$dbConf = $this->getStrcutureConfig();
		
		$cu = $_POST['cu'];
		$_alias  = $this->getAlias();
		$_table  = $this->getTabInDb();
		
		if(count($cu) > 0){
			foreach($cu as $k => $r){
				$structure = $this->getStructure($k);
				$class = $this->getClass($_alias, $k);
				foreach($class as $n => $row){
					$str = $dbConf->$n;
					$name = $str->name;
					if(!empty($structure[$name])){
						if(strtoupper(trim($structure[$name])) != '_NO'){
							$qb[] = $this->em->getAlterCol($k, $str);
						}
					}else{
						$qb[] = $this->em->getCreateCol($k, $str);
					}
				}

				if(empty($structure['chtime'])){
					$qb[] = "ALTER TABLE $k ADD COLUMN chtime timestamp without time zone";
				}
				if(empty($structure['chusr'])){
					$qb[] = "ALTER TABLE $k ADD COLUMN chusr character varying (255)";
				}
				if(empty($structure['_no'])){
					$noSeq = $k.'__no_seq';
					$qb[] = "ALTER TABLE $k ADD COLUMN _no integer";
					$qb[] = "ALTER TABLE $k ALTER COLUMN _no SET NOT NULL";
					$qb[] = "CREATE SEQUENCE $noSeq
							  INCREMENT 1
							  MINVALUE 1
							  MAXVALUE 9223372036854775807
							  START 1
							  CACHE 1";
					$qb[] = "ALTER TABLE $k ALTER COLUMN _no SET DEFAULT nextval('$noSeq'::regclass)";
				}
			}
		}
		
		echo '<pre>';
		var_dump($qb);
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	protected function getUpPk()
	{
		$cu = $_POST['pk'];
		$_alias  = $this->getAlias();
		$_table  = $this->getTabInDb();
		
		if(count($cu) > 0){
			foreach($cu as $k => $r){
				$pk = $this->em->getIndPk($k);
				$class = $this->getClass($_alias, $k);
				foreach($class->getIndex() as $n => $row){
					if(strtoupper($row) == strtoupper('PK')){
						if($pk > 0){
							$qb[] = $this->em->getDropPk($k, $n);
						}
						$qb[] = $this->em->getCreatePk($k, $n);
					}
				}
			}
		}
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	protected function getUpIndex()
	{
		$cu = $_POST['in'];
		$_alias  = $this->getAlias();
		$_table  = $this->getTabInDb();
		
		if(count($cu) > 0){
			foreach($cu as $k => $r){
				$class = $this->getClass($_alias, $k);
				foreach($class->getIndex() as $n => $row){
					if(strtoupper($row) == strtoupper('normal')){
						$in = $this->em->getIndIndex($k, $n);
						if($in > 0){
							$qb[] = $this->em->getDropIndex($k, $n);
						}
						$qb[] = $this->em->getCreateIndex($k, $n);
					}
				}
			}
		}
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	protected function getStrDomain($class)
	{
		$dbConf = $this->getStrcutureConfig();
		$res = array();
		foreach($class as $k => $r){
			$str = $dbConf->$k;
			$nama = $str->name;
			$res[$nama] = $k;
		}
		return $res;
	}
	
	protected function getDelIndex()
	{
		$cu = $_POST['del'];
		$_alias  = $this->getAlias();
		$_table  = $this->getTabInDb();
		
		if(count($cu) > 0){
			foreach($cu as $k => $r){
				$class = $this->getClass($_alias, $k);
				$domain = $this->getStrDomain($class);
				foreach($this->getStructure($k) as $n => $row){
					if(empty($domain[$n])){
						$qb[] = $this->em->getDropCell($k, $n);
					}
				}
			}
		}
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	protected function getDelTable()
	{
		$_alias  = $this->getAlias();
		$_table  = $this->getTabInDb();

		foreach($_table as $r){
			if(empty($_alias[$r])){
				$qb[] = $this->em->getDropTable($r);
			}
		}
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	public function insMenu($menu)
	{
		$attr['no_menu'] = $menu->no;
		$attr['induk'] 	= $menu->induk;
		$attr['nama'] 	= $menu->nama;
		$attr['url'] 	= $menu->url;
		$attr['logo'] 	= $menu->logo;
		$attr['ket'] 	= $menu->ket;
		$attr['jenis'] 	= (int)$menu->jenis;
		$sql = $this->em->addInsert('menu');
		$sql = $this->em->addAttrIns($attr);
		return $sql;
	}
	
	public function delMenu()
	{
		$sql = $this->em->addDelete('menu');
		return $sql;
	}
	
	protected function getInsMenu()
	{
		$qb[] = $this->delMenu();
		foreach($_SESSION[__CLASS__]->menu as $r){
			$qb[] = $this->insMenu($r);
		}
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	public function createUser($user)
	{
		$attr['kd_sub'] = strtoupper($user);
		$attr['nm_sub'] = strtoupper($user);
		$attr['username'] = strtoupper($user);
		$attr['pass'] 	= md5('12345');
		$attr['jenis'] 	= 1;
		$attr['kd_cabang'] 	= 'HO';
		$attr['status'] = 'AKTIF';
		$attr['hapus'] 	= 0;
		$sql = $this->em->addInsert('sub');
		$sql = $this->em->addAttrIns($attr);
		return $sql;
	}
	
	public function dropAcl($user)
	{
		$sql = $this->em->addDelete('acl');
		$sql = $this->em->getWhere("kd_user = '$user'");
		return $sql;
	}
	
	public function createAcl($user, $menu, $act, $val, $r)
	{
		$attr['id_acl'] = date('YmdHis').rand(100000, 999999);
		$attr['modul'] = $menu.'/'.$act;
		$attr['kd_user'] 	= $user;
		$attr['status'] = $val;
		$attr['ket'] 	= $r['nama'];
		$sql = $this->em->addInsert('acl');
		$sql = $this->em->addAttrIns($attr);
		return $sql;
	}
	
	protected function getCreateUser()
	{
		if(!empty($_POST['superUser'])){
		
			$tAcl = new Rasio_Acl;
			$acl = array();
			foreach($tAcl as $key => $row){
				$acl[$key] = $key;
			}
		
			$user = strtoupper($_POST['superUser']);
			$db = $this->em->getFind('sub', 'kd_sub', array("kd_sub = '$user'"));
			if(empty($db->kd_sub)){
				$qb[] = $this->createUser($user);
			}
			$qb[] = $this->dropAcl($user);
			
			$aMenu = $this->getPlugin('Menu')->listMenu();
			
			foreach($aMenu as $r){
				$menu = $r['url'];
				$mn = explode('-', $menu);
				$nMenu = '';
				for($i = 0; $i < count($mn); $i++){
					if($i > 0){
						$nMenu.= '-';
					}
					$nMenu.= ucfirst($mn[$i]);
				}

				if(!empty($nMenu)){
					$qb[] = $this->createAcl($user, $nMenu, 'Toleransi', '1000000', $r);
					foreach($acl as $row){
						$qb[] = $this->createAcl($user, $nMenu, $row, 1, $r);
					}
				}
			}
		}
		
		// foreach($qb as $row){
			// echo $row.';<br>';
		// }
		
		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	public function insertSetting($row)
	{
		$attr['id_setting'] = $row->no;
		$attr['setting'] 	= $row->nama;
		$attr['value'] 		= $row->value;
		$sql = $this->em->addInsert('setting');
		$sql = $this->em->addAttrIns($attr);
		return $sql;
	}
	
	public function getCreateHo()
	{
		$data = $this->em->getFind("cabang", "kd_cabang", array("kd_cabang = 'HO'"));
		if(empty($data->kd_cabang)){
			$attr['kd_cabang'] 	= 'HO';
			$attr['nm_cabang'] 	= 'HEAD OFFICE';
			$sql = $this->em->addInsert('cabang');
			$sql = $this->em->addAttrIns($attr);
			$qb[] = $sql;
			return $this->em->getFlush($qb);
		}
	
		return false;
	}
	
	protected function getSetting()
	{
		$set[1]->no 	= '1'; 
		$set[1]->nama 	= 'Tanggal Kunci'; 
		$set[1]->value 	= '01-Jan-1970'; 
		$set[1]->class 	= 'tanggal'; 
		
		$set[2]->no 	= '2'; 
		$set[2]->nama 	= 'Kunci Tanggal Aktif'; 
		$set[2]->value 	= 'T'; 
		$set[1]->class 	= 'tanggal'; 
		
		$set[3]->no 	= '3'; 
		$set[3]->nama 	= 'Jumlah Hari Toleransi'; 
		$set[3]->value 	= '30'; 
		$set[1]->class 	= 'meioMask'; 
		
		
		foreach($set as $k => $r){
			$db = $this->em->getFind('setting', 'id_setting', array("id_setting = '".$r->no."'"));
			if(empty($db->id_setting)){
				$qb[] = $this->insertSetting($r);
			}
		}

		if(count($qb) > 0){
			$save = $this->em->getFlush($qb);
		}else{
			$save = true;
		}
		return $save;
	}
	
	public function eks()
	{
		if($this->getCreate() == false){
			echo '<script>alert("Pembuatan Tabel Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if($this->getUpTable() == false){
			echo '<script>alert("Pembuatan dan Modifikasi kolom tabel Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if($this->getUpPk() == false){
			echo '<script>alert("Pembuatan Primary Key Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if($this->getUpIndex() == false){
			echo '<script>alert("Pembuatan Index Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if($this->getDelIndex() == false){
			echo '<script>alert("Penghapusan Kolom tidak terpakai Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if(!empty($_POST['delTab'])){
			if($this->getDelTable() == false){
				echo '<script>alert("Penghapusan Table tidak terpakai Gagal");</script>';
				$this->layout = 'null';
				return;
			}
		}
		if($this->getInsMenu() == false){
			echo '<script>alert("Pembuatan Menu Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if($this->getSetting() == false){
			echo '<script>alert("Setting Program Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		if($this->getCreateUser() == false){
			echo '<script>alert("Pembuatan Super User Gagal");</script>';
			$this->layout = 'null';
			return;
		}
		$this->getCreateHo();
		echo '<script>alert("Proses Sukses");</script>';
		$this->layout = 'null';
	}
}