<?php
include("CheckSession.php");
?>

<?php
require_once("class/DBConfig.php");
require_once("class/DBOperation.php");

require_once("class/FileConfig.php");
require_once("class/FileOperation.php");

$fo = new FileOperation();

$CUser = "";
if($_POST["AId"] == null || $_POST["AId"] == "")
{
	$CUser = $_SESSION['userId'];
}
else
{
	$CUser = $_POST["AId"];
}

$CMemo = $_POST["CMemo"];

$db = new DBOperation();
if (!empty($_FILES)) 
{ 
    $db->connect_db($_DB['host'], $_DB['username'], $_DB['password'], $_DB['dbname']);
    
		$orgfilName = $_FILES['Filedata']['name'];
		$newfilName = Date('YmdHis').$_FILES['Filedata']['name'];
		//$baseNewFileName = $fo->get_basename(rtrim($newfilName, '/'));
		//$baseOrgFileName = $fo->get_basename(rtrim($orgfilName, '/'));
		$useuploadfile = $_FILECONFIG['UsedDir'].basename($newfilName);
		$backupuploadNewfile = $_FILECONFIG['BackUpDir'].basename($newfilName);
		$backupuploadOrgfile = $_FILECONFIG['BackUpDir'].basename($orgfilName);
		
		if(!move_uploaded_file($_FILES['Filedata']['tmp_name'], iconv("utf-8", "big5", $backupuploadOrgfile)))
		{
			echo '<script type="text/javascript">';
  		echo 'alert("檔案上傳失敗!!!!");';
  		echo 'location.href="FileDataIndex.php?page=1"';
  		echo '</script>';
  		exit();
		}
		if(!copy(iconv("utf-8", "big5", $backupuploadOrgfile), iconv("utf-8", "big5", $backupuploadNewfile)))
		{
			echo '<script type="text/javascript">';
  		echo 'alert("檔案複製失敗!!!!");';
  		echo 'location.href="FileDataIndex.php?page=1"';
  		echo '</script>';
  		exit();
		}
		if(!copy(iconv("utf-8", "big5", $backupuploadNewfile), iconv("utf-8", "big5", $useuploadfile)))
		{
			echo '<script type="text/javascript">';
  		echo 'alert("檔案備份失敗!!!!");';
  		echo 'location.href="FileDataIndex.php?page=1"';
  		echo '</script>';
  		exit();
		}		
					
		$insertSql = "INSERT INTO FileData (CMemo, CNewFileName,COrgFileName,CCreateDateTime,CUpdateDateTime,CCreateAcc,CRealCreator)"
	          ."VALUES ('".$db->mysql_real_escape_string($CMemo)."'"
	          .",'".$db->mysql_real_escape_string($newfilName)."'"
	          .",'".$db->mysql_real_escape_string($orgfilName)."'"
	          .",'".Date('Y-m-d H:i:s')."'"
	          .",'".Date('Y-m-d H:i:s')."'"
	          .",'".$db->mysql_real_escape_string($CUser)."'"
	          .",'".$db->mysql_real_escape_string($_SESSION['userId'])."')";
		$db->query($insertSql);
    $db->close_db();
}  
	//echo '<script type="text/javascript">';
  //echo 'alert("新增成功!!!!");';
  //echo 'location.href="FileDataIndex.php?page=1"';
  //echo '</script>';
?>