<?php
if (!defined("root")) {
	define("root", $_SERVER['DOCUMENT_ROOT']);
}
require(root."/___simple_config.php");
session_start();
require(root."/".adminFolder."/_common.php");
require(root."/".adminFolder."/_lib/db.php");
require(root."/".adminFolder."/_lib/main.php");
$formodule = trim(cekpost(cleanQuery($_GET["formodule"]), ""));
$kd = cekpost(cleanQuery($_GET["kd"]), "0");
$tipeform = cekpost(cleanQuery($_GET["tipeform"]), "");
$tipedata = cekpost(cleanQuery($_GET["tipedata"]), "");
#tipeform = 0=single file or 1=multiple files
#tipedata = 0=image or 1=others
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if ($formodule=="teachers") {
	$rs=array(); $q="SELECT * FROM m_teachers WHERE kdteacher='$kd' AND isdeleted=0";
	callRS($rs, $q);
}
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
	$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
	
	if(!in_array(strtolower($extension), $allowed)){
		echo '{"status":"error"}';
		exit;
	}
	$mainDir = "../../../files/";
	
	
	if ($tipe!=0 && $kdpost!=0) {
		if ($formodule=="teachers") {
			$maxWidth = 300; $maxHeight = 300;
		}
	}
	if (file_exists($mainDir)) {
		$createdDir = $mainDir;
	} else {
		$createdDir = createDirectory2($mainDir);
	}
	if ($createdDir[strlen($createdDir)-1]!="/") $createdDir=$createdDir."/";
	$createdDir = str_replace("//", "/", $createdDir);
	$nnfile = $_FILES['upl']['name'];
	$flag = 0;
	do {
		$rscek = array(); $qcek = "SELECT original_file_name FROM u_files WHERE original_file_name = '$nnfile'";
		callRS($rscek, $qcek);
		if (count($rscek)!=0) {
			$flag = 0;
			$nnfile = "_".$nnfile;
		} else {
			$flag = 1;
		}
	} while ($flag==0);
	$fullOriName = $path.$nnfile;
	if(move_uploaded_file($_FILES['upl']['tmp_name'], $createdDir.$nnfile)){
		$now = time();
		$newName = $now.".".$ext;
		$path = $createdDir;
		$fullNewName = $path.$newName;
		smartCopy($fullOriName, $fullNewName);
		if ($tipedata=="0") {
			if ($formodule=="teachers") {
				$maxWidth = 300; $maxHeight = 300;
			}
			$tmpFileName = $path.$now."_$maxWidth.".$ext;
			smartCopy($fullNewName, $tmpFileName);
			smart_resize_image($tmpFileName, $maxWidth, $maxHeight, true, 'file', true, false);
		}
		$upby = $_SESSION["user"]["inisial"];
		$uptime = time();
		if ($formodule=="teachers") {
			$qi = "INSERT INTO u_files (kdteacher, file_type, full_path, original_file_name, current_file_name, file_ext, image_alt, image_title, upby, uptime) 
				VALUES ('$kddata', '$type', '$fullNewName', '$nnfile', '$newName', '$ext', '$image_alt', '$image_title', '$upby', '$uptime')";
			execRS($qi);
			$act_ket = "Teachers: Image: [kd: $kdteacher][nama: ".$rs[0]["nama"]."][file: ".$nnfile."]";
		}
		updateUserActivities($act_ket);
		echo '{"status":"success"}';
		exit;
	}
}

echo '{"status":"error"}';
exit;