<?php
if($_POST['t']=='create'){
	$cek=mysqli_num_rows(mysqli_query($connect, "select ID from users where user_email='$_POST[email]'"));
	if(!$cek){
		if($_POST['foto']){
			$foto = simpanGambar($_POST['foto'],'assets/images/user/',75);
		}else{
			$foto = NULL;
		}
		$password = Password($_POST['password']);
		$q=mysqli_query($connect, "INSERT INTO `users` (`user_nama`, `user_email`, `password`, `user_hp`, `user_foto`, `user_status`, `user_tgl`)
										VALUES ('$_POST[nama]', '$_POST[email]', '$password', '$_POST[no_hp]', '$foto', '1', '$now');");
		if(!$q){
			$data = array('status'=>0,'msg'=>mysqli_error($connect));
		}else{
			$data = array('status'=>1);
		}
	}else{
		$data = array('status'=>0,'msg'=>'Alamat email ini sudah terdaftar!');
	}
	echo json_encode($data);
}elseif($_POST['t']=='update'){
	$qc=mysqli_query($connect, "select * from users where user_email='$_POST[email]'");
	$cek=mysqli_num_rows($qc);
	if($cek){
		$bc=mysqli_fetch_array($qc);
		if($_POST['email']!=$bc['user_email']){
			$cemail=mysqli_num_rows(mysqli_query($connect, "select ID from users where user_email='$_POST[email]'"));
			if($cemail>0){
				$data = array('status'=>0,'msg'=>'This email address is already registered!');
				$err=1;
			}else{
				$err=0;
			}
		}else{
			$err=0;
		}
	}else{
		$data = array('status'=>0,'msg'=>'Terjadi kesalahan tak terduga!');
		$err=1;
	}
	if($err==0){
		$q=mysqli_query($connect, "UPDATE `users` SET `user_nama`='$_POST[nama]',`user_email`='$_POST[email]',`user_hp`='$_POST[no_hp]', `user_tgl`='$now',`user_status`='$_POST[status]' WHERE `ID`='$_POST[id]';");	
		if(!$_POST['old_img']){
			$foto = simpanGambar($_POST['foto'],'assets/images/user/',50);
			$q=mysqli_query($connect, "UPDATE `users` set `user_foto`='$foto' where ID='$_POST[id]'");
		}
		if($_POST['password']){
			$password = Password($_POST['password']);
			$q=mysqli_query($connect, "UPDATE `users` set `password`='$password' where ID='$_POST[id]'");
	
		}
		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 user_foto from users where ID='$_POST[id]'");
	$b=mysqli_fetch_array($q);
	if(is_file('assets/images/user/'.$b['user_foto'])){
		unlink('assets/images/user/'.$b['user_foto']);
	}
	$q=mysqli_query($connect, "DELETE FROM `users` WHERE `ID`='$_POST[id]'");
	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 .=" ( user_nama LIKE '".$params['search']['value']."%' ";
		$where .=" OR user_email LIKE '".$params['search']['value']."%' ";
		$where .=" OR user_hp LIKE '".$params['search']['value']."%' ) ";
	}
	$sql = "SELECT * FROM `users`";
	$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++;
		$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=user&id='.$b['ID'].'&s=20" style="height:30px;">';
		$status=($b['user_status']=='1')?'<span class="label bg-blue">Aktif</span>':'<span class="label bg-red">Nonaktif</span>';
		$items[] = array($i,$gambar,$b['user_nama'],$b['user_hp'],$b['user_email'],$status,$b['user_tgl'],$aksi);
	}	
	$json_data = array(
			"draw"            => intval( $params['draw'] ),   
			"recordsTotal"    => intval( $totalRecords ),  
			"recordsFiltered" => intval($totalRecords),
			"data"            => $items  // total data array
			);
	echo json_encode($json_data);
}