<?php
include_once("../../includes/var.php");
include_once("../../libs/utils.php");
include_once("../../libs/functions.php");

header("Content-Type: text/html;charset=".CS_ENCODING); //編碼

$sid = (isset($_GET["sid"])) ? $_GET["sid"] : "";
$mode = (isset($_GET["mode"])) ? $_GET["mode"] : "";
$act = (isset($_GET["act"])) ? $_GET["act"] : "";

$parary = createsidobject($sid);
if (empty($parary)) {
	header("Location: ../../shell.php");
	exit();
}
$dbo = $parary["dbo"];$ln = $parary["ln"];$user = $parary["user"];
include_once("../../classes/class.Locale_DB.php");
$lo = new Locale($ln, $dbo, 0);

$data = array();$output = array();

$item_id = "WEBRPTDEFAULT";

$cfret = get_cwconfig_setup($dbo, TYPE_FETCH_ARRAY);

switch ($act) {
	case "newERI": // Create ERI
		echo get_ERI($dbo, $_GET["table"]);
		return;
		break;

	case "pfm":
		if (empty($pname)) {
			$output["result"] = "false";
			$output["message"] = "No data can be pfm!";
			echo json_encode(array(0 => $output));
			return;
		}
		if (isset($cfret[0]["RPTROOT"]) && trim($cfret[0]["RPTROOT"]) != "" && 
			isset($cfret[0]["RPTFOLDER"]) && trim($cfret[0]["RPTFOLDER"]) != "" && 
			file_exists($cfret[0]["RPTROOT"]."/reports/".$cfret[0]["RPTFOLDER"]."/")) {
			$rptfile = str_replace("\\","/",$cfret[0]["RPTROOT"]."/reports/".$cfret[0]["RPTFOLDER"]."/");
			$pfile = glob($rptfile.$pname."*");
			if (!empty($pfile)) {
				$dnum = count($pfile);
				for ($i = 0; $i < $dnum; $i++) {
					$format[$i]["key"] = Encodehtml(str_replace($rptfile, "", $pfile[$i]));
				}
			} else {
				$format[0]["key"] = "";
			}
		} else {
			$format[0]["key"] = "";
		}
		$output["result"] = "true";
		$output["message"] = "";
		$output["data"] = $format;
		echo json_encode(array(0 => $output));
		return;
		break;

	case "save":
		$verlen = (isset($_GET["verlen"])) ? $_GET["verlen"] : 0;
		if ($verlen == mb_strlen($_POST["htmljson"],"utf-8")) {
			$data_ary = json_decode($_POST["htmljson"],true);
		} else {
			$output["result"] = "false";
			$output["message"] = $lo->text("ERROR_POST_JSON_NOT_LEN");
			echo json_encode(array(0 => $output));
			return;
		}
		$sql = "delete from WEBRPTDEFAULT;";
		$res = $dbo->execute($sql);
		$error = trim($dbo->getMessage());
		if ($error) {
			$output["result"] = "false";
			$output["message"] = "SQL: ".$sql."\n".$error."\n";
			echo json_encode(array(0 => $output));
			return;
		}
		$sql = "";
		// Insert new settings
		if (!empty($data_ary[$item_id."_ERI"])) {
			if (is_array($data_ary[$item_id."_ERI"])) {
				for ($i = 0; $i < count($data_ary[$item_id."_ERI"]); $i++) {
					$sql .= "insert into WEBRPTDEFAULT ".
							"(ERI, LASTUPD, ".
							" SERNO, PRNAME, PRCNAME, RPTFILE, FORMAT) ".
							"values ".
							"(dbo.SOPHIAERI('WEBRPTDEFAULT'), dbo.FUNC_GET_LASTUPD(), ".
							" N'".$data_ary[$item_id."_SERNO"][$i]."', ".
							" N'".$data_ary[$item_id."_PRNAME"][$i]."', ".
							" N'".$data_ary[$item_id."_PRCNAME"][$i]."', ".
							" N'".$data_ary[$item_id."_RPTFILE"][$i]."', ".
							" N'".$data_ary[$item_id."_FORMAT"][$i]."'); ";
				}
			} else {
				$sql .= "insert into WEBRPTDEFAULT ".
						"(ERI, LASTUPD, ".
						" SERNO, PRNAME, PRCNAME, RPTFILE, FORMAT) ".
						"values ".
						"(dbo.SOPHIAERI('WEBRPTDEFAULT'), dbo.FUNC_GET_LASTUPD(), ".
						" N'".$data_ary[$item_id."_SERNO"]."', ".
						" N'".$data_ary[$item_id."_PRNAME"]."', ".
						" N'".$data_ary[$item_id."_PRCNAME"]."', ".
						" N'".$data_ary[$item_id."_RPTFILE"]."', ".
						" N'".$data_ary[$item_id."_FORMAT"]."'); ";
			}
		}
		if (!empty($sql)) {
			$res = $dbo->execute($sql);
			$error = trim($dbo->getMessage());
			if ($error) {
				$output["result"] = "false";
				$output["message"] = "SQL: ".$sql."\n".$error."\n";
				echo json_encode(array(0 => $output));
				return;
			}
		}
		$output["result"] = "true";
		$output["message"] = "";
		echo json_encode(array(0 => $output));
		return;
		break;

	case "xml_out": // xml_out
		if (empty($_POST)) {
			$output["result"] = "false";
			$output["message"] = "No data can be xml out!";
			echo json_encode(array(0 => $output));
			return;
		}
		$sql = "SELECT * ".
			   "FROM WEBRPTDEFAULT ".
			   "WHERE ERI IS NOT NULL ".
			   "ORDER BY SERNO; ";
		if (!sql_to_xml($dbo, $sql, "WEBRPTDEFAULT", "../../xml/RptXML/")) {
			$output["result"] = "false";
			$output["message"] = "XML export failed!";
			echo json_encode(array(0 => $output));
			return;
		}
		$output["result"] = "true";
		$output["message"] = "";
		echo json_encode(array(0 => $output));
		return;
		break;

	case "xml_in":
		$xml = xml_to_array("WEBRPTDEFAULT", TYPE_FETCH_ARRAY, "../../xml/RptXML/");
		if (empty($xml)) {
			$output["result"] = "false";
			$output["message"] = "XML import failed!";
			echo json_encode(array(0 => $output));
			return;
		} else {
			$sql = "DELETE FROM WEBRPTDEFAULT;";
			for ($i = 0; $i < count($xml); $i++) {
				$xfid = "";
				$xval = "";
				foreach ($xml[$i] as $key => $val) {
					if ($key == "ERI" || $key == "LASTUPD") continue;
					if (!empty($xfid)) $xfid .= ",";
					$xfid .= $key;
					if (!empty($xval)) $xval .= ",";
					if (is_numeric($val)) {
						$xval .= "N'".$val."'";
					} else {
						if (empty($val)) $xval .= "N''";
						else $xval .= sql_type_save_str("edNormal",str_replace("'","''",$val));
					}
				}
				$sql .= "INSERT INTO WEBRPTDEFAULT(ERI,LASTUPD,".$xfid.")".
						"VALUES(dbo.SOPHIAERI('WEBRPTDEFAULT'), dbo.FUNC_GET_LASTUPD(),".$xval.");";
			}
			if (!empty($sql)) {
				$res = $dbo->execute($sql);
				$error = trim($dbo->getMessage());
				if ($error) {
					$output["result"] = "false";
					$output["message"] = "SQL: ".$sql."\n".$error."\n";
					echo json_encode(array(0 => $output));
					return;
				}
			}
		}
		$output["result"] = "true";
		$output["message"] = "";
		echo json_encode(array(0 => $output));
		return;
		break;

	default:
		// Fetch existed settings
		$sql = "SELECT dbo.SOPHIAERI('WEBRPTDEFAULT')AS ERI,'作業項報表' AS CSYS,A.REPORTNAME AS PRCSYS,A.REPORTCNAME AS PRCNAME,A.REPORTENAME AS PRNAME,D.RPTFILE,D.FORMAT ".
			   "FROM REPORTFILEM AS A ".
			   "LEFT JOIN WEBRPTDEFAULT AS D ON D.PRNAME = A.REPORTENAME ".
			   "UNION ".
			   "SELECT A.ERI,'報表作業項' AS CSYS,A.FORMNAME AS PRCSYS,A.PRINTFORMNAME AS PRCNAME,A.PRINTPAPERNO AS PRNAME,D.RPTFILE,D.FORMAT ". 
			   "FROM PRINTFORM AS A ".
			   "LEFT JOIN WEBRPTDEFAULT AS D ON D.PRNAME = A.PRINTPAPERNO ".
			   "ORDER BY CSYS,PRCSYS,PRCNAME;";
		$res = $dbo->execute($sql);
		$error = trim($dbo->getMessage());
		if ($error) echo "SQL: ".$sql."<br>".$error."<br>";
		else $data = fetch_query_result($res, TYPE_FETCH_ARRAY);
		// 取fr3
		if (isset($cfret[0]["RPTROOT"]) && trim($cfret[0]["RPTROOT"]) != "" && 
			isset($cfret[0]["RPTFOLDER"]) && trim($cfret[0]["RPTFOLDER"]) != "" && 
			file_exists($cfret[0]["RPTROOT"]."/reports/".$cfret[0]["RPTFOLDER"]."/")) {
			$rptfile = str_replace("\\","/",$cfret[0]["RPTROOT"]."/reports/".$cfret[0]["RPTFOLDER"]."/");
			$pfile = glob($rptfile."*");
			if (!empty($pfile)) {
				$dnum = count($pfile);
				for ($i = 0; $i < $dnum; $i++) {
					$pfile[$i] = str_replace($rptfile, "", $pfile[$i]);
				}
			} else {
				$pfile = array();
			}
		} else {
			$pfile = array();
		}
		break;
}

include_once("../../classes/general/class.CSTemplate.php");
$cst = new CSTemplate();

$page = "index.html";
$cst->set("SID", $sid);
$cst->set("mode", $mode);
$cst->set("locale_obj", $lo);
$cst->set("item_id", $item_id);
$cst->set("data", $data);
$cst->set("pfile", $pfile);
$cst->show($page);
?>