<?php
if($_POST['t']=='create'){
	$cek=mysqli_num_rows(mysqli_query($connect, "select ID from admin where email='$_POST[email]'"));
	if(!$cek){
		if($_POST['foto']){
			$foto = simpanGambar($_POST['foto'],'assets/images/admin/',75);
		}else{
			$foto = NULL;
		}
		$password = Password($_POST['password']);
		$q=mysqli_query($connect, "INSERT INTO `users` (`nama`, `email`, `password`, `hp`, `foto`, `status`, `date_create`)
										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'=>'This email address is already registered!');
	}
	echo json_encode($data);
}elseif($_POST['t']=='update'){
	$qc=mysqli_query($connect, "select * from admin where email='$_POST[email]'");
	$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 admin where 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 `admin` SET `nama`='$_POST[nama]',`email`='$_POST[email]',`hp`='$_POST[no_hp]', `date_create`='$now',`status`='$_POST[status]' WHERE `ID`='$_POST[id]';");	
		if(!$_POST['old_img']){
			$foto = simpanGambar($_POST['foto'],'assets/images/admin/',50);
			$q=mysqli_query($connect, "UPDATE `admin` set `foto`='$foto' where ID='$_POST[id]'");
		}
		if($_POST['password']){
			$password = Password($_POST['password']);
			$q=mysqli_query($connect, "UPDATE `admin` set `password`='$password' where ID='$_POST[id]'");
	
		}
		if(!$q){
			$data = array('status'=>0,'msg'=>mysqli_error($connect));
		}else{
			if($_POST['id']==$_SESSION['id_user']){
				$_SESSION[ 'nama_user' ] = $_POST['nama'];
				if($foto){
					$_SESSION['foto'] = $foto;
				}
				$data = array('status'=>1,'reloadPage'=>1);
			}else{
				$data = array('status'=>1);
			}
		}
	}
	echo json_encode($data);
}elseif($_POST['t']=='delete'){
	$q=mysqli_query($connect, "select foto from admin where ID='$_POST[id]'");
	$b=mysqli_fetch_array($q);
	if(is_file('assets/images/admin/'.$b['foto'])){
		unlink('assets/images/admin/'.$b['foto']);
	}
	$q=mysqli_query($connect, "DELETE FROM `admin` 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 .=" ( nama LIKE '".$params['search']['value']."%' ";
		$where .=" OR email LIKE '".$params['search']['value']."%' ";
		$where .=" OR hp LIKE '".$params['search']['value']."%' ) ";
	}
	$sql = "SELECT * FROM `admin`";
	$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++;
		if($b['ID']!=$_SESSION['id_user']){
			$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>';
		}else{
			$aksi='-';
		}
		$gambar='<img src="assets/images/placeholder.png" data-src="'.getConfig($connect, 'base_url').'/image.php?t=admin&id='.$b['ID'].'&s=20" style="height:30px;">';
		$status=($b['status']=='1')?'<span class="label bg-blue">Aktif</span>':'<span class="label bg-red">Nonaktif</span>';
		$items[] = array($i,$gambar,$b['nama'],$b['hp'],$b['email'],$status,$b['date_create'],$aksi);
	}	
	$json_data = array(
			"draw"            => intval( $params['draw'] ),   
			"recordsTotal"    => intval( $totalRecords ),  
			"recordsFiltered" => intval($totalRecords),
			"data"            => $items  // total data array
			);
	echo json_encode($json_data);
}