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

//if(!isset($_SESSION['module'])) exit;
//if($_SESSION['module']["mod_".$dest]!=2) exit;

if(!isset($_SESSION['profile']) || $_SESSION['profile']['level']!=30) {
	echo "{\"status\":\"GAGAL\",\"pesan\":\"ERROR UPLOAD\",\"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(strtolower($ext)!="jpg" && strtolower($ext)!="jpeg" && strtolower($ext)!="png" && strtolower($ext)!="pdf") {
	echo "{\"status\":\"GAGAL\",\"pesan\":\"File Tidak diijinkan\",\"data\":\"NONE\"}";
	exit;
}
$np = $db->gentoken(32);
$folder="public_html/upload/";
$filedp= $np.'.'.$ext;
$ftpstream = ftp_connect("localhost");
$login = ftp_login($ftpstream, FTPUSER, FTPPASSWORD);

$filePath = $folder.$filedp;
$iduser=$_SESSION['profile']['id'];
if($login){
	$origin = ftp_pwd($ftpstream);
	$fp = fopen($tmp, 'r');
	if(!@ftp_chdir($ftpstream, $folder)){
		ftp_mkdir($ftpstream,$folder);
	}
	ftp_chdir($ftpstream, $origin);
	$upl = ftp_fput($ftpstream, $filePath, $fp, FTP_BINARY);
	fclose($fp);
	
	include('../include/lib/imagic/php_image_magician.php');
	list($width, $height, $type, $attr) = getimagesize("../upload/".$filedp);
	$skala=420/$width;
	$newh=$height*$skala;
	
	$imgRz = new imageLib("../upload/".$filedp);
	$imgRz->resizeImage(420, $newh, 'auto', false);
	
	$file = $imgRz->objImage($ext);
	ob_start();
	imagejpeg($file, NULL, 100);
	$background = ob_get_clean();
	
	$filePathrz = 'public_html/upload/thumb/thumb_'.$filedp;
	//error_log("PATH2 ".$filePathrz);
	$temp=tmpfile();
	fwrite($temp, $background);
	fseek($temp,0);
	$uplthumb = ftp_fput($ftpstream, $filePathrz, $temp, FTP_BINARY);
	//error_log("UPLOAD ".$upl);
	fclose($temp);
	
	ftp_close($ftpstream);
	if($upl && $uplthumb){
		$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,'upload'),1);
		$hasil=array("nama"=>$fileName,"id"=>$rs);
		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\"}";
}

?>