<?php
if(count(get_included_files()) ==1) exit("Direct access not permitted.");
require_once('include/global.php');
if (!isset($_SESSION)) session_start();
date_default_timezone_set('Asia/Jakarta');
$db=pDatabase::getInstance();

if(!isset($_SESSION['profile']) && $_SESSION['profile']['level']<20) {
	echo "{\"status\":\"GAGAL\",\"pesan\":\"ERROR UPLOAD\",\"data\":\"NONE\"}";
	exit;
}

if(!$db->ceckmodule($dest_module)){
	echo "{\"status\":\"GAGAL\",\"pesan\":\"Akses Tidak diijinkan\",\"data\":\"NONE\"}";
	exit;
}

$genfl=$_POST['APC_UPLOAD_PROGRESS'];
$fileName = $_FILES["file_".$genfl]['name'];  
$fileSize = $_FILES["file_".$genfl]['size'];  
$fileError = $_FILES["file_".$genfl]['error']; 
$tmp = $_FILES["file_".$genfl]['tmp_name'];

$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$data=json_decode($_POST['upload_data_'.$genfl]);
//error_log($genfl);
$jenis=0;
if(isset($data->jenis)){
	$jenis=$data->jenis;
}
if(!$db->cekupload($jenis,$ext)){
	echo "{\"status\":\"GAGAL\",\"pesan\":\"File Tidak diijinkan\",\"data\":\"NONE\"}";
	exit;
}

$np = $db->gentoken(32);
$folder=$db->getfolder($jenis);

$filedp= $np.'.'.$ext;
$ftpstream = ftp_connect("localhost");
$login = ftp_login($ftpstream, FTPUSER, FTPPASSWORD);

$filePath = "public_html/".$folder.$filedp;
$iduser=$_SESSION['profile']['id'];
if($login){
	$origin = ftp_pwd($ftpstream);
	$fp = fopen($tmp, 'r');
	if(!@ftp_chdir($ftpstream, "public_html/".$folder)){
		ftp_mkdir($ftpstream,"public_html/".$folder);
	}
	ftp_chdir($ftpstream, $origin);
	$upl = ftp_fput($ftpstream, $filePath, $fp, FTP_BINARY);
	fclose($fp);
	
	ftp_chdir($ftpstream, $origin);
	ftp_chmod($ftpstream, 0644, $filePath);
	
	ftp_close($ftpstream);
	if($upl){
		$now = date('Y-m-d H:i:s');
		$query="INSERT INTO tb_dokumen (iduser,tanggal,nama_awal,nama_baru,idjenis,ukuran,tipefile,folder) 
			VALUES (?,?,?,?,?,?,?,?)";
		$rs=$db->query($query,array($iduser,$now,$fileName,$filedp,$data->jenis,$fileSize,$ext,$folder),1);
		$hasil=array("nama"=>$fileName,"id"=>$rs,"namabaru"=>$filedp);
		
		if($rs){
			echo "{\"status\":\"SUKSES\",\"pesan\":\"".$fileName."\",\"data\":".json_encode($hasil)."}";
		}else{
			echo "{\"status\":\"GAGAL\",\"pesan\":\"Error db\",\"data\":\"NONE\"}";
		}
		
	}else{
		echo "{\"status\":\"GAGAL\",\"pesan\":\"Upload gagal\",\"data\":\"NONE\"}";
	}
}else{
	echo "{\"status\":\"GAGAL\",\"pesan\":\"Upload gagal\",\"data\":\"NONE\"}";
}

?>