<?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();

$hasil=array("status"=>"GAGAL","pesan"=>"Terjadi kesalahan","data"=>array());

if(!isset($_SESSION['profile']) && $_SESSION['profile']['level']<20) {
	$hasil['pesan']="ERROR UPLOAD";
	echo json_encode($hasil,true);
	exit;
}
if(!$db->ceckmodule($dest_module)){
	$hasil['pesan']="Tidak diijinkan";
	echo json_encode($hasil,true);
	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]);

$jenis=0;
if(isset($data->jenis)){
	$jenis=$data->jenis;
}

if(!$db->cekupload($jenis,$ext)){
	$hasil['pesan']="File Tidak diijinkan";
	echo json_encode($hasil,true);
	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');
		$datain=[
			"iduser"=>$_SESSION['profile']['id'],
			"nama_awal"=>$fileName,
			"nama_baru"=>$filedp,
			"idjenis"=>$data->jenis,
			"ukuran"=>$fileSize,
			"tipefile"=>$ext,
			"folder"=>$folder
		];
		
		$rsin=$db->insert("tb_dokumen",$datain,1);
		
		if($rsin>0){
			$hasil['status']="SUKSES";
			$hasil['pesan']=$fileName;
			$arrdata=array("nama"=>$fileName,"id"=>$rsin,"namabaru"=>$filedp,"folder"=>$folder);
			$hasil['data']=$arrdata;
			
			shell_exec("nohup python ".HOMEDIR."py/ubahgambar.py $rsin > /dev/null 2>&1 &");
		}else{
			$hasil['pesan']="Error input db data dokumen";
		}
		
	}else{
		$hasil['pesan']="Error simpan Upload";
	}
}else{
	$hasil['pesan']="Error sign simpan Upload";
}
echo json_encode($hasil,true);
?>