<?php
//set time indonesia
ini_set('date.timezone', 'Asia/Jakarta');


//mengaktifkan fungsi autoprint pdf
require('pdf_js.php');
class PDF_AutoPrint extends PDF_JavaScript
{
	function AutoPrint($dialog=false)
	{
		//Open the print dialog or start printing immediately on the standard printer
		$param=($dialog ? 'true' : 'false');
		$script="print($param);";
		$this->IncludeJS($script);
	}
	function AutoPrintToPrinter($server, $printer, $dialog=false)
	{
		//Print on a shared printer (requires at least Acrobat 6)
		$script = "var pp = getPrintParams();";
		if($dialog)
			$script .= "pp.interactive = pp.constants.interactionLevel.full;";
		else
			$script .= "pp.interactive = pp.constants.interactionLevel.automatic;";
		$script .= "pp.printerName = '\\\\\\\\".$server."\\\\".$printer."';";
		$script .= "print(pp);";
		$this->IncludeJS($script);
	}
}


/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel-1.8/Classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';

//Source => http://www.infragistics.com/community/blogs/taz_abdeali/archive/2012/02/08/netadvantage-for-jquery-with-php-101.aspx
//Cek metode
$metode = $_SERVER['REQUEST_METHOD'];

//di aktifkan sblm session
$nameprog =basename($_SERVER['PHP_SELF']);
include ('ceklogin.php');

//aktifkan session
if(!isset($_SESSION)){session_start();}
$fkodekantorx=isset($_SESSION['f_kodekantor'])?$_SESSION['f_kodekantor']:"";

//jika user diberi akses maka bisa pilih kode kantor (butuh ceklogin.php)
$bcadd_haky=($bcadd_hakx=='disabled')?1:0;

//open connection
include ('connect-DB.php');

if ($metode=="POST"){
	// parameter bawaan yg di dapat dari jquery easy ui grid
	$page   = isset($_POST['page']) ? intval($_POST['page']) : 1;
	$rows   = isset($_POST['rows']) ? intval($_POST['rows']) : 25;
	$offset = ($page-1)*$rows;
	//utk short
	$sortx  = isset($_POST['sort']) ? 'absen_user.'.strval($_POST['sort']) : 'absen_user.id';   
	$orderx = isset($_POST['order']) ? strval($_POST['order']) : 'asc'; 
	//utk search
	$nsbhidx	=isset($_POST['nsbhid'])	? trim($_POST['nsbhid'])	: "";
	$nsbhnmx	=isset($_POST['nsbhnm'])	? $_POST['nsbhnm']		: "";
	$kotax	=isset($_POST['kota'])	? $_POST['kota']	: "";
	$isix	=isset($_POST['isi'])		? $_POST['isi'] : "";
	$qx		=isset($_POST['q'])			? $_POST['q'] : "";
	$kuncix	  =isset($_POST['kunci'])	? $_POST['kunci'] : "";
	$prosesx	=isset($_POST['proses'])	? $_POST['proses'] : 0;
	$filex		=isset($_POST['file'])	? $_POST['file'] : "";
	$tahunx		=isset($_POST['tahun'])	? $_POST['tahun'] : "";
	$tanggalx	=isset($_POST['tanggal'])	? $_POST['tanggal'] : "";
	$idx			=isset($_POST['id'])	? $_POST['id'] : "";
	$ssx			=isset($_POST['ss'])	? $_POST['ss'] : null;

	//utk save
	$savetox=isset($_POST['saveto'])	? $_POST['saveto'] : "";
	$filenamex=isset($_POST['filename'])	? $_POST['filename'] : "";
	//utk delete
	$nsbhiddelx=isset($_POST['nsbhiddel'])	? $_POST['nsbhiddel'] : "";
	$deletex=isset($_POST['hapus'])	? $_POST['hapus'] : "";

	//$filterRulesx=isset($_POST['filterRules']) ? $_POST['filterRules'] : 	$_SESSION['filterRules'];
	//$filterRulesx=isset($_POST['filterRules']) ? $_POST['filterRules'] : (isset($_SESSION['filterRules']) ? $_SESSION['filterRules']:'');  
	if (isset($_POST['filterRules'])) {
		if ($_POST['filterRules']!=''){
		  $_SESSION['filterRules']=$_POST['filterRules'];
			$filterRulesx						=$_POST['filterRules'];
		}else{
			$_POST['filterRules']=$_SESSION['filterRules'];
			$filterRulesx				 =$_SESSION['filterRules'];
		}
	}else{
		if (isset($_SESSION['filterRules'])) {
			$_POST['filterRules']=$_SESSION['filterRules'];
			$filterRulesx				 =$_SESSION['filterRules'];
		}
	}
}
else
{
	// parameter bawaan yg di dapat dari jquery easy ui grid
	$page   = isset($_GET['page']) ? intval($_GET['page']) : 1;
	$rows   = isset($_GET['rows']) ? intval($_GET['rows']) : 25;
	$offset = ($page-1)*$rows;
	//utk short
	$sortx  = isset($_GET['sort']) ? 'absen_user.'.strval($_GET['sort']) : 'absen_user.id';   
	$orderx = isset($_GET['order']) ? strval($_GET['order']) : 'asc'; 
	//utk search
	$nsbhidx	=isset($_GET['nsbhid'])	? $_GET['nsbhid']	: "";
	$nsbhnmx	=isset($_GET['nsbhnm'])		? $_GET['nsbhnm']		: "";
	$kotax	=isset($_GET['kota'])	? $_GET['kota']		: "";
	$isix	=isset($_GET['isi'])		? $_GET['isi'] : "";
	$qx		=isset($_GET['q'])			? $_GET['q'] : "";
	$kuncix	  =isset($_GET['kunci'])	? $_GET['kunci'] : "";
	$prosesx	=isset($_GET['proses'])	? $_GET['proses'] : 0;
	$filex		=isset($_GET['file'])	? $_GET['file'] : "";
	$tahunx		=isset($_GET['tahun'])	? $_GET['tahun'] : "";
	$tanggalx	=isset($_GET['tanggal'])	? $_GET['tanggal'] : "";
	$idx			=isset($_GET['id'])	? $_GET['id'] : "";
	$ssx			=isset($_GET['ss'])	? $_GET['ss'] : null;

	//utk save
	$savetox=isset($_GET['saveto'])	? $_GET['saveto'] : "";
	$filenamex=isset($_GET['filename'])	? $_GET['filename'] : "";
	//utk delete	
	$nsbhiddelx=isset($_GET['nsbhiddel'])	? $_GET['nsbhiddel'] : "";
	$deletex=isset($_GET['hapus'])	? $_GET['hapus'] : "";
	//$filterRulesx=isset($_GET['filterRules']) ? $_GET['filterRules'] : 	$_SESSION['filterRules'];
	//$filterRulesx=isset($_GET['filterRules']) ? $_GET['filterRules'] : (isset($_SESSION['filterRules']) ? $_SESSION['filterRules']:'');

	if (isset($_GET['filterRules'])) {
		if ($_GET['filterRules']!=''){
		  $_SESSION['filterRules']=$_GET['filterRules'];
			$filterRulesx						=$_GET['filterRules'];
		}else{
			$_GET['filterRules']=$_SESSION['filterRules'];
			$filterRulesx				 =$_SESSION['filterRules'];
		}
	}else{
		if (isset($_SESSION['filterRules'])) {
			$_GET['filterRules']=$_SESSION['filterRules'];
			$filterRulesx				=$_SESSION['filterRules'];
		}
	}
}
//include("LogCekVar.php");
//die();


//parameter utk search 
$wherex ="1=1";
$wherex2="1=1";
//$wherex .= !empty($nsbhidx)	? " and absen_user.id		like '$nsbhidx%'"	: ""; //utk membuat kosong grid
//$wherex .= !empty($nsbhnmx)		? " and absen_user.nama			like '$nsbhnmx%'"		: ""; 
//$wherex .= !empty($kotax)	? " and absen.kodekota		like '$kotax%'"		: "";


//multisearch - simpan info variable yang terkirim dari page, post, session sebelumnya (membaca json stringify to php)
$ss=isset($filterRulesx)?json_decode($filterRulesx):"";

//$wherex=$filterRulesx; //is_array($ss) || is_object($ss);
//include("LogCekVar.php");
//die();

//butuh if utk cek - https://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach
if (is_array($ss) || is_object($ss))
{
	//$_SESSION['filterRules']=$filterRulesx;
	foreach($ss as $value ){
		if (trim($value->field)=='tgl_masuk' || trim($value->field)=='tgl_keluar'){

			$tgl12 = explode(":", $value->value);
			/*
			//simbol equal jadi =
			if (trim($value->op)=='equal'){
				$simbol='='."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
			}else{
				if (trim($value->op)=='notequal'){
					$simbol='!='."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
				}else{
					if (trim($value->op)=='less'){
						$simbol='<'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
					}else{
						if (trim($value->op)=='greater'){
							$simbol='>'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
						}else{
							//$simbol=' like "'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
							//$simbol=' like "'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
						}
					}
				}
			}
			*/
			//simbol equal jadi =
			if ($tgl12[0]<>'' and $tgl12[1]<>'') {
				if (trim($value->op)=='equal'){
					$simbol=' between '."STR_TO_DATE('".$tgl12[0]."', '%d-%m-%Y')".' and '."STR_TO_DATE('".$tgl12[1]."', '%d-%m-%Y')";
				}else{
					if (trim($value->op)=='notequal'){
						$simbol=' not between '."STR_TO_DATE('".$tgl12[0]."', '%d-%m-%Y')".' and '."STR_TO_DATE('".$tgl12[1]."', '%d-%m-%Y')";
					}else{
						if (trim($value->op)=='less'){
							$simbol='<'."STR_TO_DATE('".$tgl12[0]."', '%d-%m-%Y')";
						}else{
							if (trim($value->op)=='greater'){
								$simbol='>'."STR_TO_DATE('".$tgl12[0]."', '%d-%m-%Y')";
							}else{
								//$simbol=' like "'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
								//$simbol=' like "'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
							}
						}
					}
				}
				$wherex .=" and absen_user.".$value->field.$simbol;
				$wherex2.=" and absen_user.".$value->field.$simbol;
			}
		}else{
			//simbol equal jadi =
			if (trim($value->op)=='equal'){
				$simbol='='.$value->value;
			}else{
				if (trim($value->op)=='notequal'){
					$simbol='!='.$value->value;
				}else{
					if (trim($value->op)=='less'){
						$simbol='<'.$value->value;
					}else{
						if (trim($value->op)=='greater'){
							$simbol='>'.$value->value;
						}else{
							$simbol=' like "%'.$value->value.'%" ';
							//$simbol=' like "'."STR_TO_DATE('".$value->value."', '%d-%m-%Y')";
						}
					}
				}
			}
			$wherex2.=" and absen_user.".$value->field.$simbol;
		}
		
	}
	//tambahan session supaya tetap tersimpan where nya krn menggunakan data filter
	$_SESSION['filterRules']=$filterRulesx;
}

//user yang bisa add bisa lihat user cab lain
if ($bcadd_haky!=0){
	$wherex .=" and trim(kode_kantor)='$fkodekantorx' ";
	$wherex2.=" and trim(kode_kantor)='$fkodekantorx' ";
	//include("LogCekVar.php");
	//die();
}


//multisorting - membuat menjadi multi sorting 
if ($savetox<>'1'){
	$sortx  = explode(",", $sortx);
	$orderx = explode(",", $orderx);
	$arrlength = count($sortx);
	$sorty='';
	for($x = 0; $x < $arrlength; $x++) {
		if ($x>0){
			$sorty.=',';
		}
		$sorty.=$sortx[$x].' '.$orderx[$x];
	}
	$_SESSION['sorty']=$sorty;
}else{
	if (!isset($_SESSION['sorty'])) {
		$_SESSION['sorty']=$sortx.' '.$orderx;
	}else{
		$sorty=$_SESSION['sorty'];
	}
}

//ambil no id terakhir
//$kuncix="ambil_id";
if ($kuncix=="ambil_id"){
	$qstring="
	select max(id) from absen_user
	";
	$rs = mysqli_query($conn_login,$qstring);
	if ($rs){
		$row = mysqli_fetch_row($rs);
		$maxid = $row[0]+1;
		$idnext = substr(1000000000000+$maxid,1);
		$arr = array ('isimsg'=>$idnext,'berhasil'=>true);
	}else{
		$arr = array ('isimsg'=>'','berhasil'=>false);
	}

	echo json_encode($arr);
	die();
}

if ($kuncix=="delpegawai"){
	$arr = array ('');
	//$barcodex	=isset($_POST['addtoner_barcode'])	? $_POST['addtoner_barcode']	: "";
	$idsx	=isset($_POST['ids'])	? $_POST['ids']	: "";

	$ss=json_decode($idsx);
	foreach($ss as $value ){
	  $test[]=$value->id;
	  $info[]=$value->id.":".$value->nama.":".$value->tgl_masuk;
	}
	$query ="delete from absen_user where id in ('".implode("','",$test)."')";
	$rs = mysqli_multi_query($conn_login, $query);
	if (!$rs) {
		//$arr = array ('isimsg'=>'Invalid query: '.mysql_error());
		$arr = array ('isimsg'=>'Invalid query: '.$query);
	}else{
		$arr = array ('isimsg'=>implode("<br>",$info).'<br><font color="blue"><b>Berhasil dihapus</b></font>','berhasil'=>true);
	}
	echo json_encode($arr);
	//$wherex=$qstring;
	//include("LogCekVar.php");
	die();
}


//simpan data pegawai
//$kuncix="addpegawai";
if ($kuncix=="addpegawai" || $kuncix=="editpegawai"){
	//utk insert data
	$idx				=isset($_POST['addpegawai_id'])					? $_POST['addpegawai_id']					: "";	
	$kartux			=isset($_POST['addpegawai_kartu'])			? $_POST['addpegawai_kartu']			: "";
	$ktpx			=isset($_POST['addpegawai_ktp'])			? $_POST['addpegawai_ktp']			: "";	
	$kodekantorx=isset($_POST['addpegawai_kodekantor'])	? $_POST['addpegawai_kodekantor']	: "";
	$namax			=isset($_POST['addpegawai_nama'])				? $_POST['addpegawai_nama']				: "";
	$tglmasukx	=isset($_POST['addpegawai_tglmasuk'])		? $_POST['addpegawai_tglmasuk']		: "";
	$tglkeluarx	=isset($_POST['addpegawai_tglkeluar'])	? $_POST['addpegawai_tglkeluar']	: "";
	$statusx		=isset($_POST['addpegawai_status'])			? $_POST['addpegawai_status']			: "0";

	if ($tglmasukx<>""){
		$tglmasukx="STR_TO_DATE('$tglmasukx', '%d-%m-%Y')";
	}else{
		$tglmasukx="NULL";
	}
	if ($tglkeluarx<>""){
		$tglkeluarx="STR_TO_DATE('$tglkeluarx', '%d-%m-%Y')";
		$statusx = "0";
	}else{
		$tglkeluarx="NULL";
		$statusx = "1";
	}
	
	//cek apakah id sdh ada di server karena jika add maka id harus kosong
	if ($kuncix=="addpegawai"){
		$qstring="
		select count(*) from absen_user
		where id='$idx'
		";
		$rs   = mysqli_query($conn_login,$qstring);
		$row  = mysqli_fetch_row($rs);
		$jmlx = $row[0];
		if ($jmlx==0){
			$lanjutx=true;
		}else{
			$lanjutx=false;
		}
	}else{
		$lanjutx=true;
	}

	//$wherex=$lanjutx;
	//include("LogCekVar.php");
	//die();

	if ($lanjutx){
		$query="
				INSERT INTO absen_user	(kode_kantor   , id			,	kartu    , nama		 ,	tgl_masuk		, tgl_keluar, status, ktp) 
				values									('$kodekantorx', '$idx'	, '$kartux', '$namax',	$tglmasukx	, $tglkeluarx, '$statusx', '$ktpx')
				ON DUPLICATE KEY UPDATE  
						kode_kantor='$kodekantorx',
						kartu='$kartux',
						nama='$namax',
						tgl_masuk =$tglmasukx,
						tgl_keluar=$tglkeluarx,
						status='$statusx',
						ktp='$ktpx'
		";
	  
		//$wherex=$query;
	  //include("LogCekVar.php");
	  //die();

		$rs = mysqli_multi_query($conn_login, $query);
		if ($rs){
			$arr = array ('isimsg'=>'ID = '.stripslashes($idx).'<br>Nama = '.stripslashes($namax).'</p> <font color="blue"><b>Berhasil disave</b></font>',"berhasil"=>true);
		}else{
			$arr = array ('isimsg'=>'ID ='.stripslashes($idx).'<br>Nama = '.stripslashes($namax).'</p> <font color="red"><b>Gagal disave cek:'.$query.'</b></font>',"berhasil"=>false);
		}		
	}else{
		$arr = array ('isimsg'=>'</p> <font color="red"><b>Gagal disave karena id '.stripslashes($idx).' sdh pernah ada </b></font>',"berhasil"=>false);
	}
	echo json_encode($arr);
	die();
}


//simpan ke csv
if ($savetox=='1'){
	//membuang karakter tab dan enter
	$karakteraneh = array("\r","\n");
  $filename=$filenamex.".xls";

	// Create your database query
	$query = "
				select id,nama,tgl_masuk,tgl_keluar, status
				from absen_user
				where $wherex2
				order by $sorty
	";

	// Execute the database query
	$result = 	$rs = mysqli_query($conn_login,$query) or die(mysqli_error());

	//sumber => https://stackoverflow.com/questions/12611148/how-to-export-data-to-an-excel-file-using-phpexcel
	// Instantiate a new PHPExcel object
	$objPHPExcel = new PHPExcel(); 
	// Set the active Excel worksheet to sheet 0
	$objPHPExcel->setActiveSheetIndex(0); 

	// Initialise the Excel row number - header
	$rowCount = 1;  
	//start of printing column names as names of MySQL fields  
	$column = 'A';
	//sumber => https://stackoverflow.com/questions/14629636/mysql-field-name-to-the-new-mysqli
	while ($property = mysqli_fetch_field($result)) {
			$objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $property->name);
			$column++;
	}
	//end of adding column names  

	// Initialise the Excel row number - detail
	$rowCount = 2; 
	// Iterate through each result from the SQL query in turn
	// We fetch each database result row into $row in turn
	while($rowx = mysqli_fetch_array($result,MYSQLI_ASSOC)){ 
			// Set cell An to the "name" column from the database (assuming you have a column called name)
			//    where n is the Excel row number (ie cell A1 in the first row)
			$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $rowx['id']); 
			// Set cell Bn to the "age" column from the database (assuming you have a column called age)
			//    where n is the Excel row number (ie cell A1 in the first row)
			$rowx['nama']=trim(str_replace($karakteraneh, "", $rowx['nama'])); //tambahan saja
			$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $rowx['nama']); 
			// Increment the Excel row counter
			$objPHPExcel->getActiveSheet()->SetCellValue('C'.$rowCount, $rowx['tgl_masuk']); 
			$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $rowx['tgl_keluar']); 
			$objPHPExcel->getActiveSheet()->SetCellValue('E'.$rowCount, ($rowx['status']==1?'Aktif':'Resign')); 
			$rowCount++; 
	} 
	
	//utk test isi query
	//$objPHPExcel->getActiveSheet()->SetCellValue('D'.$rowCount, $query); 

	//set bold
	$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);

	// Redirect output to a client’s web browser (Excel5) 
	header('Content-Type: application/vnd.ms-excel'); 
	header('Content-Disposition: attachment;filename='.$filename); 
	header('Cache-Control: max-age=0'); 
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
	$objWriter->save('php://output');

	//info
	$arr = array ('isimsg'=>"saved");
	echo json_encode($arr);
	die();
}

//20150530, kluar kalau session usernya habis
if ($kuncix=="ceklogin"){
	//var keluar dan tutupakses jika tidak di deklarasikan otomatis dianggap "undefined"==false oleh javascript
	if (is_null($upuserx)){			
		$arr = array ('isimsg'=>"<font color=red>GAGAL, Harap Login Ulang!!</font>",'keluar'=>true);
	}else{
		//if ($levelx!=0){   &&=>ditutup (set false) karena tdk perlu control hak lewat javascript
		//if (false){
		if (is_null($openx)||!$openx) {
			$arr = array ('isimsg'=>"<font color=red>GAGAL, Anda tidak berhak!!</font>",'tutupakses'=>true);
		}
		else{
			$arr = array ('isimsg'=>"");
		}
	}
	echo json_encode($arr);
	die();
}

//jika user absen menggunakan barcode
if ($kuncix=='HariIni'){
	//cek konfirmasi
	$konfirmasix=isset($_POST['konfirmasi'])	? $_POST['konfirmasi'] : "";
	//password konfirmasi sementara manual tidak baca database dan bisa dirubah sewaktu2, 
	//jika ingin menggunakan barcode tanpa konfirmasi: $konfirmasix di set selalu true, bagian cetak barcode di arahkan ke halaman pegawaiFunc.php dan echo dibawah tnp menggunakan json_encode
	if ($konfirmasix=='12345'){
		//urutan proses decrpyt
		$idx=decrypt($idx);

		//initial $t dengan hari ini
		$t=time();
		$tgljamx=date("Y-m-d H:i:s",$t);
		$tglx   =date("Y-m-d",$t);
		$jamx   =date("H:i:s",$t);
		$manualx=1;
		$upuserx=$idx;
		$uptglx =$tglx;

		$lanjut=-1;
		$qstring="
			SELECT a.`id`  ,min(`tgl_jam`) as `tgl_jammsk`, max(`tgl_jam`) as `tgl_jam`, `tgl` ,max(`jam`) as `jam`,`manual`  ,`upuser`  ,`uptgl`, b.nama
			FROM `hensap`.`absen_mesin` a inner join `hensap`.`absen_user` b on a.id=b.id
			WHERE
			a.id='$idx' AND tgl='$tglx'
		";

		//$wherex=$qstring;
		//include("LogCekVar.php");
		//echo $idx;
		//die();

		$rs = mysqli_query($conn_login,$qstring); 
		while ($rowx = mysqli_fetch_array($rs,MYSQLI_ASSOC)){
			$namax=$rowx["nama"];
			//jeda waktu absen 5 menit => $diff<=5 menit
			$diff=floor(($t-strtotime($rowx['jam']))/60) ;
			if ($diff<=5){
				//$isimsg="<font color='red'><b>Gagal</b></font>, Anda $idx sudah absen<br>Terakhir absen : ".date('d-m-y, H:i:s',strtotime($rowx['tgl_jam']))."<br>";
				$isimsg="<font color='red'><b>Gagal</b></font>, Anda $idx sudah absen<br>Skrg : ".date('d-m-y, H:i:s',$t)."<br>";
				$lanjut=0;
				$jam_msk=$rowx['tgl_jammsk'];
				$jam_plg=$rowx['tgl_jam'];
			}else{
				$isimsg ="<font color='blue'><b>Berhasil1</b></font><br>Absen $idx : ".date('d-m-y, H:i:s',$t)."<br>";
				$lanjut=1;
				$jam_msk=is_null($rowx['tgl_jammsk'])?$tgljamx:$rowx['tgl_jammsk'];  //===> ini coba cek ulang karena aneh
				$jam_plg=$tgljamx;
			}
		}

		if ($lanjut==(-1)){
			$isimsg ="<font color='blue'><b>Berhasil2</b></font><br>Absen $idx : ".date('d-m-Y, H:i:s',$t)."<br>";
			$lanjut=1;
			$jam_msk=$tgljamx;
			$jam_plg=$tgljamx;
			$lanjut=1;
		}

		if ($lanjut==1){
			$qstring="
			INSERT INTO `hensap`.`absen_mesin` 
				(`id`  ,`tgl_jam` ,`tgl`   ,`jam`  ,`manual`  ,`upuser`  ,`uptgl`) 
			VALUES
				('$idx','$tgljamx', '$tglx','$jamx','$manualx','$upuserx','$uptglx');
			";
			$rs = mysqli_query($conn_login,$qstring);
		}

		$isimsg.="---------------------------------------------------------<br>";
		$isimsg.="- Jam masuk  : ".(strtotime($jam_msk)<strtotime("13:00") ?date('d-m-Y, H:i:s',strtotime($jam_msk)) :"") ."<br>";
		$isimsg.="- Jam pulang : ".(strtotime($jam_plg)>=strtotime("13:00") ?date('d-m-Y, H:i:s',strtotime($jam_plg)) :"")."<br>";
	}else{
		$isimsg="<font color='red'><b>Gagal</b></font>, Anda tidak berhak absen";
	}
	//jika langsung ke pegawaiFunc.php
	//echo $isimsg;
	//jika butuh konfirmasix
	$arr = array ('isimsg'=>$isimsg);
	echo json_encode($arr);
	die();
}

//cetak data ke barcode qrcode
if ($kuncix=="cetakqr"){
	//set barcode
	include("phpqrcode/qrlib.php");
	$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
	//html PNG location prefix
	$PNG_WEB_DIR = 'temp/';
	//jika tidak di temukan maka buat directory temp
	if (!file_exists($PNG_TEMP_DIR))
		mkdir($PNG_TEMP_DIR);

	//membaca data yg di pilih utk di cetak
	foreach(json_decode($ssx) as $value) {
		//remember to sanitize user input in real-life solution 'L','M','Q','H' !!!
		$errorCorrectionLevel = 'H';
		//set 1-10
		$matrixPointSize = 6;
		//$Encrypted1 = encrypt($value->kode_kantor);

		//urutan proses decrpyt
		$Encrypted2 = encrypt($value->id);
		//jika menggunakan tanpa konfirmx
		//$_REQUEST['data']="http://192.168.0.8/pegawaiConfirm.php?kunci=HariIni&id=".$Encrypted2;			//server
		//$_REQUEST['data']="http://192.168.0.51/Utama/pegawaiFunc.php?kunci=HariIni&id=".$Encrypted2;	//local
		//jika menggunakan konfirmx
		//$_REQUEST['data']="http://192.168.0.8/pegawaiConfirm.php?kunci=HariIni&id=".$Encrypted2;			//server
		$_REQUEST['data']="http://192.168.0.51/Utama/pegawaiConfirm.php?kunci=HariIni&id=".$Encrypted2;	//local
		$namefile = $value->id."_".md5($_REQUEST['data'].'|'.$errorCorrectionLevel.'|'.$matrixPointSize.time());
		$extfile = '.png';
		$filename = $PNG_TEMP_DIR.$namefile.$extfile ;	
		$file[]=array(
			"file"=>$filename,
			"kode_kantor"=>$value->kode_kantor,
			"id"=>$value->id,
			"nama"=>$value->nama 
		);
		//membuat image
		QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
		//$stars = imagecreatefrompng("$filename");
		//header('Content-type: image/png');
		//imagepng($stars,"$filename");
		//imagedestroy($stars);
		//header('Content-Type: text/html');//membuat normal, sumber => http://stackoverflow.com/questions/4954624/echo-problem-after-after-generating-iamge
	}


	//membuat lembar pdf berikut gambar barcodeqr nya
	//set pdf
	//require('./fpdf/fpdf.php');
	//$pdf = new FPDF();
	$pdf=new PDF_AutoPrint();
	$pdf->AddPage('P', 'A4'); 
	$pdf->SetFont('Arial','',9);
	//ukuran kertas dan tiap cell
	//$height_of_cell = 22; // mm
	//$page_height = 290.5; // mm (portrait letter)
	//$bottom_margin = 0; // mm

	//20170318, atur posisi cetak / print barcode dan isi nya 1 set 
	//$pdf->Cell(40,10,'Hello World!');
	$y=10;
	$x=10;
	$resolusi=-230;
	$wh=32;
	$x1=$x+5;
	foreach($file as $filenameku => $isi){
		//buat gambar barcode
		$pdf->SetXY($x,$y);
		$pdf->Image($PNG_WEB_DIR.basename($isi["file"]),$x1,$y,$wh,$wh,"png");

		//buat tulisan angka barcode disebelah kiri dan vertikal
		$pdf->TextWithDirection($x1,$y+$wh-(($wh-21)/2),$isi["id"],'U');

		//buat garis vertikal
		$pdf->Line($x1+$wh+2, $y-1, $x1+$wh+2, $y+$wh+1);

		//buat garis horizontal atas
		$pdf->Line($x, $y-1, $x+100, $y-1);

		//buat garis horizontal atas
		$pdf->Line($x, $y+$wh+1, $x+100, $y+$wh+1);
		
		//tulisan
		$pdf->SetXY($x1+$wh+2+2,$y);
		$pdf->Cell(1,6,$isi["id"]);
		//tulisan
		$pdf->SetXY($x1+$wh+2+2,$y+4);
		$pdf->Cell(1,6,$isi["kode_kantor"]);
		//tulisan
		$pdf->SetXY($x1+$wh+2+2,$y+8);
		$pdf->Cell(1,6,$isi["nama"]);

		if ($y+12>=251){
			$pdf->AddPage(); 
			$y=10;
			$x=10;
			$resolusi=-230;
			$wh=32;
			$x1=$x+5;
		}	
		$y=$y+$wh+4;

		//hapus file temporary
		unlink($isi["file"]);

	}

	//memunculkan dialog print
	$pdf->AutoPrint(true);

	//Fungsi "OUTPUT" di FPDF, sumber : http://stackoverflow.com/questions/29121375/fpdf-outputfilename-pdf-f-downloading-file-on-browser-instead-of-saving-i
	//Output('filename.pdf','D');
	//For reference, here are the different values for the destination parameter:
	//I: send the file inline to the browser. The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.
	//D: send to the browser and force a file download with the name given by name.
	//F: save to a local file with the name given by name (may include a path).
	//S: return the document as a string. name is ignored.	
	
	//printah cetak / print
	//$pdf->Output();
	//die();

	//module test isian
	//$wherex=($filename);
	//include("LogCekVar.php");$arr = array ('isimsg'=>"Ok");echo json_encode($arr);die();
	
	//perintah cetak / print di rubah menjadi :
	//simpan ke file
	$pdffile='temp/'.$namefile.'.pdf';
	$pdf->Output($pdffile ,'F');
	$arr = array ('isimsg'=>"Berhasil.. please wait!!",'namapdf'=>$pdffile);
	echo json_encode($arr);

	//simpan info variable yang terkirim dari page, post, session sebelumnya
	//$wherex=$arr;
	//include("LogCekVar.php");

	die();
}
 
//kumpulan function
function encrypt( $q ) {
	$cryptKey			 = 'qJB0rGtIn5UB1xG03efyCp';
	$qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
	$qEncoded=str_replace("+","plus",$qEncoded);
	$qEncoded=str_replace("/","slashL",$qEncoded);
	$qEncoded=str_replace("\\","slashR",$qEncoded); //echo str_replace('\\', '/', $str);
	$qEncoded=str_replace("-","min",$qEncoded);
	$qEncoded=str_replace(":","bagi",$qEncoded);
	$qEncoded=str_replace("=","sama",$qEncoded);
	$qEncoded=str_replace("*","kali",$qEncoded);
	return( $qEncoded );
}
function decrypt( $q ) {
	$cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
	$q=str_replace("plus","+",$q);
	$q=str_replace("slashL","/",$q);
	$q=str_replace("slashR","\\",$q);
	$q=str_replace("min","-",$q);
	$q=str_replace("bagi",":",$q);
	$q=str_replace("sama","=",$q);
	$q=str_replace("kali","*",$q);
	$qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
	return( $qDecoded );
}


// total rec data
$qstring="
select count(*) from absen_user
where $wherex2
";
$rs = mysqli_query($conn_login,$qstring);
$row = mysqli_fetch_row($rs);
$result["total"] = $row[0];

// ambil data absen
$qstring="
	select * from absen_user
	where $wherex2
	order by $sorty
	limit $offset,$rows
";
//$wherex=$qstring;
//include("LogCekVar.php");


//cara baca	mysqli - https://stackoverflow.com/questions/21797118/deprecated-mysql-connect
$rs = mysqli_query($conn_login,$qstring);

//membuat array dalam format (ini cara otomatis kl mau buat manual)
$items = array();
while($row = mysqli_fetch_object($rs)){
	//if (!is_null($row->tgllahir)){
	//	$datetmp = strtotime($row->tgllahir);
	//	$row->tgllahir=date("d-m-Y", $datetmp);
	//}
	array_push($items, $row);
}
//total keseluruhan isi data
$result["rows"] = $items;
 
echo json_encode($result);
die();

?>