<?php
if(count(get_included_files()) ==1) exit("Direct access not permitted.");
class pDatabase
{
    protected static $_instance = null;

    protected $_conn = null;
	
	protected function __construct() {
    }

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	public function setdb($db){
		
		if (is_null($this->_conn)) {
        	try{
            	$this->_conn = new PDO('mysql:dbname='.$db.';host='.HOST, USER, PASSWORD); 
			 	$this->_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
				$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
	        }
	        catch(PDOException $e) {  
	            $this->_conn=null;
	            die("Tidak bisa terhubung ke database");
	        }
        }
	}
	
	public function getConnection() {
		
        if (is_null($this->_conn)) {
        	try{
            	$this->_conn = new PDO('mysql:dbname='.DATABASE.';host='.HOST, USER, PASSWORD); 
			 	$this->_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
				$this->_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
	        }
	        catch(PDOException $e) {  
	            $this->_conn=null;
	            die("Tidak bisa terhubung ke database");
	        }
        }
        return $this->_conn;
    }
	public function close(){
		if (!(is_null($this->_conn))) {
			$this->_conn=null;
		}
	}
	public function begin()
	{
		$conn = $this->getConnection();
		$conn->beginTransaction();
	}

	public function commit()
	{
		$conn = $this->getConnection();
		$conn->commit();
	}

	public function rollback()
	{
		$conn = $this->getConnection();
		$conn->rollBack();
	}
	
	public function query($query,$data=array(),$id=0,$mode=0) {
        $conn = $this->getConnection();
		$sth = $conn->prepare($query);
		
		try{
			if($mode==0){
				$arrdata=array();
				for($i=0;$i<sizeof($data);$i++){
					array_push($arrdata,strip_tags(trim($data[$i])));
				}
				$data=$arrdata;
			}
			$rs=$sth->execute($data);
			if($id==1){
				if($rs){
					return $conn->lastInsertId();
				}else{
					return false;
				}
			}if($id==2){
				$rt=array("status"=>$rs,"id"=>$conn->lastInsertId());
				return $rt;
			}else{
				return true;
			}
		}catch (PDOException $e) {
			error_log($e);
		    return false;
		}
        
    }
	
	public function insert($tabel,$data=array(),$id=0,$mode=0) {
        $conn = $this->getConnection();
		try{
			$datakey=array_keys($data);
			if(sizeof($datakey)<=0) return 0;
			$datafld="";
			$datatanya="";
			
			$n=0;
			$arrdata=array();
			foreach ($datakey as $obj) {
				if($n==0){
					$datafld.='`'.$obj.'`';
					$datatanya.="?";
				}else{
					$datafld.=',`'.$obj.'`';
					$datatanya.=",?";
				}
				$datainput=NULL;
				if(isset($data[$obj])) $datainput=$data[$obj];
				if($mode==0){
					array_push($arrdata,strip_tags(trim($datainput)));
				}else if($mode==1){
					array_push($arrdata,$datainput);
				}
				
				$n++;
			}
			$sth = $conn->prepare("insert into ".$tabel." (".$datafld.") values (".$datatanya.")");
			$rs=$sth->execute($arrdata);
			if($id==1){
				if($rs){
					return $conn->lastInsertId();
				}else{
					return false;
				}
			}if($id==2){
				$rt=array("status"=>$rs,"id"=>$conn->lastInsertId());
				return $rt;
			}else{
				return true;
			}
		}catch (PDOException $e) {
			error_log($e);
		    return false;
		}
        
    }
	
	public function insertupdate($tabel,$data=array(),$dataupdate=array(),$mode=0) {
        $conn = $this->getConnection();
		try{
			$datakey=array_keys($data);
			if(sizeof($datakey)<=0) return 0;
			$datafld="";
			$datatanya="";
			
			$n=0;
			$arrdata=array();
			foreach ($datakey as $obj) {
				if($n==0){
					$datafld.='`'.$obj.'`';
					$datatanya.="?";
				}else{
					$datafld.=',`'.$obj.'`';
					$datatanya.=",?";
				}
				$datainput=NULL;
				if(isset($data[$obj])) $datainput=$data[$obj];
				if($mode==0){
					array_push($arrdata,strip_tags(trim($datainput)));
				}else if($mode==1){
					array_push($arrdata,$datainput);
				}
				
				$n++;
			}
			$datakeyupdate=array_keys($dataupdate);
			$arrupdate=array();
			$dataset=array();
			foreach ($datakeyupdate as $obj) {
				array_push($arrupdate,$obj."=?");
				if($mode==0){
					array_push($dataset,strip_tags($dataupdate[$obj]));
				}else if($mode==1){
					array_push($dataset,$dataupdate[$obj]);
				}
				
			}
			$whup=implode(",", $arrupdate);
			$arrdata=array_merge($arrdata,$dataset);
			
			$sth = $conn->prepare("insert into ".$tabel." (".$datafld.") values (".$datatanya.") 
				on duplicate key update ".$whup);
			$rs=$sth->execute($arrdata);
			return $rs;
		}catch (PDOException $e) {
			error_log($e);
		    return false;
		}
        
    }
	
	public function update($tabel,$data=array(),$id,$iddata,$mode=0) {
        $conn = $this->getConnection();
		try{
			$datakey=array_keys($data);
			if(sizeof($datakey)<=0) return 0;
			$datafld="";
			
			$n=0;
			$arrdata=array();
			foreach ($datakey as $obj) {
				if($n==0){
					$datafld.='`'.$obj.'`=?';
				}else{
					$datafld.=',`'.$obj.'`=?';
				}
				
				$datainput=NULL;
				if(isset($data[$obj])) $datainput=$data[$obj];
				if($mode==0){
					array_push($arrdata,strip_tags(trim($datainput)));
				}else if($mode==1){
					array_push($arrdata,$datainput);
				}
				
				$n++;
			}
			
			array_push($arrdata,$iddata);
			$sth = $conn->prepare("update ".$tabel." set ".$datafld." where ".$id."=?");
			$rs=$sth->execute($arrdata);
			
			return true;
		}catch (PDOException $e) {
		    error_log($e);
		    return false;
		}
        
    }
	
	public function updates($tabel,$data=array(),$id=array(),$iddata=array(),$mode=0) {
        $conn = $this->getConnection();
		try{
			$datakey=array_keys($data);
			if(sizeof($datakey)<=0) return 0;
			$datafld="";
			
			$n=0;
			$arrdata=array();
			foreach ($datakey as $obj) {
				if($n==0){
					$datafld.='`'.$obj.'`=?';
				}else{
					$datafld.=',`'.$obj.'`=?';
				}
				
				$datainput=NULL;
				if(isset($data[$obj])) $datainput=$data[$obj];
				if($mode==0){
					array_push($arrdata,strip_tags(trim($datainput)));
				}else if($mode==1){
					array_push($arrdata,$datainput);
				}
				
				$n++;
			}
			
			$whid="";
			for($i=0;$i<sizeof($id);$i++){
				if($i==0){
					$whid.=$id[$i]."=? ";
				}else{
					$whid.="and ".$id[$i]."=? ";
				}
			}
			$arrdata=array_merge($arrdata,$iddata);
			
			$sth = $conn->prepare("update ".$tabel." set ".$datafld." where ".$whid);
			$rs=$sth->execute($arrdata);
			
			return true;
		}catch (PDOException $e) {
		    error_log($e);
		    return false;
		}
        
    }
    
	public function getObj($query,$data=array())
	{
		 $conn=$this->getConnection();
		 
		 $sth = $conn->prepare($query);
		 $sth->execute($data);
		 $result = $sth->fetchAll(PDO::FETCH_CLASS, "ArrayObject");
		 return $result;
	}
	
	public function loadAssoc($query,$data=array())
	{
		 $conn=$this->getConnection();
		 $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
		 $sth = $conn->prepare($query);
		 $sth->execute($data);
		 $result = $sth->fetch(PDO::FETCH_ASSOC);
		 return $result;
	}
	
	public function loadAll($query,$data=array())
	{
		 $conn=$this->getConnection();
		 
		 $sth = $conn->prepare($query);
		 $sth->execute($data);
		 $result = $sth->fetchAll(PDO::FETCH_ASSOC);
		 return $result;
	}
	public function setAttr()
	{
		 $conn=$this->getConnection();
		 $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
		 return true;
	}
	public function jsonData($query,$data=array())
	{
		 $conn=$this->getConnection();
		 
		 $sth = $conn->prepare($query);
		 $sth->execute($data);
		 $result = $sth->fetchAll(PDO::FETCH_ASSOC);
		 //var_dump($result);
		 return json_encode($result);
	}
	public function gentoken($length) {
    	return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
	}
	public function genangka($length) {
    	return substr(str_shuffle("0123456789"), 0, $length);
	}
	public function genPassword($password) {
		//$db = Database::getInstance();
		$tpass = stripslashes($password);
		
		$salt = sha1($this->gentoken(32));
		$shpass = sha1($tpass.$salt).'$'.$salt;
		return $shpass;
	}
	
	public function replace($str)
	{
	    $from = array(
	        " ",",","&","(",")","/",".","'",":","`","!"
	    );
	    $to = array(
	        "-","","dan","","","atau","-","","","",""
	    );
	    return str_replace($from, $to, $str);
	}
	
	public function strtrim($text,$awal,$akhir){
		$batas = strrpos(substr(strip_tags($text),$awal,$akhir)," ");
		return substr(strip_tags($text), $awal,$batas).' ...';
	}
	
	public function dataSet(){
		$query = "SELECT setting FROM ".TBREF."setting WHERE id=1";
		
		$row = $this->loadAssoc($query);
		return explode("&",$row['setting']);
	}
	
	public function dataProfileweb(){
		$query = "SELECT setting FROM ".TBREF."setting WHERE id=3";
		
		$row = $this->loadAssoc($query);
		$arr=array();
		if(isset($row['setting'])){
			$arr=json_decode($row['setting'],true);
		}
		return $arr;
	}
	
	public function bruteForce(){
		$ipa = $_SERVER['REMOTE_ADDR'];
		$query = "SELECT ipaddress,waktu FROM ".TBREF."ipbrute WHERE ipaddress=? ORDER BY waktu ASC";
		
		$row = $this->getObj($query,array($ipa));
		if(sizeof($row)>0){
			$now = date('Y-m-d H:i:s');
			$dtset = $this->dataSet();
			$login_awal = strtotime($row[0]->waktu);
			$last_login = strtotime($row[sizeof($row)-1]->waktu);
	
			if((sizeof($row)>=$dtset[1])&&(($last_login+($dtset[3]*60))>strtotime($now))){
				return false;	
			}else{
				if(($last_login+($dtset[3]*60))<strtotime($now)){
					$this->del_brute($ipadd);
					return true;
				}else{
					return true;
				}
			}
		}else{
			return true;
		}
	}
	public function del_brute($ip){
		$ipa = stripslashes($ip);
		$query = "DELETE FROM ".TBREF."ipbrute WHERE ipaddress = ?";
		$rs = $this->query($query,array($ipa));
		return $rs;
	}
	public function add_brute($ip,$user){
		
		$query = "INSERT INTO ".TBREF."ipbrute (ipaddress,waktu,username)VALUES(?,NOW(),?)";
		$rs = $this->query($query,array($ip,$user));
		return $rs;
	}
	public function stsession($usr,$id,$mode=0) {
		
		$sid = $this->gentoken(32);
		$eusr = stripslashes($usr);
		$iduser = stripslashes($id);
		
		$query = "INSERT INTO ".TBREF."session (session_key,username,waktu,id_user) VALUES 
			(?,?,NOW(),?)
			ON DUPLICATE KEY UPDATE session_key=?,waktu=DATE_FORMAT(NOW(),'%Y-%m-%d;%H:%i')";
		$rs = $this->query($query,array($sid,$eusr,$iduser,$sid));

		if($rs) {
			//session_start();
			if($mode==0){
				$_SESSION['userlogin']=$sid;
				$this->sessWaktu();
			}else if($mode==1){
				$_SESSION['useradmin']=$sid;
				$this->sessWaktu(1);
			}
			return true;
		}else{
			return false;
		}
	}
	public function delSess($mode=0){
		if($mode==0){
			$sess = $_SESSION['userlogin'];
		}else if($mode==1){
			$sess = $_SESSION['useradmin'];
		}
		if(isset($_SESSION['menu_sub'])) unset($_SESSION['menu_sub']);
		
		$query = "DELETE FROM ".TBREF."session WHERE session_key = ?";
		$rs = $this->query($query,array($sess));
		if(isset($_SESSION['menu_sub'])) unset($_SESSION['menu_sub']);
		
		if($rs){
			//session_destroy();
			if($mode==0){
				unset($_SESSION['userlogin']);
				unset($_SESSION['habis']);
			}else if($mode==1){
				unset($_SESSION['useradmin']);
				unset($_SESSION['adminhabis']);
			}
			
			return true;
		}else{
			return false;
		}
	}
	public function sessWaktu($mode=0){
		$query = "SELECT setting FROM ".TBREF."setting WHERE id=1";
		$row = $this->loadAssoc($query);
		$set = $row['setting'];
		$waktu = explode("&", $set);
		if($mode==0){
			$_SESSION['habis'] = time() + ($waktu[0]*60) ;
		}else if($mode==1){
			$_SESSION['adminhabis'] = time() + ($waktu[0]*60) ;
		}
		return true;
	}
	public function adminlogin($user,$pass){
		$ipadd = $_SERVER['REMOTE_ADDR'];
		if(!$this->bruteForce()){
			return 50;
		}else{
			$us=stripslashes(strip_tags($user));
			$passw=sha1($pass);
			$query = "SELECT * FROM ".TBREF."username WHERE username = ? AND status=1";
			$row = $this->loadAssoc($query,array($user));
			$passdb = $row['password'];
			$iduser = $row['id'];
			if($row['level']==100 ){
				if($passdb!=''){
					list($pass, $salt) = explode('$', $passdb);
					$spass = sha1($passw.$salt);
					if($pass == $spass){
						$this->del_brute($ipadd);
						$sess = $this->stsession($user,$iduser,1);
						
						if($sess){
							$this->close();
							return true;
						}else{
							$this->close();
							return false;
						}
			
					}else{
						$this->add_brute($ipadd,$user);
						$this->close();
						return false;
					}
				}else{
					$this->add_brute($ipadd,$user);
					$this->close();
					return false;
				}
			}else{
				$this->add_brute($ipadd,$user);
				return false;
			}
			
		}
	}
	public function ceckpassword($us,$pass){
		$passw=sha1($pass);
		$query = "SELECT * FROM ".TBREF."username WHERE username = ? AND status=1";
		$row = $this->loadAssoc($query,array($us));
		$passdb = $row['password'];
		$iduser = $row['id'];
		if($row['level']>0 ){
			if($passdb!=''){
				list($pass, $salt) = explode('$', $passdb);
				$spass = sha1($passw.$salt);
				if($pass == $spass){
					$this->close();
					return true;
		
				}else{
					$this->close();
					return false;
				}
			}else{
				$this->close();
				return false;
			}
		}
	}
	
	public function userlogin($user,$pass){
		$ipadd = $_SERVER['REMOTE_ADDR'];
		if(!$this->bruteForce()){
			return 50;
		}else{
			$us=stripslashes(strip_tags($user));
			$passw=sha1($pass);
			$query = "SELECT * FROM ".TBREF."username WHERE username = ? AND status=1";
			$row = $this->loadAssoc($query,array($user));
			$passdb = $row['password'];
			$iduser = $row['id'];
			if($row['level']>0 ){
				if($passdb!=''){
					list($pass, $salt) = explode('$', $passdb);
					$spass = sha1($passw.$salt);
					
					if($pass == $spass){
						$this->del_brute($ipadd);
						$sess = $this->stsession($user,$iduser);
						
						if($sess){
							$this->close();
							return true;
	
						}else{
							$this->close();
							return 0;
						}
			
					}else{
						$this->add_brute($ipadd,$user);
						$this->close();
						return 2;
					}
				}else{
					$this->add_brute($ipadd,$user);
					$this->close();
					return 2;
				}
			}else{
				$this->add_brute($ipadd,$user);
				return 3;
			}
			
		}
	}
	
	public function ceckUser(){
		if(!isset($_SESSION['userlogin'])){
			return false;
		}else if(time()>$_SESSION['habis']){
			$del=$this->delSess();
			
			if($del) return false;
		}else{
			$session=$_SESSION['userlogin'];
			$query="SELECT COUNT(*) as total,t2.level FROM ".TBREF."session as t1
				INNER JOIN ".TBREF."username as t2 ON t1.id_user = t2.id
				WHERE session_key=?";
			$rs=$this->loadAssoc($query,array($session));
			if($rs['level']>=1 ){
				$this->sessWaktu();
				return true;
			}else{
				return false;
			}
		}
	}
	public function ceckadmin(){
		if(!$this->ceckUser()) return false;
		if($_SESSION['profile']['level']<100) return false;
		return true;
	}
	
	public function getid($mode=0)
	{
		$session="";
		if($mode==0){
			if(!isset($_SESSION['userlogin'])) return false;
			$session=$_SESSION['userlogin'];
		}else if($mode==1){
			if(!isset($_SESSION['useradmin'])) return false;
			$session=$_SESSION['useradmin'];
		}
		
		$session=stripslashes($session);
		$query="SELECT * FROM ".TBREF."session WHERE session_key=?";
		$rs=$this->loadAssoc($query,array($session));
		return $rs['id_user'];
	}
	public function getemail($mode=0)
	{
		$session="";
		if($mode==0){
			if(!isset($_SESSION['userlogin'])) return false;
			$session=$_SESSION['userlogin'];
		}else if($mode==1){
			if(!isset($_SESSION['useradmin'])) return false;
			$session=$_SESSION['useradmin'];
		}
		
		$session=stripslashes($session);
		$query="SELECT t2.email FROM ".TBREF."session as t1 
			INNER JOIN ".TBREF."username as t2 ON t1.id_user=t2.id
			WHERE session_key=?";
		$rs=$this->loadAssoc($query,array($session));
		return $rs['email'];
	}
	
	public function getProfile($mode=0){
		$userid=$this->getid($mode);
		
		$query="SELECT t1.`id`,
				t1.`username`,
				t1.`level`,
				t1.`status`,
				t1.`nama`,
				t1.idpegawai,
				t2.nama as namalevel,
				t2.pegawai,
				t2.peserta,
				if(t3.idjabatanstruk is null,0,t3.idjabatanstruk) as idjabatanstruk,
				if(t3.idjabatanfung is null,0,t3.idjabatanfung) as idjabatanfung
				FROM tb_username as t1
			inner join tb_level as t2 on t1.level=t2.id	
			left join tb_pegawai as t3 on t1.idpegawai=t3.id
			WHERE t1.id=? AND t1.status=1";
		$hasil=$this->loadAssoc($query,array($userid));
		return $hasil;
	}
	
	public function ceckmodule($mod){
		
		$hasil=false;
		if(isset($_SESSION['profile']) && $_SESSION['profile']['level']==100){
			$query="select id from tb_module where module=? and (level=0 or level=100) and status=1";
			$rs=$this->loadAssoc($query,array($mod));
			if(isset($rs['id'])){
				$hasil=true;
			}else{
				$query="select t1.id from tb_module as t1
					inner join tb_module_akses as t2 on t1.id=t2.idmodule
					where t1.module=? and t2.level=? and t1.status=1";
				$rs=$this->loadAssoc($query,array($mod,$_SESSION['profile']['level']));
				if(isset($rs['id'])){
					$hasil=true;
				}
			}
		}else{
			$query="select id from tb_module where module=? and level=0 and status=1";
			$rs=$this->loadAssoc($query,array($mod));
			if(isset($rs['id'])){
				$hasil=true;
			}else{
				if(!isset($_SESSION['profile'])) return false;
				$query="select t1.id from tb_module as t1
					inner join tb_module_akses as t2 on t1.id=t2.idmodule
					where t1.module=? and t2.level=? and t1.status=1";
				$rs=$this->loadAssoc($query,array($mod,$_SESSION['profile']['level']));
				if(isset($rs['id'])){
					$hasil=true;
				}
				
			}
		}
		
		return $hasil;
	}
	
	public function getLevel()
	{
		$id=$this->getid(1);
		$query = "SELECT * FROM ".TBREF."username WHERE id=? AND status=1";
		$rs=$this->loadAssoc($query,array($id));
		return $rs['level'];
	}
	
	public function cekstatusakses($mod,$idstatus,$md=0){
		$hasil=false;
		$idmodule=0;
		if($md==0){
			$idmodule=$this->getidmodule($mod);
		}else if($md==1){
			$idmodule=$this->getidmodulenama($mod);
		}else if($md==2){
			$idmodule=$mod;
		}
		$hasil=false;
		$query="select id from tb_master_status_module where idmodule=? and idstatus=?";
		$rsc=$this->loadAssoc($query,array($idmodule,$idstatus));
		if(isset($rsc['id'])) $hasil=true;
		return $hasil;
	}
	
	public function cekstatusedit($mod,$idstatus,$md=0){
		$hasil=false;
		$idmodule=0;
		if($md==0){
			$idmodule=$this->getidmodule($mod);
		}else if($md==1){
			$idmodule=$this->getidmodulenama($mod);
		}else if($md==2){
			$idmodule=$mod;
		}
		$hasil=false;
		$query="select id from tb_master_status_module where idmodule=? and idstatus=?";
		$rsc=$this->loadAssoc($query,array($idmodule,$idstatus));
		if(isset($rsc['id'])) $hasil=true;
		
		$query="select id from tb_master_status_level where idlevel=? and idstatus=? and mode=0";
		$rsc=$this->loadAssoc($query,array($_SESSION['profile']['level'],$idstatus));
		if(!isset($rsc['id'])) $hasil=false;
		return $hasil;
	}
	
	public function d_date($a,$delimiter="/"){
		$awal = "0000-00-00";
		if(sizeof(explode($delimiter, $a))==3){
			list($d,$m,$y) = explode($delimiter, $a);
			if(is_numeric($d) && is_numeric($m) && is_numeric($y)){
				$awal = $y."-".$m."-".$d;
			}
		}
		return $awal;	
	}
	public function sql_date($a,$bt="/"){
		$awal = "00/00/0000";
		
		if(sizeof(explode('-', $a))==3){
			list($y,$m,$d) = explode('-', $a);
			if(is_numeric($d) && is_numeric($m) && is_numeric($y)){
				$awal = $d.$bt.$m.$bt.$y;
			}
		}
		return $awal;	
	}
	
	public function fulldate($a){
		$bulan=array("Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember");
		$awal = "............................";
		$arr=explode(" ", $a);
		
		if(sizeof($arr)<=0) return $awal;
		
		$waktu="";
		if(sizeof($arr)==2) $waktu=" ".$arr[1];
		if(sizeof(explode('-', $arr[0]))==3){
			list($y,$m,$d) = explode('-', $arr[0]);
			if(is_numeric($d) && is_numeric($m) && is_numeric($y)){
				$awal = $d." ".$bulan[((int) $m)-1]." ".$y.$waktu;
			}
		}
		
		return $awal;	
	}
	
	public function halfdate($a){
		$bulan=array("JAN","FEB","MAR","APR","MEI","JUN","JUL","AGU","SEP","OKT","NOV","DES");
		$awal = "............................";
		$arr=explode(" ", $a);
		
		if(sizeof($arr)<=0) return $awal;
		
		$waktu="";
		if(sizeof($arr)==2) $waktu=" ".$arr[1];
		if(sizeof(explode('-', $arr[0]))==3){
			list($y,$m,$d) = explode('-', $arr[0]);
			if(is_numeric($d) && is_numeric($m) && is_numeric($y)){
				$awal = $d." ".$bulan[((int) $m)-1]." ".$y.$waktu;
			}
		}
		
		return $awal;	
	}
	
	public function ceckeks($jenis,$eks){
		$hasil=false;
		$query="SELECT ekstensi FROM tb_upload_jenis WHERE id=?";
		$rs=$this->loadAssoc($query,array($jenis));
		$arreks=array();
		if(isset($rs['ekstensi'])){
			$arreks=explode(",", $rs['ekstensi']);
			for($i=0;$i<sizeof($arreks);$i++){
				if(strtolower($eks)==strtolower($arreks[$i])){
					$hasil=true;
				}
			}
		}
		return $hasil;
	}
	
	
	public function hapusdokumen($id){
		$wh="";
		$datapush=array($id);	
		if($_SESSION['profile']['level']<10){
			$wh.="and iduser=? ";
			array_push($datapush,$_SESSION['profile']['id']);
		}
		$query="select * from tb_dokumen where id=? ".$wh;
		$rsdok=$this->loadAssoc($query,$datapush);
		
		if(!isset($rsdok['id'])) return false;
		$path=PATHFTP.$rsdok['folder'].$rsdok['nama_baru'];
		$ftpstream = ftp_connect("localhost");
		$login = ftp_login($ftpstream, FTPUSER, FTPPASSWORD);
		
		$statushapus=true;
		if($login){
			$listing = @ftp_nlist($ftpstream, $path);
			if($listing === FALSE){
				$statushapus=false;
			}else{
				$hapus=ftp_delete($ftpstream , $path );
			}
			
			if($rsdok['thumb']==1 && $statushapus){
				$paththumb=PATHFTP.$rsdok['folder'].'thumb/'.$rsdok['nama_baru'];
				$listingthumb = @ftp_nlist($ftpstream, $paththumb);
				
				if($listingthumb === FALSE){
					$statushapus=false;
				}else{
					$hapus=ftp_delete($ftpstream , $paththumb );
				}
			}
		}else{
			$statushapus=false;
		}
		ftp_close($ftpstream);
		if($statushapus){
			$this->query("delete from tb_dokumen where id=? ",array($id));
		}
		return $statushapus;
	}
	
	public function datacari($data,$arrcr){
		$datapush=array();
		$wh="";
		for($i=0;$i<sizeof($arrcr);$i++){
			$arrkunci=explode("=", $arrcr[$i]);
			if(sizeof($arrkunci)==2){
				if (in_array($arrkunci[0], $data['kunci'], true)) {
				    $ind=array_search($arrkunci[0],$data['kunci']);
					$arrkolom=$data['kolom'];
					
					$jenis="LIKE";
					$mode=0;
					
					if(isset($data['jenis'][$arrkunci[0]])){
						$arrjenis=$data['jenis'][$arrkunci[0]];
						if(isset($arrjenis['tipe'])){
							$jenis=$arrjenis['tipe'];
						}
						if(isset($arrjenis['jenis'])){
							if($arrjenis['jenis']=="tanggal"){
								$mode=1;
							}else if($arrjenis['jenis']=="umur"){
								$mode=2;
							}
						}
					}
					
					if($mode==0){
						$caristr="%$arrkunci[1]%";
						$wh.="AND ".$arrkolom[$ind]." $jenis ? ";
						if($jenis=="="){
							$caristr=$arrkunci[1];
						}else if($jenis=="<"){
							$caristr<$arrkunci[1];
						}else if($jenis=="<="){
							$caristr<=$arrkunci[1];
						}else if($jenis==">"){
							$caristr>$arrkunci[1];
						}else if($jenis==">="){
							$caristr>=$arrkunci[1];
						}else if($jenis=="!="){
							$caristr!=$arrkunci[1];
						}
						array_push($datapush,$caristr);
					}else if($mode==1){
						$caristr="%$arrkunci[1]%";
						$wh.="AND ".$arrkolom[$ind]." $jenis ? ";
						$tanggal=$this->d_date($arrkunci[1]);
						$caristr="%$tanggal%";
						if($jenis=="="){
							$caristr=$tanggal;
						}else if($jenis==">="){
							$caristr=$tanggal;
						}else if($jenis=="<="){
							$caristr=$tanggal;
						}
						array_push($datapush,$caristr);
					}else if($mode==2){
						
						$arraum=explode("-", $arrkunci[1]);
						if(sizeof($arraum)==2){
							$wh.="AND (TIMESTAMPDIFF(YEAR, ".$arrkolom[$ind].", CURDATE())>=? AND TIMESTAMPDIFF(YEAR, ".$arrkolom[$ind].", CURDATE())<=?) ";
							array_push($datapush,$arraum[0],$arraum[1]);
						}else{
							$wh.="AND TIMESTAMPDIFF(YEAR, ".$arrkolom[$ind].", CURDATE())=? ";
							array_push($datapush,$arraum[0]);
						}
						//$caristr=$this->d_date($arrkunci[1]);
					}
					
				}	
			}
		}
		return array("query"=>$wh,"datapush"=>$datapush);
	}

	
	public function cekupload($jenis,$ext)
	{
		$hasil=false;
		$query="select * from tb_jenis_konten where id=?";
		$rs=$this->loadAssoc($query,array($jenis));
		if(isset($rs['tipefile'])){
			$tipe=explode(",", $rs['tipefile']);
			if(in_array(strtolower($ext),$tipe)) $hasil=true;
		}
		return $hasil;
	}
	
	public function cekaksesuploadmodule($module,$ext){
		$hasil=false;
		$query="select t1.idmodule,t1.idjenis,t3.tipefile from tb_module_upload as t1
			inner join tb_module as t2 on t1.idmodule=t2.id
			inner join tb_jenis_konten as t3 on t1.idjenis=t3.id
			where (t2.module=? or t2.id=?)";
		$rsmod=$this->loadAll($query,array($module,$module));
		foreach ($rsmod as $obj) {
			$tipe=explode(",", $obj['tipefile']);
			if(in_array(strtolower($ext),$tipe)) $hasil=true;
		}
		return $hasil;
	}
	
	public function cekuploadmodule($module,$ext){
		$hasil=false;
		$query="select t1.idmodule,t1.idjenis,t3.tipefile from tb_module_upload as t1
			inner join tb_module as t2 on t1.idmodule=t2.id
			inner join tb_jenis_konten as t3 on t1.idjenis=t3.id
			where (t2.module=? or t2.id=?)";
		$rsmod=$this->loadAll($query,array($module,$module));
		foreach ($rsmod as $obj) {
			$tipe=explode(",", $obj['tipefile']);
			if(in_array(strtolower($ext),$tipe)) $hasil=true;
		}
		return $hasil;
	}
	
	public function getfolder($jenis)
	{
		$hasil="";
		$query="select * from tb_jenis_konten where id=?";
		$rs=$this->loadAssoc($query,array($jenis));
		if(isset($rs['folder'])){
			$hasil=$rs['folder'];
		}
		return $hasil;
	}
	

	public function renderdata($obj,$data)
	{
		$newline=$obj->data;
		$search = "/<data>(.*?)<\/data>/s";
		preg_match_all($search, $newline, $matches);
		if(sizeof($matches)==2){
			for($i=0;$i<sizeof($matches[1]);$i++){
				$repl="null";
				if(isset($data[$matches[1][$i]])){
					
					$repl=$data[$matches[1][$i]];
				}
				$newline=str_replace($matches[0][$i], $repl, $newline);
			}
		}
		
		$searchkotak = "/<kotak>(.*?)<\/kotak>/s";
		preg_match_all($searchkotak, $newline, $matches);
		if(sizeof($matches)==2){
			for($i=0;$i<sizeof($matches[1]);$i++){
				$arrrp=explode(":", $matches[1][$i]);
				$strrepl="";
				if(isset($data[$arrrp[0]])){
					$strrepl=$data[$arrrp[0]];
				}
				
				$jumlah=strlen($strrepl);
				if(sizeof($arrrp)>0 && $arrrp[1]>0){
					$jumlah=$arrrp[1];
				}
				if(sizeof($arrrp)==3 && $arrrp[2]>0){
					$strrepl=$this->buatdigit($strrepl, $arrrp[2]);
				}
				$jumlahstr=strlen($strrepl);
				$repl="";
				for($n=0;$n<$jumlah;$n++){
					if($strrepl[$n]=="" || $n>$jumlahstr || trim($strrepl[$n])==""){
						$repl.="<span class='kotak'>&nbsp;</span>";
					}else{
						$hasilrpl=$strrepl[$n];
						
						$repl.="<span class='kotak'>".$hasilrpl."</span>";
					}
				}
				
				$newline=str_replace($matches[0][$i], $repl, $newline);
			}
		}
		
		$searchtanda = "/<tanda>(.*?)<\/tanda>/s";
		preg_match_all($searchtanda, $newline, $matches);
		if(sizeof($matches)==2){
			for($i=0;$i<sizeof($matches[1]);$i++){
				$repl="";
				if(strtolower($matches[1][$i])=="x"){
					$repl="*";
				}else if(strtolower($matches[1][$i])=="+"){
					$repl="+";
				}else if(strtolower($matches[1][$i])=="-"){
					$repl="-";
				}else if(strtolower($matches[1][$i])=="/"){
					$repl="/";
				}
				$newline=str_replace($matches[0][$i], $repl, $newline);
			}
		}
		$search = "/<@hasiluji id=\"(.*?)\">(.*?)<\/@hasiluji>/s";
		preg_match_all($search, $newline, $matches);
		
		if(sizeof($matches)==3){
			for($i=0;$i<sizeof($matches[1]);$i++){
				if($matches[1][$i]=="hasilsatuan"){
					$repl="null";
					if(isset($data['hasiluji']['hasil'][$matches[2][$i]])){
						$hasiluji=$data['hasiluji']['hasil'][$matches[2][$i]];
						$datahasil=array();
						foreach ($hasiluji as $obs) {
							array_push($datahasil,$obs['hasil']." ".$obs['satuan']);
						}
						$repl=implode("<br/>", $datahasil);
					}
					
				}
				if($matches[1][$i]=="hasil"){
					$repl="null";
					if(isset($data['hasiluji']['hasil'][$matches[2][$i]])){
						$hasiluji=$data['hasiluji']['hasil'][$matches[2][$i]];
						$datahasil=array();
						foreach ($hasiluji as $obs) {
							array_push($datahasil,$obs['hasil']);
						}
						$repl=implode("<br/>", $datahasil);
					}
					
				}
				if($matches[1][$i]=="satuan"){
					$repl="null";
					if(isset($data['hasiluji']['hasil'][$matches[2][$i]])){
						$hasiluji=$data['hasiluji']['hasil'][$matches[2][$i]];
						$datahasil=array();
						foreach ($hasiluji as $obs) {
							array_push($datahasil,$obs['satuan']);
						}
						$repl=implode("<br/>", $datahasil);
					}
					
				}
				$newline=str_replace($matches[0][$i], $repl, $newline);
			}
		}
		
		$searchformula = "/<formula>(.*?)<\/formula>/s";
		preg_match_all($searchformula, $newline, $matches);
		if(sizeof($matches)==2){
			for($i=0;$i<sizeof($matches[1]);$i++){
				$repl="";
				$newline=str_replace($matches[0][$i], $this->calculate_string($matches[1][$i]), $newline);
			}
			
		}
		
		$search2 = "/<cb>(.*?)<\/cb>/s";
		preg_match_all($search2, $newline, $matchecb);
		if(sizeof($matchecb)==2){
			for($i=0;$i<sizeof($matchecb[1]);$i++){
				
				$repl="";
				if(isset($data[$matchecb[1][$i]])){
					if($data[$matchecb[1][$i]]==1){
						$repl="<div style='position:absolute;left:8px;'>X</div>";
					}
					
				}
				$newline=str_replace($matchecb[0][$i], $repl, $newline);
			}
		}
		
		
		return str_replace("null", "", $newline);
	}
	
	public function buatkotak($str,$jumlah,$class="kotak"){
		$repl="";
		$strrepl=$str;
		$jumlahstr=strlen($strrepl);
		
		for($n=0;$n<$jumlah;$n++){
			if($strrepl[$n]=="" || $n>$jumlahstr || trim($strrepl[$n])==""){
				$repl.="<span class='".$class."'>&nbsp;</span>";
			}else{
				$repl.="<span class='".$class."'>".$strrepl[$n]."</span>";
			}
		}
		
		return $repl;
	}
	
	public function buatkotaksilang($str,$tanda,$jumlah,$class="kotak"){
		$repl="";
		
		for($n=0;$n<$jumlah;$n++){
			$dispay="display:none";
			if($str==($n+1)){
				$dispay="display:block";
			}
			$repl.="<span class='".$class."'><span style='$dispay;' class='silangposisi'>".$tanda."</span>".($n+1)."</span>";
		}
		
		return $repl;
	}
	
	public function buatdigit($data,$jumlah,$tb="0")
	{
		if($jumlah<strlen($data)) {
			return $data;
		}
		
		$sl=$jumlah-strlen($data);
		
		$dp="";
		for($i=0;$i<$sl;$i++){
			$dp.=$tb;
		}
		return $dp.$data;
	}
	
	
	
	public function lihatsess()
	{
		if(!isset($_SESSION['userlogin'])){
			return false;
		}else if(time()>$_SESSION['habis']){
			$del=$this->delSess();
			return false;
		}else{
			$session=$_SESSION['userlogin'];
			$query="SELECT t2.level FROM tb_session as t1
				INNER JOIN tb_username as t2 ON t1.id_user = t2.id
				WHERE session_key=?";
			$rs=$this->loadAssoc($query,array($session));
			
			if($rs['level']>0 ){
				return true;
			}else{
				return false;
			}
		}
	}
	public function calculate_string($mathString)    {
		
		$mathString = trim($mathString);     // trim white spaces
		$mathString= str_replace("null", "0", $mathString);
		$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators
		try{
			$compute = create_function("", "return (" . str_replace(",", ".", $mathString) . ");" );
			$hasil=0 + $compute();
			if($hasil==0) $hasil="-";
			return $hasil;
		}catch (Exception $e) {
			return "";
		}
		
	}
	
	public function getidmodule($mod)
	{
		$hasil=0;
		$query="select * from tb_module where module=?";
		$rs=$this->loadAssoc($query,array($mod));
		if(isset($rs['id'])){
			$hasil=$rs['id'];
		}
		return $hasil;
	}
	public function getidmodulenama($mod)
	{
		$module=substr($mod, 4,strlen($mod));
		$hasil=0;
		$query="select * from tb_module where module=?";
		$rs=$this->loadAssoc($query,array($module));
		if(isset($rs['id'])){
			$hasil=$rs['id'];
		}
		return $hasil;
	}
	
	public function notin($data,$wh,$dtpush,$col="id"){
		$whe=$wh;
		$datapush=$dtpush;
		$tt="";
		
		for($i=0;$i<sizeof($data);$i++){
			if($i==0){
				$tt.="?";
			}else{
				$tt.=",?";
			}
			array_push($datapush,$data[$i]);
		}
		if(sizeof($data)>0){
			$whe.="and $col not in ($tt) ";
		}
		
		return array("where"=>$whe,"datapush"=>$datapush);
	}
	
	
	public function gettahun($tanggal){
		return date('Y', strtotime($tanggal));
	}
	
	public function getbulan($tanggal){
		return date('n', strtotime($tanggal));
	}
	
	public function getnamabulan($no,$mode=0){
		$hasil="";
		$query="select * from tb_bulan where id=?";
		$rsb=$this->loadAssoc($query,array($no));
		if(isset($rsb['nama'])){
			if($mode==0){
				$hasil=$rsb['nama'];
			}else if($mode==1){
				$hasil=$rsb['rom'];
			}
			
		}
		return $hasil;
	}
	
	public function gethari($tgl){
		$arrd=array("Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");	
		$day = date('w', strtotime($tgl));
		return $arrd[$day];
	}
	
	public function angkahuruf($data,$mode=0)
	{
		
		$arrangka=array("","Satu","Dua","Tiga","Empat","Lima","Enam","Tujuh","Delapan","Sembilan");
		$arrfinal=array("Ribu","Juta","Milyar");
		
		$hasil="";
		$jumlah=strlen($data);
		$arrdata=str_split(strrev($data),3);
		$sub=strrev($arrdata[sizeof($arrdata)-1]);
		$a1="";
		$pj=sizeof($arrdata);
		
		$huruf=array();
		
		$minus=2;
		for($i=(sizeof($arrdata)-1);$i>=0;$i--){
			$subangka=strrev($arrdata[$i]);
			$pjs=strlen($subangka);
			
			for($n=0;$n<$pjs;$n++){
				$angka=$arrangka[$subangka[$n]]." ";
				if(($pjs-$n)==3){
					$a1="Ratus";
					if($subangka[$n]==1){
						$angka="Se";
						$a1="ratus";
					}else if($subangka[$n]==0){
						$angka="";
						$a1="";
					}
				}else if(($pjs-$n)==2){
					$a1="Puluh";
					if($subangka[$n]==1){
						$angka="Se";
						$a1="";
						if($subangka[$n+1]==0){
							$a1="puluh";
						}else if($subangka[$n+1]==1){
							$a1="belas";
						}else{
							$angka=$arrangka[$subangka[$n+1]]." ";
							$a1="Belas";
							$n++;
							
						}
					}else if($subangka[$n]==0){
						$angka="";
						$a1="";
					}else{
						$angka=$arrangka[$subangka[$n]]." ";
					}
				}else if(($pjs-$n)==1){
					if($subangka[$n-1]==1){
						$angka="";
					}
					$a1=" ";
				}else{
					$angka="";
					$a1="";
				}
				if($a1!="" && $angka!=""){
					array_push($huruf,$angka.$a1);
				}
				
			}
			$nf=$pj-$minus;
			
			if($nf>=0){
				$blok=strrev($arrdata[$i]);
					
				if((int) $blok>0) {
					array_push($huruf,$arrfinal[$nf]);
				}
			}
			$minus++;
		}
		if($mode==1){
			array_push($huruf,"Rupiah");
		}
		
		for($i=0;$i<sizeof($huruf);$i++){
			if($i==0){
				$hasil.=$huruf[$i];
			}else if($i==(sizeof($huruf)-1)){
				$hasil.=" ".$huruf[$i];
			}else{
				$hasil.=" ".$huruf[$i];
			}
		}
		return $hasil;
	}

	
	public function kirimemail($tujuan,$subject,$isi){
		for($i=0;$i<sizeof($tujuan);$i++){
			$query="insert into tb_kirim_email (tanggal,email,subject,pesan) values (NOW(),?,?,?)";
			$rsjob=$this->query($query,array($tujuan[$i],$subject,$isi),1);
			if($rsjob>0) shell_exec("nohup python ".HOMEDIR."py/mail.py $rsjob > /dev/null 2>&1 &");
		}
	}
	
	
	public function cekstatusmodule($idmodule,$status){
		$hasil=false;
		$query="select t1.id from tb_master_status as t1
			inner join tb_master_status_module as t2 on t1.id=t2.idstatus
			where t1.status=1 and t1.id=? and t2.idmodule=? ";
		$rsc=$this->loadAssoc($query,array($status,$idmodule));
		if(isset($rsc['id'])) $hasil=true;
		return $hasil;
	}
	
	public function getkategoriinformasi($id){
		$query="select * from tb_konten_kategori where id=?";
		return $this->loadAssoc($query,array($id));
	}
	
	
	public function getdatasetting()
	{
		$arrsett=array();
		$query="select * from tb_setting where id=3";
		$rsst=$this->loadAssoc($query);
		if(isset($rsst['id'])){
			$arrsett=json_decode($rsst['setting'],true);
		}
		
		return $arrsett;
	}
	
	public function whnotin($dataid,$nama="id")
	{
		$hasil="";
		$arrtanya=array();
		for($i=0;$i<sizeof($dataid);$i++){
			array_push($arrtanya,"?");
		}
		
		if(sizeof($dataid)>0) $hasil="and ".$nama." not in (".implode(",", $arrtanya).") ";
		return $hasil;
	}
	
	public function whinor($dataid,$wh)
	{
		$hasil="";
		$arrtanya=array();
		for($i=0;$i<sizeof($dataid);$i++){
			array_push($arrtanya,"?");
		}
		
		if(sizeof($dataid)>0) $hasil=$wh." (".implode(",", $arrtanya).") ";
		return $hasil;
	}
	
	public function extmoduleupload($idmodule){
		$hasil="";
		$query="select group_concat(distinct t2.tipefile) as tipefile 
				from tb_module_upload as t1
			inner join tb_jenis_konten as t2 on t1.idjenis=t2.id
			where t1.idmodule=? group by t1.id";
		$rs=$this->loadAssoc($query,array($idmodule));
		if(isset($rs['tipefile'])){
			$arr=explode(",", $rs['tipefile']);
			$arruq=array_unique($arr);
			$hasil=implode(",", $arruq);
		}
		return $hasil;
	}
	
	public function getdatastatus($status){
		$hasil="";
		$query="SELECT *
			FROM tb_master_status
			WHERE id=? ";
		$hasil=$this->loadAssoc($query,array($status));
		return $hasil;
	}
	
	public function getemailmodule($mod,$mode=1,$user=0){
		$hasil=array();
		$idmodule=0;
		if($mode==1){
			$idmodule=$this->getidmodule($mod);
		}else if($mode==2){
			$idmodule=$this->getidmodulenama($mod);
		}else if($mode==3){
			$idmodule=$mod;
		}
		
		$query="select t1.id,t2.email from tb_module_akses as t1
			inner join tb_username as t2 on t1.level=t2.level
			where t1.idmodule=? and t1.level>10";
		$rs=$this->loadAll($query,array($idmodule));
		if(sizeof($rs)>0){
			foreach ($rs as $obj) {
				array_push($hasil,$obj['email']);
			}
		}
		
		if($user==1){
			$query="select t1.id,t2.email from tb_module_akses as t1
				inner join tb_username as t2 on t1.level=t2.level
				where t1.idmodule=? and t2.id=?";
			$rs=$this->loadAll($query,array($idmodule,$_SESSION['profile']['id']));
			if(sizeof($rs)>0){
				foreach ($rs as $obj) {
					array_push($hasil,$obj['email']);
				}
			}
		}
		
		return $hasil;
	}
	
	public function uanghuruf($data)
	{
		
		$arrangka=array("","Satu","Dua","Tiga","Empat","Lima","Enam","Tujuh","Delapan","Sembilan");
		$arrfinal=array("Ribu","Juta","Milyar");
		
		$hasil="";
		$jumlah=strlen($data);
		$arrdata=str_split(strrev($data),3);
		$sub=strrev($arrdata[sizeof($arrdata)-1]);
		$a1="";
		$pj=sizeof($arrdata);
		
		$huruf=array();
		
		$minus=2;
		for($i=(sizeof($arrdata)-1);$i>=0;$i--){
			$subangka=strrev($arrdata[$i]);
			$pjs=strlen($subangka);
			
			for($n=0;$n<$pjs;$n++){
				$angka=$arrangka[$subangka[$n]]." ";
				if(($pjs-$n)==3){
					$a1="Ratus";
					if($subangka[$n]==1){
						$angka="Se";
						$a1="ratus";
					}else if($subangka[$n]==0){
						$angka="";
						$a1="";
					}
				}else if(($pjs-$n)==2){
					$a1="Puluh";
					if($subangka[$n]==1){
						$angka="Se";
						$a1="";
						if($subangka[$n+1]==0){
							$a1="puluh";
						}else if($subangka[$n+1]==1){
							$a1="belas";
						}else{
							$angka=$arrangka[$subangka[$n+1]]." ";
							$a1="Belas";
							$n++;
							
						}
					}else if($subangka[$n]==0){
						$angka="";
						$a1="";
					}else{
						$angka=$arrangka[$subangka[$n]]." ";
					}
				}else if(($pjs-$n)==1){
					if($subangka[$n-1]==1){
						$angka="";
					}
					$a1=" ";
				}else{
					$angka="";
					$a1="";
				}
				if($a1!="" && $angka!=""){
					array_push($huruf,$angka.$a1);
				}
				
			}
			$nf=$pj-$minus;
			
			if($nf>=0){
				$blok=strrev($arrdata[$i]);
					
				if((int) $blok>0) {
					array_push($huruf,$arrfinal[$nf]);
				}
			}
			
			$minus++;
		}
		
		array_push($huruf,"Rupiah");
		
		for($i=0;$i<sizeof($huruf);$i++){
			if($i==0){
				$hasil.= $huruf[$i];
			}else if($i==(sizeof($huruf)-1)){
				$hasil.=" ".$huruf[$i];
			}else{
				$hasil.=" ".$huruf[$i];
			}
		}
		
		
		
		return $hasil;
	}

	public function gethalaman($hal){
		$hasil=array("status"=>1,"nama"=>"Halaman");
		
		$level=0;
		if(isset($_SESSION['profile']['level'])) $level=$_SESSION['profile']['level'];
		
		$query="select t1.id,t1.nama,t1.halaman 
			from tb_halaman as t1
			where t1.status=1 and t1.level<=? and t1.halaman=? ";
			
		$rs=$this->loadAssoc($query,array($level,$hal));
		
		if(!isset($rs['id'])) {
			$hasil['status']=0;
		}else{
			$hasil['nama']=$rs['nama'];
		}
		return $hasil;
	}
	
	public function gennomororder(){
		date_default_timezone_set('Asia/Jakarta');
		$tahun=date("Y");
		$bulan=date("m");
		$nomorurut=1;
		$qr="select max(nourut) nourut from tb_order where id>0 and tahun=? ";
		$rsn=$this->loadAssoc($qr,array($tahun));
		if(isset($rsn['nourut'])){
			$nomorurut=$rsn['nourut']+1;
		}
		
		$nomororder=$tahun.".".$bulan.".".$nomorurut;
		$hasil=array("nourut"=>$nomorurut,"noorder"=>$nomororder,"tahun"=>$tahun);
		return $hasil;
	}
	
	public function gennomornota($tanggal){
		date_default_timezone_set('Asia/Jakarta');
		$tahun=date("Y");
		$bulan=date("m");
		$arrtahun=explode("-", $tanggal);
		if(sizeof($arrtahun)==3){
			$tahun=$arrtahun[0];
			$bulan=$arrtahun[1];
		}
		
		$nomorurut=1;
		$qr="select max(nourut) nourut from tb_order_bayar where id>0 and tahun=? ";
		$rsn=$this->loadAssoc($qr,array($tahun));
		if(isset($rsn['nourut'])){
			$nomorurut=$rsn['nourut']+1;
		}
		$nomornota=$tahun.".".$bulan.".".$nomorurut;
		return array("tahun"=>$tahun,"nourut"=>$nomorurut,"nomor"=>$nomornota);
	}
	
	public function getiddiposisi($idsurat,$mode=0){
		date_default_timezone_set('Asia/Jakarta');
		$hasil=array("iddisposisi"=>0,"statusdisposisi"=>0);
		
		$query="select * from tb_suratbdk where id=? ";
		$rss=$this->loadAssoc($query,array($idsurat));
		if(!isset($rss['id'])) return false;
		if($mode==0){
			$query="select t1.id from tb_master_disposisi_status as t1
				inner join tb_master_disposisi as t2 on t1.iddisposisi=t2.id
				where t2.idjenissurat=? 
				order by t1.urutan asc limit 0,1";
			$rsd=$this->loadAssoc($query,array($rss['idjenissurat']));
			if(!isset($rsd['id'])) return false;
			$hasil['statusdisposisi']=1;
			$hasil['iddisposisi']=$rsd['id'];
		}else if($mode==1){
			$query="select t1.id,t2.urutan from tb_suratbdk_disposisi as t1
				inner join tb_master_disposisi_status as t2 on t1.iddisposisi=t2.id
				where t1.idsurat=? order by t1.tanggal desc limit 0,1";
			$rssurat=$this->loadAssoc($query,array($idsurat));
			if(!isset($rssurat['id'])){
				$query="select t1.id from tb_master_disposisi_status as t1
					inner join tb_master_disposisi as t2 on t1.iddisposisi=t2.id
					where t2.idjenissurat=?
					order by t1.urutan asc limit 0,1";
				$rsd=$this->loadAssoc($query,array($rss['idjenissurat']));
				if(!isset($rsd['id'])) return false;
				$hasil['statusdisposisi']=1;
				$hasil['iddisposisi']=$rsd['id'];
			}else{
				$query="select t1.id from tb_master_disposisi_status as t1
					inner join tb_master_disposisi as t2 on t1.iddisposisi=t2.id
					where t2.idjenissurat=? and t1.urutan>?
					order by t1.urutan asc limit 0,1";
				$rsd=$this->loadAssoc($query,array($rss['idjenissurat'],$rssurat['urutan']));
				if(!isset($rsd['id'])){
					$hasil['statusdisposisi']=0;
				}else{
					$hasil['statusdisposisi']=1;
					$hasil['iddisposisi']=$rsd['id'];
				}
			}
		}
		
		return $hasil;
	}
	
	public function setdatadisposisiawal($idsurat)
	{
		$hasil=array("status"=>0,"pesan"=>[["pesan"=>"Terjadi kesalahan"]],"data"=>array());
		
		$query="delete from tb_suratbdk_disposisi where idsurat=? ";
		$rsdel=$this->query($query,array($idsurat));
		
		$query="select t1.id,
				t1.idjenissurat,
				t1.idpegawai,
				t2.idjabatanstruk,
				t2.idjabatanfung,
				t3.id as iddisposisi,
				t4.id as idsubdisposisi,
				t4.mode
				from tb_suratbdk as t1
			left join tb_pegawai as t2 on t1.idpegawai=t2.id
			inner join tb_master_disposisi as t3 on t1.idjenissurat=t3.idjenissurat
			inner join tb_master_disposisi_status as t4 on t3.id=t4.iddisposisi
			where t1.id=? 
			group by t3.id, t4.id
			order by t4.urutan asc";
		$rss=$this->loadAll($query,array($idsurat));
		$urutan=1;
		$datajabatan=array();
		$nomorgroup=0;
		foreach ($rss as $obd) {
			if($obd['mode']==0){
				$query="select 
						t1.id as iddisposisijabatan,
						t1.idjabatan,
						t1.mode as modejabatan,
						t1.view,
						t1.edit,
						t1.hapus,
						t2.nama
					from tb_master_disposisi_status_jabatan as t1
					inner join tb_master_disposisi_status as t2 on t1.idsubdisposisi=t2.id
					where t1.iddisposisi=? and t1.idsubdisposisi=? ";
				$arrjabatan=$this->loadAll($query,array($obd['iddisposisi'],$obd['idsubdisposisi']));
				foreach ($arrjabatan as $obj) {
					$query="select idstatus from tb_master_disposisi_status_jabatan_idst where iddisposisijabatan=?";
					$rsstatus=$this->loadAll($query,array($obj['iddisposisijabatan']));
					$arrj=array(
						"idjabatan"=>$obj['idjabatan'],
						"modejabatan"=>$obj['modejabatan'],
						"nama"=>$obj['nama'],
						"urutan"=>$urutan,
						"view"=>$obj['view'],
						"edit"=>$obj['edit'],
						"hapus"=>$obj['hapus'],
						"datastatus"=>$rsstatus
					);
					array_push($datajabatan,$arrj);
				}
				$urutan=$urutan+1;
			}else if($obd['mode']==1){
				if(isset($obd['idjabatanstruk']) && $obd['idjabatanstruk']>0){
					$query="select t1.idparrent as idjabatan,
							t2.id as iddisposisijabatan,
							t2.mode as modejabatan,
							t2.view,
							t2.edit,
							t2.hapus,
							t3.nama
							from tb_master_jabatan as t1
						inner join tb_master_disposisi_status_jabatan as t2 on t1.idparrent=t2.idjabatan
						inner join tb_master_disposisi_status as t3 on t2.idsubdisposisi=t3.id
						inner join tb_master_disposisi as t4 on t3.iddisposisi=t4.id
						where t1.id=? and t4.idjenissurat=? 
						group by t1.idparrent";
					$arrjabatan=$this->loadAll($query,array($obd['idjabatanstruk'],$obd['idjenissurat']));
					foreach ($arrjabatan as $obj) {
						$query="select idstatus from tb_master_disposisi_status_jabatan_idst where iddisposisijabatan=?";
						$rsstatus=$this->loadAll($query,array($obj['iddisposisijabatan']));
						$arrj=array(
							"idjabatan"=>$obj['idjabatan'],
							"modejabatan"=>$obj['modejabatan'],
							"nama"=>$obj['nama'],
							"urutan"=>$urutan,
							"view"=>$obj['view'],
							"edit"=>$obj['edit'],
							"hapus"=>$obj['hapus'],
							"datastatus"=>$rsstatus
						);
						array_push($datajabatan,$arrj);
						$urutan=$urutan+1;
					}
				}
			}else if($obd['mode']==2){
				$query="select * from tb_suratbdk_disposisi_manual 
					where idsurat=? and nomorgroup=? order by urutan asc";
				$arrjabatan=$this->loadAll($query,array($idsurat,$nomorgroup));
				foreach ($arrjabatan as $obj) {
					$query="select * from tb_suratbdk_disposisi_manual_jabatan 
						where iddisposisimanual=? ";
					$rsdisjab=$this->loadAll($query,array($obj['id']));
					foreach ($rsdisjab as $obdjab) {
						$query="select idstatus from tb_suratbdk_disposisi_manual_idstatus where iddisposisimanualjabatan=? ";
						$rsstatus=$this->loadAll($query,array($obdjab['id']));
						
						$arrj=array(
							"idjabatan"=>$obdjab['idjabatan'],
							"modejabatan"=>$obdjab['modejabatan'],
							"nama"=>$obj['nama'],
							"urutan"=>$urutan,
							"view"=>$obdjab['view'],
							"edit"=>$obdjab['edit'],
							"hapus"=>$obdjab['hapus'],
							"datastatus"=>$rsstatus
						);
						array_push($datajabatan,$arrj);
					}
					
					$urutan=$urutan+1;
				}
				
				$nomorgroup=$nomorgroup+1;
			}
		}
		$statusdisp=true;
		$dataerr=array();
		if(sizeof($datajabatan)>0){
			foreach ($datajabatan as $obj) {
				$statusdisposisi=0;
				if($obj['urutan']==1) $statusdisposisi=1;
				$datain=array(
					"idsurat"=>$idsurat,
					"modejabatan"=>$obj['modejabatan'],
					"idjabatan"=>$obj['idjabatan'],
					"urutan"=>$obj['urutan'],
					"statusdisposisi"=>$statusdisposisi,
					"nama"=>$obj['nama'],
					"view"=>$obj['view'],
					"edit"=>$obj['edit'],
					"hapus"=>$obj['hapus'],
				);
				
				$rsin=$this->insert("tb_suratbdk_disposisi",$datain,1);
				if($rsin<=0){
					$statusdisp=false;
					array_push($dataerr,array("pesan"=>"Gagal input data disposisi idjabatan ".$obj['idjabatan']));
				}
				$iddisposisisurat=$rsin;
				if($statusdisp){
					if(isset($obj['datastatus'])){
						$datastatus=$obj['datastatus'];
						foreach ($datastatus as $obst) {
							$datainst=array(
								"iddisposisisurat"=>$iddisposisisurat,
								"idstatus"=>$obst['idstatus']
							);
							$rsst=$this->insert("tb_suratbdk_disposisi_idstatus",$datainst);
							if($rsst!=1){
								$statusdisp=false;
								array_push($dataerr,array("pesan"=>"Gagal input status jabatan ".$obj['idjabatan']." idstatus ".$obst['idstatus']));
							}
						}
					}
					
				}
				if($statusdisp){
					$dataupsurat=array(
						"iddisposisi"=>$iddisposisisurat
					);
					$rsdissr=$this->update("tb_suratbdk", $dataupsurat,"id",$idsurat);
					if($rsdissr!=1){
						$statusdisp=false;
						array_push($dataerr,array("pesan"=>"Gagal update disposisi surat"));
					}
				}
				
				if($statusdisposisi==1 && $statusdisp){
					$whp="";
					$datapushp=array();
					if($obj['modejabatan']==1){
						$whp.="and idjabatanstruk=? ";
						array_push($datapushp,$obj['idjabatan']);
					}
					if($obj['modejabatan']==2){
						$whp.="and idjabatanfung=? ";
						array_push($datapushp,$obj['idjabatan']);
					}
					$query="select nama,email from tb_pegawai 
						where status!=9 ".$whp;
					$rspeg=$this->loadAll($query,$datapushp);
					foreach ($rspeg as $obp) {
						$datain=array(
							"email"=>$obp['email'],
							"subject"=>"Pesan Disposisi",
							"pesan"=>"Pegawai ".$obp['nama']." Terdapat disposisi aktif baru "
						);
						
						$rs=$this->insert("tb_kirim_email",$datain);
						if($rs==1){
							shell_exec("nohup python ".HOMEDIR."py/mailmasal.py > /dev/null 2>&1 &");
						}
					}
				}
			}
		}
		
		
		$hasil['status']=$statusdisp;
		$hasil['pesan']=$dataerr;
		return $hasil;
	}
	
	public function cekdatadisposisi($idsurat){
		$hasil=array("status"=>0,"pesan"=>"Terjadi kesalahan","data"=>array());
		$query="select id,urutan from tb_suratbdk_disposisi 
			where idsurat=? and statusdisposisi=1";
		$rsc=$this->loadAssoc($query,array($idsurat));
		if(!isset($rsc['id'])) return $hasil;
		$query="select * from tb_suratbdk_disposisi 
			where idsurat=? and statusdisposisi=0 and urutan>? ";
		$rsl=$this->loadAssoc($query,array($idsurat,$rsc['urutan']));
		if(!isset($rsl['id'])) return $hasil;
		$hasil['status']=1;
		return $hasil;
	}
	
	public function getstatusdisposisi($idsurat){
		$query="select t1.id,
				t1.keterangan,
				dp2.idstatus,
				dp3.nama as namastatus,
				dp3.bg,
				dp3.warna
			from tb_suratbdk as t1
			inner join tb_suratbdk_disposisi as dp1 on t1.id=dp1.idsurat
				and dp1.edit=1 and dp1.statusdisposisi=1
			inner join tb_suratbdk_disposisi_idstatus as dp2 
				on dp1.id=dp2.iddisposisisurat
			inner join tb_master_status as dp3 on dp2.idstatus=dp3.id
			where t1.id=? and ((dp1.idjabatan=? and dp1.modejabatan=1) or (dp1.idjabatan=? and dp1.modejabatan=0))
			group by dp2.idstatus";
		$rs=$this->loadAll($query,array($idsurat,
			$_SESSION['profile']['idjabatanstruk'],
			$_SESSION['profile']['idjabatanfung']));
		return $rs;
	}
	
	public function cekdisposisistatus($idsurat,$idstatus){
		$hasilstatus=false;
		$query="select t1.id
			from tb_suratbdk as t1
			inner join tb_suratbdk_disposisi as dp1 on t1.id=dp1.idsurat
				and dp1.edit=1 and dp1.statusdisposisi=1
			inner join tb_suratbdk_disposisi_idstatus as dp2 
				on dp1.id=dp2.iddisposisisurat
			inner join tb_master_status as dp3 on dp2.idstatus=dp3.id
			where t1.id=? and ((dp1.idjabatan=? and dp1.modejabatan=1) or (dp1.idjabatan=? and dp1.modejabatan=0))
			and dp2.idstatus=? ";
		$rs=$this->loadAssoc($query,array($idsurat,
			$_SESSION['profile']['idjabatanstruk'],
			$_SESSION['profile']['idjabatanfung'],
			$idstatus));
		if(isset($rs['id'])) $hasilstatus=true;
		return $hasilstatus;
	}
	
	public function cekdisposisiaksesupdate($idsurat){
		$hasilstatus=false;
		$query="select t1.id
			from tb_suratbdk as t1
			inner join tb_suratbdk_disposisi as dp1 on t1.id=dp1.idsurat
				and dp1.edit=1 and dp1.statusdisposisi=1
			where t1.id=? and ((dp1.idjabatan=? and dp1.modejabatan=1) or (dp1.idjabatan=? and dp1.modejabatan=0))";
		$rs=$this->loadAssoc($query,array($idsurat,
			$_SESSION['profile']['idjabatanstruk'],
			$_SESSION['profile']['idjabatanfung']));
		if(isset($rs['id'])) $hasilstatus=true;
		return $hasilstatus;
	}
	
	public function cekdisposisiakseshapus($idsurat){
		$hasilstatus=false;
		$query="select t1.id
			from tb_suratbdk as t1
			inner join tb_suratbdk_disposisi as dp1 on t1.id=dp1.idsurat
				and dp1.hapus=1 and dp1.statusdisposisi=1
			where t1.id=? and ((dp1.idjabatan=? and dp1.modejabatan=1) or (dp1.idjabatan=? and dp1.modejabatan=0))";
		$rs=$this->loadAssoc($query,array($idsurat,
			$_SESSION['profile']['idjabatanstruk'],
			$_SESSION['profile']['idjabatanfung']));
		if(isset($rs['id'])) $hasilstatus=true;
		return $hasilstatus;
	}
	
	public function updatedatadisposisi($idsurat){
		$hasil=array("status"=>0,"pesan"=>"Terjadi kesalahan","data"=>array());
		$query="select id,urutan from tb_suratbdk_disposisi 
			where idsurat=? and statusdisposisi=1";
		$rsc=$this->loadAssoc($query,array($idsurat));
		if(!isset($rsc['id'])) return $hasil;
		$query="select * from tb_suratbdk_disposisi 
			where idsurat=? and statusdisposisi=0 and urutan=?";
		$rsl=$this->loadAll($query,array($idsurat,$rsc['urutan']+1));
		if(sizeof($rsl)<=0) return $hasil;
		
		$statusupdate=true;
		$this->begin();
		
		$urutandata=1;
		foreach ($rsl as $obl) {
			if($urutandata==1){
				$dataupsurat=array(
					"iddisposisi"=>$obl['id']
				);
				$rsdissr=$this->update("tb_suratbdk", $dataupsurat,"id",$idsurat);
				if($rsdissr!=1) $statusupdate=false;
			}
			
			if($statusupdate){
				$dataup=array(
					"statusdisposisi"=>1
				);
				$rsup=$this->update("tb_suratbdk_disposisi",$dataup,"id",$obl['id']);
			}
			
			if($rsup!=1) $statusupdate=false;
			
			if($statusupdate){
				$whp="";
				$datapushp=array();
				if($obl['modejabatan']==1){
					$whp.="and idjabatanstruk=? ";
					array_push($datapushp,$obl['idjabatan']);
				}
				if($obl['modejabatan']==2){
					$whp.="and idjabatanfung=? ";
					array_push($datapushp,$obl['idjabatan']);
				}
				$query="select nama,email from tb_pegawai 
					where status!=9 ".$whp;
				$rspeg=$this->loadAll($query,$datapushp);
				foreach ($rspeg as $obp) {
					$datain=array(
						"email"=>$obp['email'],
						"subject"=>"Pesan Disposisi",
						"pesan"=>"Pegawai ".$obp['nama']." Terdapat disposisi aktif baru "
					);
					
					$rs=$this->insert("tb_kirim_email",$datain);
					if($rs==1){
						shell_exec("nohup python ".HOMEDIR."py/mailmasal.py > /dev/null 2>&1 &");
					}
				}
			}
			$urutandata=$urutandata+1;
		}
		
		if($statusupdate){
			$dataup=array(
				"statusdisposisi"=>2,
				"iduser"=>$_SESSION['profile']['id'],
				"tanggal_close"=>date("Y-m-d H:i:s")
			);
			$rsup=$this->updates("tb_suratbdk_disposisi",$dataup,["idsurat","urutan"],[$idsurat,$rsc['urutan']]);
			if($rsup!=1) $statusupdate=false;
		}
		
		if($statusupdate){
			$this->commit();
		}else{
			$this->rollback();
		}
		
		$hasil['status']=$statusupdate;
		return $hasil;
	}
	
	public function cekemailupdatestatus($idsurat){
		date_default_timezone_set('Asia/Jakarta');
		$datakirimemail=0;
		$query="select t1.id,
					t1.idjenissurat,
					t1.nomor_panjang,
					t2.nama as namastatus
				from tb_suratbdk as t1
			inner join tb_master_status as t2 on t1.status=t2.id
			where t1.id=? ";
		$rssurat=$this->loadAssoc($query,array($idsurat));
		if(isset($rssurat['id'])){
			if($rssurat['idjenissurat']==10){
				$query="select t1.idpegawai,
						t2.nama,
						t2.email
					from tb_cuti_pegawai as t1
					inner join tb_pegawai as t2 on t1.idpegawai=t2.id and t2.status!=9
					where t1.idsurat=? ";
				$rsemail=$this->loadAssoc($query,array($idsurat));
				if(isset($rsemail['idpegawai'])){
					$datain=array(
						"email"=>$rsemail['email'],
						"subject"=>"Pesan Update Status Pengajuan Cuti",
						"pesan"=>"Pengajuan Cuti pegawai ".$rsemail['nama']." dengan nomor ".$rssurat['nomor_panjang']." terdapat perubahan status menjadi ".$rssurat['namastatus']
					);
					
					$rs=$this->insert("tb_kirim_email",$datain);
					if($rs==1) $datakirimemail=$datakirimemail+1;
				}
			}else if($rssurat['idjenissurat']==11){
				$query="select t1.id,
						t3.nama,
						t3.email
					from tb_surat_tugas as t1
					inner join tb_surat_tugas_pegawai as t2 on t1.id=t2.idsurattugas
					inner join tb_pegawai as t3 on t2.idpegawai=t3.id and t3.status!=9
					where t1.idsurat=? ";
				$rsemail=$this->loadAll($query,array($idsurat));
				foreach ($rsemail as $obe) {
					$datain=array(
						"email"=>$obe['email'],
						"subject"=>"Pesan Update Status Pengajuan Surat Tugas",
						"pesan"=>"Pengajuan Surat Tugas pegawai ".$obe['nama']." dengan nomor ".$rssurat['nomor_panjang']." terdapat perubahan status menjadi ".$rssurat['namastatus']
					);
					$rs=$this->insert("tb_kirim_email",$datain);
					if($rs==1) $datakirimemail=$datakirimemail+1;
				}	
			}else if($rssurat['idjenissurat']==20){
				$query="select t1.id,
						t2.nama,
						t2.email
					from tb_pengajuan_pkl as t1
					inner join tb_username as t2 on t1.iduser=t2.id
					where t1.idsurat=? ";
				$rsemail=$this->loadAll($query,array($idsurat));
				foreach ($rsemail as $obe) {
					$datain=array(
						"email"=>$obe['email'],
						"subject"=>"Pesan Update Status Pengajuan Surat Tugas",
						"pesan"=>"Pengajuan Surat Tugas pegawai ".$obe['nama']." dengan nomor ".$rssurat['nomor_panjang']." terdapat perubahan status menjadi ".$rssurat['namastatus']
					);
					$rs=$this->insert("tb_kirim_email",$datain);
					if($rs==1) $datakirimemail=$datakirimemail+1;
				}	
			}
		}
		if($datakirimemail>0){
			shell_exec("nohup python ".HOMEDIR."py/mailmasal.py > /dev/null 2>&1 &");
		}
		return true;
	}
	
	public function tutupdisposisi($idsurat){
		$hasil=array("status"=>0,"pesan"=>"Terjadi kesalahan","data"=>array());
		date_default_timezone_set('Asia/Jakarta');
		
		$query="select id,urutan from tb_suratbdk_disposisi 
			where idsurat=? and statusdisposisi=1";
		$rsc=$this->loadAssoc($query,array($idsurat));
		if(!isset($rsc['id'])) return $hasil;
		
		$statusupdate=true;
		$dataup=array(
			"statusdisposisi"=>2,
			"iduser"=>$_SESSION['profile']['id'],
			"tanggal_close"=>date("Y-m-d H:i:s")
		);
		$rsup=$this->updates("tb_suratbdk_disposisi",$dataup,["idsurat","urutan"],[$idsurat,$rsc['urutan']]);
		if($rsup!=1) $statusupdate=false;
		
		$sekarang=date("Y-m-d");
		if($statusupdate){
			$dataup=array(
				"statusdisposisi"=>1,
				"tanggal_close"=>$sekarang
			);
			$rsdis=$this->update("tb_suratbdk",$dataup,"id",$idsurat);
			if($rsdis!=1) $statusupdate=false;
		}
		$hasil['status']=$statusupdate;
		return $hasil;
	}	
	
	public function getdatadisposisi($idsurat,$mode=0){
		$hasil=array("status"=>0,"pesan"=>"Terjadi kesalahan","data"=>array());
		$datajabatan=array();
		$iddisposisi=0;
		$modemanual=0;
		if($mode==0){
			$query="select t1.id,
					t1.idjenissurat,
					t1.idpegawai,
					t2.idjabatanstruk,
					t2.idjabatanfung,
					t3.id as iddisposisi,
					t4.id as idsubdisposisi,
					t4.mode
					from tb_suratbdk as t1
				left join tb_pegawai as t2 on t1.idpegawai=t2.id
				inner join tb_master_disposisi as t3 on t1.idjenissurat=t3.idjenissurat
				inner join tb_master_disposisi_status as t4 on t3.id=t4.iddisposisi
				where t1.id=? 
				order by t4.urutan asc limit 0,1";
			$rss=$this->loadAssoc($query,array($idsurat));
			if(!isset($rss['id'])) return $hasil;
			$iddisposisi=$rss['idsubdisposisi'];
			
			if($rss['mode']==2){
				$modemanual=1;
				$query="select modejabatan,
						idjabatan,nomorgroup,
						urutan
						from tb_suratbdk_disposisi_manual 
					where idsurat=? and nomorgroup=0
					order by urutan asc ";
				$datajabatan=$this->loadAll($query,array($idsurat));
			}else if($rss['mode']==1){
				if(isset($rss['idjabatanstruk']) && $rss['idjabatanstruk']>0){
					$query="select t1.idparrent as idjabatan,
							t2.mode as modejabatan,
							t3.urutan
							from tb_master_jabatan as t1
						inner join tb_master_disposisi_status_jabatan as t2 on t1.idparrent=t2.idjabatan
						inner join tb_master_disposisi_status as t3 on t2.idsubdisposisi=t3.id
						where t1.id=?";
					$datajabatan=$this->loadAll($query,array($rss['idjabatanstruk']));
				}
			}else if($rss['mode']==0){
				$query="select t1.idjabatan,
						t1.mode as modejabatan,
						t2.urutan 
					from tb_master_disposisi_status_jabatan as t1
					inner join tb_master_disposisi_status as t2 on t1.idsubdisposisi=t2.id
					where t1.iddisposisi=? and t1.idsubdisposisi=? ";
				$datajabatan=$this->loadAll($query,array($rss['iddisposisi'],$rss['idsubdisposisi']));
				
			}
		}else if($mode==1){
			$query="select urutan from tb_suratbdk_disposisi 
				where idsurat=? 
				order by tanggal desc limit 0,1 ";
			$rsu=$this->loadAssoc($query,array($idsurat));
			if(!isset($rsu['urutan'])) return $hasil;
			$query="select 
					t1.id,
					t1.id as idsubdisposisi,
					t1.iddisposisi,
					t1.mode,
					t4.idjabatanstruk,
					t4.idjabatanfung
					from tb_master_disposisi_status as t1
				inner join tb_master_disposisi as t2 on t1.iddisposisi=t2.id
				inner join tb_suratbdk as t3 on t2.idjenissurat=t3.idjenissurat
				left join tb_pegawai as t4 on t3.idpegawai=t4.id
				where t3.id=? and t1.urutan > ?
				order by t1.urutan asc limit 0,1";
			$rss=$this->loadAssoc($query,array($idsurat,$rsu['urutan']));
			if(!isset($rss['id'])) {
				$hasil['pesan']="Data disposisi tidak di temukan";
				return $hasil;
			}
			$iddisposisi=$rss['idsubdisposisi'];
			
			if($rss['mode']==2){
				
			}else if($rss['mode']==1){
				if(isset($rss['idjabatanstruk']) && $rss['idjabatanstruk']>0){
					$query="select t1.idparrent as idjabatan,
							t2.mode as modejabatan,
							t3.urutan
							from tb_master_jabatan as t1
						inner join tb_master_disposisi_status_jabatan as t2 on t1.idparrent=t2.idjabatan
						inner join tb_master_disposisi_status as t3 on t2.idsubdisposisi=t3.id
						where t1.id=?";
					$datajabatan=$this->loadAll($query,array($rss['idjabatanstruk']));
				}
			}else if($rss['mode']==0){
				$query="select t1.idjabatan,
						t1.mode as modejabatan,
						t2.urutan 
					from tb_master_disposisi_status_jabatan as t1
					inner join tb_master_disposisi_status as t2 on t1.idsubdisposisi=t2.id
					where t1.iddisposisi=? and t1.idsubdisposisi=? ";
				$datajabatan=$this->loadAll($query,array($rss['iddisposisi'],$rss['idsubdisposisi']));
			}
		}
		
		if(sizeof($datajabatan)>0){
			$hasil['status']=1;
			$hasil['data']=array(
				"modemanual"=>$modemanual,
				"iddisposisi"=>$iddisposisi,
				"datajabatan"=>$datajabatan
			);
		}
		
		return $hasil;
	}

	public function getmasakerja($idpegawai){
		date_default_timezone_set('Asia/Jakarta');
		
		$wh="";
		$datapush=array($idpegawai);
		
		if($_SESSION['profile']['pegawai']==1){
			$wh.="and id=? ";
			array_push($datapush,$_SESSION['profile']['idpegawai']);
		}
		
		$hasil=array(
			"tahun"=>0,
			"bulan"=>0,
			"hari"=>0
		);
		$query="select * from tb_pegawai where id=? ".$wh;
		$rs=$this->loadAssoc($query,$datapush);
		if(isset($rs['id'])){
			$datetime1 = new DateTime($rs['tanggal_sk_awal']);
			$datetime2 = new DateTime();
			$interval = $datetime1->diff($datetime2);
			
			$hasil['tahun']=$interval->y;
			$hasil['bulan']=$interval->m;
			$hasil['hari']=$interval->d;
		}
		
		return $hasil;
	}
	
	public function buatnomorsurat($idjenissurat,$tanggalsurat="")
	{
		$sekarang=date("Y-m-d");
		if($tanggalsurat!="") $sekarang=$tanggalsurat;	
		$tahun=date('Y',strtotime($sekarang));
		$bulan=date('m',strtotime($sekarang));
				
		$nomorpanjang="";
		$nomor=1;
		$query="select * from tb_setting where id=15";
		$rss=$this->loadAssoc($query);
		$dataset=json_decode($rss['setting'],true);
		
		if(!isset($rss['id'])){
			$query="select max(nomor) as nomor from tb_suratbdk where id>0 ";
			$rsn=$this->loadAssoc($query);
			if(isset($rsn['nomor'])) $nomor=$rsn['nomor']+1;
		}else{
			$wh="";
			$datapush=array();
			if(isset($dataset['reset'])){
				if($dataset['reset']=="tahun"){
					$wh.="and tahun=? ";
					array_push($datapush,$tahun);
				}else if($dataset['reset']=="bulan"){
					$wh.="and bulan=? and tahun=? ";
					array_push($datapush,$bulan,$tahun);
				}
				
				$query="select max(nomor) as nomor from tb_suratbdk where id>0 ".$wh;
				$rsn=$this->loadAssoc($query,$datapush);
				if(isset($rsn['nomor'])) $nomor=$rsn['nomor']+1;
			}
		}
		
		if(isset($dataset['dataurutan'])){
			$dataurutan=$dataset['dataurutan'];
			$batas="/";
			if(isset($dataset['batas'])) $batas=$dataset['batas'];
			for($i=0;$i<sizeof($dataurutan);$i++){
				if($i>0 && $nomorpanjang!="") $nomorpanjang=$nomorpanjang.$batas; 
				if($dataurutan[$i]['jenis']=="nourut"){
					$nomorpanjang=$nomorpanjang.$nomor;
				}else if($dataurutan[$i]['jenis']=="kode"){
					$query="select kodesurat from tb_master_jenissurat where id=? ";
					$rsj=$this->loadAssoc($query,array($idjenissurat));
					if(isset($rsj['kodesurat'])){
						$nomorpanjang=$nomorpanjang.$rsj['kodesurat'];
					}
				}else if($dataurutan[$i]['jenis']=="custom"){
					$nomorpanjang=$nomorpanjang.$dataurutan[$i]['custom'];
				}else if($dataurutan[$i]['jenis']=="bulanangka"){
					$nomorpanjang=$nomorpanjang.$this->buatdigit($bulan, 2);
				}else if($dataurutan[$i]['jenis']=="bulanromawi"){
					$nomorpanjang=$nomorpanjang.$this->getnamabulan((int) $bulan,1);
				}else if($dataurutan[$i]['jenis']=="tahun"){
					$nomorpanjang=$nomorpanjang.$tahun;
				}
			}
			
		}
		
		$hasil=array("nomor"=>$nomor,"nomorpanjang"=>$nomorpanjang);
		return $hasil;	
	}
}
?>