<?php
if($_POST['t']=='create'){
	if($_POST['gambar_toko']){
		$foto = simpanGambar($_POST['gambar_toko'],'assets/images/toko/',75);
	}else{
		$foto = NULL;
	}
	$url = $_SESSION['id_user'].'-'.create_slug($_POST['nama_toko']);
	$q=mysqli_query($connect, "INSERT INTO `toko` (`ID_user`, `nama_toko`, `alamat_toko`, `gambar_toko`, `url_toko`, `date_create`)
								VALUES ('$_SESSION[id_user]', '$_POST[nama_toko]', '$_POST[alamat_toko]', '$foto', '$url', '$now');");
	if(!$q){
		$data = array('status'=>0,'msg'=>mysqli_error($connect));
	}else{
		$data = array('status'=>1);
	}
	echo json_encode($data);
}elseif($_POST['t']=='update'){
	$url = $_SESSION['id_user'].'-'.create_slug($_POST['nama_toko']);
	$q=mysqli_query($connect, "UPDATE `toko` SET `nama_toko`='$_POST[nama_toko]',`alamat_toko`='$_POST[alamat_toko]', `url_toko`='$url',`date_create`='$now' WHERE `ID`='$_POST[id]' and ID_user='$_SESSION[id_user]';");	
	if(!$_POST['old_img']){
		$foto = simpanGambar($_POST['gambar_toko'],'assets/images/toko/',50);
		$q=mysqli_query($connect, "UPDATE `toko` set `gambar_toko`='$foto' 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);
}elseif($_POST['t']=='delete'){
	$ql=mysqli_num_rows(mysqli_query($connect, "select ID from toko where `ID_user`='$_SESSION[id_user]'"));
	if((int)$ql>1){
		$q=mysqli_query($connect, "select gambar_toko from toko where ID_user='$_SESSION[id_user]' and ID='$_POST[id]'");
		$b=mysqli_fetch_array($q);
		if(is_file('assets/images/toko/'.$b['gambar_toko'])){
			unlink('assets/images/toko/'.$b['gambar_toko']);
		}
		$q=mysqli_query($connect, "DELETE FROM `toko` 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);
		}
	}else{
		$data = array('status'=>0,'msg'=>'Cannot delete a store if there is only one store.');
	}
	echo json_encode($data);
}elseif($_POST['t']=='chart-data'){
	$bulan=$_POST['bulan'];
	$datasets='"datasets": [{';
	$data='"data":[';
	$color='"backgroundColor":[';
	$label='"labels": [';
	$y=date('Y');
	$qi=mysqli_query($connect, "select * from indikator_kategori order by ID asc") or die(mysqli_error($connect));
	$h=0;
	while($bi=mysqli_fetch_array($qi)){
		$q=mysqli_query($connect, "select sum(b.capaian),b.data from capaian b where b.bulan='$bulan' and b.tahun='$y' and b.ID_kategori='$bi[ID]'") or die(mysqli_error($connect));
		while($b=mysqli_fetch_array($q)){
			$data.=(int)$b[0].",";
			$h+=$b[0];
			$color.='"#'.random_color().'",';
		}
		$label.='"'.$bi['nama_kategori'].'",';
	}
		$data = substr($data,0,-1).'],';
		$color = substr($color,0,-1).']';
	$label = substr($label,0,-1).']';
	$datasets.=$data.$color.'}]';
	$cartData = $datasets.','.$label;
	if(!$q){
		$jdata = array('status'=>0,'msg'=>mysqli_error($connect));
	}else{
		$jdata = array('status'=>1,'chart_data'=>$cartData,'r'=>$h);
	}
	echo json_encode($jdata);
}else{
	$params = $columns = $totalRecords = $data = array();
	$params = $_POST;
	$where = $sqlTot = $sqlRec = "";
	if( !empty($params['search']['value']) ) {   
		$where .=" AND ";
		$where .=" ( nama_toko LIKE '".$params['search']['value']."%' ";
		$where .=" OR alamat_toko LIKE '".$params['search']['value']."%' ) ";
	}
	$sql = "SELECT * FROM `toko` 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++;
		$aksi = '<a href="'.getConfig($connect, 'base_url').'?page='.$p.'&chart='.$b['ID'].'" class="btn btn-xs bg-blue waves-effect" data-tooltip="true" data-placement="top" title="Grafik"><i class="material-icons">multiline_chart</i></a>&nbsp;';
		$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=toko&id='.$b['ID'].'&s=20" style="height:30px;">';
		$items[] = array($i,$gambar,$b['nama_toko'],$b['alamat_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);
}