<?php
if($_POST['t']=='create'){
	$cek=mysqli_num_rows(mysqli_query($connect, "select ID from karyawan where email='$_POST[email]'"));
	if(!$cek){
		$cek2=mysqli_num_rows(mysqli_query($connect, "select ID from users where user_email='$_POST[email]'"));
		if(!$cek2){
			if($_POST['foto']){
				$foto = simpanGambar($_POST['foto'],'assets/images/kasir/',75);
			}else{
				$foto = NULL;
			}
			$password = Password($_POST['password']);
			$q=mysqli_query($connect, "INSERT INTO `karyawan` (`ID_user`, `nama`, `email`, `password`, `no_hp`, `foto`, `status`, `date_create`)
											VALUES ('$_SESSION[id_user]', '$_POST[nama]', '$_POST[email]', '$password', '$_POST[no_hp]', '$foto', '1', '$now');");
			$idk=mysqli_fetch_array(mysqli_query($connect, "select ID from karyawan where email='$_POST[email]' and password='$password' and nama='$_POST[nama]' and ID_user='$_SESSION[id_user]'"));
			foreach($_POST['toko'] as $toko){
				$q=mysqli_query($connect, "INSERT INTO `karyawan_toko` (`ID_user`, `ID_karyawan`, `ID_toko`)
													VALUES ('$_SESSION[id_user]', '$idk[0]', '$toko');");
			}
			if(!$q){
				$data = array('status'=>0,'msg'=>mysqli_error($connect));
			}else{
				$data = array('status'=>1);
			}
	}else{
		$data = array('status'=>0,'msg'=>'This email address is already registered!');
	}
	}else{
		$data = array('status'=>0,'msg'=>'This email address is already registered!');
	}
	echo json_encode($data);
}elseif($_POST['t']=='update'){
	$qc=mysqli_query($connect, "select * from karyawan where ID='$_POST[id]'");
	$cek=mysqli_num_rows($qc);
	if($cek){
		$bc=mysqli_fetch_array($qc);
		if($_POST['email']!=$bc['email']){
			$cemail=mysqli_num_rows(mysqli_query($connect, "select ID from karyawan where email='$_POST[email]'"));
			if($cemail>0){
				$cemail2=mysqli_num_rows(mysqli_query($connect, "select ID from users where user_email='$_POST[email]'"));
				if($cemail2>0){
					$data = array('status'=>0,'msg'=>'This email address is already registered!');
					$err=1;
				}else{
					$err=0;
				}
			}else{
				$err=0;
			}
		}else{
			$err=0;
		}
	}else{
		$data = array('status'=>0,'msg'=>'An unexpected error occurred!');
		$err=1;
	}
	if($err==0){
		$q=mysqli_query($connect, "UPDATE `karyawan` SET `nama`='$_POST[nama]',`email`='$_POST[email]',`no_hp`='$_POST[no_hp]', `date_create`='$now' WHERE `ID`='$_POST[id]' and `ID_user`='$_SESSION[id_user]';");	
		if(!$_POST['old_img']){
			$foto = simpanGambar($_POST['foto'],'assets/images/kasir/',50);
			$q=mysqli_query($connect, "UPDATE `karyawan` set `foto`='$foto' where ID='$_POST[id]' and `ID_user`='$_SESSION[id_user]'");
		}
		if($_POST['password']){
			$password = Password($_POST['password']);
			$q=mysqli_query($connect, "UPDATE `karyawan` set `password`='$password' where ID='$_POST[id]' and `ID_user`='$_SESSION[id_user]'");
	
		}
		$qd=mysqli_query($connect, "DELETE FROM `karyawan_toko` where ID_user='$_SESSION[id_user]' and ID_karyawan='$_POST[id]'");
		foreach($_POST['toko'] as $toko){
			$q=mysqli_query($connect, "INSERT INTO `karyawan_toko` (`ID_user`, `ID_karyawan`, `ID_toko`)
												 VALUES ('$_SESSION[id_user]', '$_POST[id]', '$toko');");
		}
		if(!$q){
			$data = array('status'=>0,'msg'=>mysqli_error($connect));
		}else{
			$data = array('status'=>1);
		}
	}
	echo json_encode($data);
}elseif($_POST['t']=='delete'){
	$q=mysqli_query($connect, "select foto from karyawan where ID_user='$_SESSION[id_user]' and ID='$_POST[id]'");
	$b=mysqli_fetch_array($q);
	if(is_file('assets/images/kasir/'.$b['foto'])){
		unlink('assets/images/kasir/'.$b['foto']);
	}
	$q=mysqli_query($connect, "DELETE FROM `karyawan` WHERE `ID`='$_POST[id]' and ID_user='$_SESSION[id_user]'");
	if(!$q){
		$data = array('status'=>0,'msg'=>mysqli_error($connect));
	}else{
		$data = array('status'=>1);
	}
	echo json_encode($data);
}else{
	$params = $columns = $totalRecords = $data = array();
	$params = $_POST;
	$where = $sqlTot = $sqlRec = "";
	if( !empty($params['search']['value']) ) {   
		$where .=" AND ";
		$where .=" ( nama LIKE '".$params['search']['value']."%' ";
		$where .=" OR email LIKE '".$params['search']['value']."%' ";
		$where .=" OR no_hp LIKE '".$params['search']['value']."%' ) ";
	}
	$sql = "SELECT * FROM `karyawan` WHERE ID_user='$_SESSION[id_user]'";
	$sqlTot .= $sql;
	$sqlRec .= $sql;
	if(isset($where) && $where != '') {

		$sqlTot .= $where;
		$sqlRec .= $where;
	}
	$sqlRec .=  " order by ID asc LIMIT ".$params['start']." ,".$params['length']." ";
	$queryTot = mysqli_query($connect, $sqlTot) or die("database error:". mysqli_error($connect));
	$totalRecords = mysqli_num_rows($queryTot);
	$queryRecords = mysqli_query($connect, $sqlRec) or die("error to fetch $p");
	$items = array();
	$i=0;
	while( $b = mysqli_fetch_array($queryRecords) ) {
		$i++;
		$qt = mysqli_query($connect, "select a.nama_toko from toko a,karyawan_toko b where a.ID=b.ID_toko and b.ID_karyawan='$b[ID]' and a.ID_user='$_SESSION[id_user]'") or die(mysqli_error($connect));
		while($bt=mysqli_fetch_array($qt)){
			$toko = '- '.$bt['nama_toko']."<br>";
		}
		$aksi = '<a href="'.getConfig($connect, 'base_url').'?page='.$p.'&lihat='.$b['ID'].'" class="btn btn-xs bg-grey waves-effect" data-tooltip="true" data-placement="top" title="Lihat"><i class="material-icons">list</i></a>&nbsp;';
		//$aksi.='<a href="'.getConfig($connect, 'base_url').'?page='.$p.'&edit='.$b['ID'].'" class="btn btn-xs bg-blue-grey waves-effect" data-tooltip="true" data-placement="top" title="Edit"><i class="material-icons">edit</i></a>&nbsp;';
		//$aksi.='<button data-delconfirm="be careful, deleting this data may affect other data<br>because this data is interconnected with other data" class="btn bg-red waves-effect btn-xs hapus_ajax" data-id="'.$b['ID'].'" data-p="'.$p.'" data-t="delete" data-token="'.getToken().'" title="Hapus"><i class="material-icons">delete</i></button>';
		$gambar='<img src="assets/images/placeholder.png" data-src="'.getConfig($connect, 'base_url').'/image.php?t=kasir&id='.$b['ID'].'&s=20" style="height:30px;">';
		$items[] = array($i,$gambar,$b['nama'],$b['no_hp'],$b['email'],$toko,$aksi);
	}	
	$json_data = array(
			"draw"            => intval( $params['draw'] ),   
			"recordsTotal"    => intval( $totalRecords ),  
			"recordsFiltered" => intval($totalRecords),
			"data"            => $items  // total data array
			);
	echo json_encode($json_data);
}