<meta http-equiv="Conten-Type" content="text/html; charset=UTF-8">

<?php


//////////////////////////////////////////////
///// バージョンアップした DB との互換性チェック /////
// ### 古いバージョンの DB 構造を更新する目的なので 2010 年には廃止予定 ###

function hasField($_dbname, $_tablename, $_fieldname){
	// $db_name 中に $_tablename があれば 1 を、なければ 0 を返す
	$result = mysql_query("SHOW COLUMNS FROM $_tablename");
	if ($result) {
		if (mysql_num_rows($result) > 0) {
			while ($row = mysql_fetch_assoc($result)) {
				$fieldname = $row['Field'];
				//echo "$_tablename ..... $fieldname \n";
				if (strcmp($fieldname, $_fieldname) == 0) return TRUE;
			}
		}
	} else 
		echo 'Could not run query: ' . mysql_error();
	return FALSE;
}

function checkDatabseStructure(){
	// DB 構造をチェック、必要なら新しい構造に調整
	if (! hasField('NOA', 'FrontTable', 'plan')){
		// FrontTable に plan を追加
		$sql = "ALTER TABLE `FrontTable` 
		ADD `plan` VARCHAR( 512 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL AFTER `kanjiName`";
		echo "$sql ======<br>"; //##
		$result = mysql_query($sql);
	}
	if (! hasField('NOA', 'FrontTable', 'point')){
		// FrontTable に plan を追加
		$sql = "ALTER TABLE `FrontTable` 
		ADD `point` FLOAT AFTER `newPatient`";
		echo "$sql ======<br>"; //##
		$result = mysql_query($sql);
	}
}

///// バージョンアップした DB との互換性チェック /////
//////////////////////////////////////////////
	
	
	
function _FRONT_layout($userCode){
	if ($userCode == 4){
		$_control['inOut']="on";
		$_control['monthB']="on";
		$_control['planB']="on";
		$_control['registF']="on";
		$_control['optionB']="on";
		$_control['checkAverage']="on";
		$results['controls']=$_control;
		$_dayly[]="予約";
		$_dayly[]="受付";
		$_dayly[]="PID";
		$_dayly[]="氏名";
		$_dayly[]="新患";
		$_dayly[]="本人";
		$_dayly[]="家族";
		$_dayly[]="国保";
		$_dayly[]="自費";
		$_dayly[]="未収";
		$_dayly[]="合計";
		$_dayly[]="受取";
		$_dayly[]="診療待";
		$_dayly[]="会計待";
		$_dayly[]="編集";
		$_dayly[]="会計";
		$results['daily']=$_dayly;
		$_monthly[]="日付";
		$_monthly[]="人数";
		$_monthly[]="新患";
		$_monthly[]="本人";
		$_monthly[]="家族";
		$_monthly[]="国保";
		$_monthly[]="自費";
		$_monthly[]="合計";
		$_monthly[]="未収";
		$results['monthly']=$_monthly;
	} else {
		$_control['inOut']="on";
		$_control['registF']="on";
		$_control['planB']="on";
		$results['controls']=$_control;
		$_dayly[]="予約";
		$_dayly[]="受付";
		$_dayly[]="PID";
		$_dayly[]="氏名";
		$_dayly[]="新患";
		$_dayly[]="本人";
		$_dayly[]="家族";
		$_dayly[]="国保";
		$_dayly[]="自費";
		$_dayly[]="未収";
		$_dayly[]="合計";
		$_dayly[]="会計";
		$_dayly[]="受取";
		$_dayly[]="釣銭";
		$_dayly[]="会計待";
		$results['daily']=$_dayly;
	}
	
	return $results;
}
	
    function decodeSTRING($val){
        // #, &, +  < > などが URI 送信で化けるため encode して送られたものを decode
        $array = explode("%x0;", $val);
        $val = implode("#", $array);
        $array = explode("%x1;", $val);
        $val = implode("&", $array);
        $array = explode("%x2;", $val);
        $val = implode("+", $array);
        $array = explode("%x3;", $val);
        $val = implode("<", $array);
        $array = explode("%x4;", $val);
        $val = implode(">", $array);
        $array = explode("%x5;", $val);
        $val = implode(" ", $array);
        $array = explode("%x6;", $val);
        $val = implode("\n", $array);
        $array = explode("%x7;", $val);
        $val = implode("\"", $array);
        $array = explode("%x8;", $val);
        $val = implode("$", $array);
        $array = explode("%x9;", $val);
        $val = implode("'", $array);
        /*
         $array = explode("%xa;", $val);
         $val = implode("(", $array);
         $array = explode("%xb;", $val);
         $val = implode(")", $array);
         */
        return $val;
    }
    
function leftBrackets(){
	// $leftBrackets = "\^\[\^" では誤作動
	return "^[^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
}
function rightBrackets(){
	return "^]^"; // encode 中で使う '(' -- クライアント側との約束 lib.js
}

function decodeObject($buff){
	// "key(value)" 形式の文字列を OBJECT に decode して返す
	$obj = array();
	//	echo "decodeObject ===\n$buff\n"; //##
	for ($p=$begin=$nest=0, $len=strlen($buff); $p < $len; $p++){
		$ch = substr($buff, $p, 1);
		if (strcmp($ch, "(") == 0){
			if ($nest == 0){
				$key = trim(substr($buff, $begin, $p - $begin)); // key 終端
				$begin = $p + 1; // value 開始位置
			}
			$nest++;
		} else if (strcmp($ch, ")") == 0){
			if (--$nest == 0){
				if ($nest == 0){
					// value 終端 ( trim しない )
					$value = substr($buff,$begin,$p-$begin);
					$begin = $p + 1; // key 開始位置
				}
				if (ereg(")", $value)){ // まだ入れ子になっているなら
					$obj[$key] = decodeObject($value);
				} else {
					// 特定文字を "(", ")" へ戻す
					$array = explode(leftBrackets(), $value);
					$value = join("(", $array);
					$array = explode(rightBrackets(), $value);
					$value = join(")", $array);
					
					$obj[$key] = $value;
				}
				//echo "$key{".$obj[$key]."}\n"; //##
			}
		}
	}
	return $obj;
}
	
	
function hasTable($_dbname, $_tablename)
{
	// $db_name 中に $_tablename があれば 1 を、なければ 0 を返す
	$result = mysql_list_tables ($_dbname);
	$i = 0;
	while ($i < mysql_num_rows ($result)) {
		$tb_names[$i] = mysql_tablename ($result, $i);
		if ($tb_names[$i]==$_tablename) return 1;
		$i++;
	}
	return 0;
}

function formatedRecord($row){
	$unpaidDate = "";
	$unpaid = 0;
	// $row['mishuu'] は "2009-01-30 19:16:00,3650" のような形式
	$mishuu = $row['mishuu'];
	if ($mishuu && (strlen($mishuu) > 0)){
		$array = explode(",", $mishuu);
		if (count($array) > 1){
			$unpaidDate = $array[0];
			$unpaid = $array[1] * 1;
		}
	}
	
	// ### ここはいずれ json_encode() に変更
	$array = array();
	$array[] = $row['reserved'];
	$array[] = $row['entryDate'];
	$array[] = $row['patientId'];
	$array[] = $row['kanjiName'];
	$array[] = $row['groupCode'];
	$array[] = $row['inOut'];
	$array[] = $row['newPatient'];
	$array[] = $row['insFee'];
	$array[] = $row['ownFee'];
	$array[] = $row['beginTime'];
	$array[] = $row['endTime'];
	$array[] = $row['checkOutTime'];
	$array[] = $row['userCode'];
	$array[] = $unpaidDate;
	$array[] = $unpaid;
	$array[] = $row['receive'];
	$array[] = $row['owner'];
	$array[] = $row['updateTime'];
	$array[] = $row['plan'];
	$array[] = $row['anotherId'];
	
	return encodeArgs($array);
}

function honin($groupCode, $insFee){
	return ($groupCode == 0) ? $insFee : 0;
}
function kazoku($groupCode, $insFee){
	return ($groupCode == 1) ? $insFee : 0;
}
function kokuho($groupCode, $insFee){
	return ($groupCode == 2) ? $insFee : 0;
}
function calcSum($array, $row){
	if (! $array){
		$array = array();
		//$array[0] = 10000;
	}
	$unpaid = 0;
	// $row['mishuu'] は "2009-01-30 19:16:00,3650" のような形式
	$mishuu = $row['mishuu'];
	if ($mishuu && (strlen($mishuu) > 0)){
		$ary = explode(",", $mishuu);
		if (count($ary) > 1){
			$unpaid = $ary[1] * 1;
		}
	}
	
	$array[0] = $array[0] + 1;
	$array[1] = substr($row['entryDate'], 0, 10);
	$array[2] += honin($row['groupCode'], $row['insFee']);
	$array[3] += kazoku($row['groupCode'], $row['insFee']);
	$array[4] += kokuho($row['groupCode'], $row['insFee']);
	$array[5] += $row['ownFee'];
	$array[6] += $unpaid;
	$array[7] += $row['receive'];
	$array[8] += (strlen($row['inOut'])) ? 1 : 0;
	$array[9] += $row['newPatient'];
	$array[10] += $row['point'];
	
	return $array;
}

function getKanjiName($pid){
	$sql = "SELECT `patientKanjiName` FROM `NameSection`
		WHERE `patientId`='$pid' ORDER BY `entryDate` DESC";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	while ($row = mysql_fetch_array($result)){
		$kanjiName = $row['patientKanjiName'];
		if (strlen($kanjiName) > 0)
			return $kanjiName;
	}
	return "";
}
	
function getAnotherId($pid){
	$sql = "SELECT `anotherId` FROM `PatientTable`
	WHERE `patientId`='$pid'";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	while ($row = mysql_fetch_array($result)){
		$anotherId = $row['anotherId'];
		if (strlen($anotherId) > 0)
			return $anotherId;
	}
	return "";
}

function getPlan($patientId, $entryDate){
	// 前回受診時の plan を返す
	$sql = "SELECT `plan` FROM `FrontTable`
	WHERE `patientId`='$patientId' AND `entryDate`<'$entryDate'
	ORDER BY `entryDate` DESC";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	while ($row = mysql_fetch_array($result)){
		return $row['plan'];
	}
	return "";
}
	
function getLastMishuu($pid){
	// PatientTable に記録された未収金を返す
	$sql = "SELECT `unpaid` FROM `PatientTable` WHERE `patientId`='$pid'";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
	$row = mysql_fetch_array($result);
	return $row['unpaid'];
}
	
function putUnpaid($patientId, $unpaid){
	// 未収金を PatientTable に記録
	// $unpaid : "2009-01-30 19:16:00,3650" 形式
	$timestamp = date("Y-m-d H:i:s",time());
	$sql = "UPDATE `PatientTable`
	SET `unpaid`='$unpaid',`updateTime`='$timestamp'
	WHERE `patientId`='$patientId'";
	echo "$sql ------------ \n"; //###
	$result=mysql_query($sql);
}
	
function hasPatientTable($patientId){
	// この患者が PatientTable に登録されているかどうかを返す
	// PatientRegister がアクセスした PatientTable の更新データをピックアップできない
	$sql = "SELECT * FROM `PatientTable` WHERE `patientId`='$patientId'";
	$result=mysql_query($sql);
	return (mysql_num_rows($result) > 0) ? 1 : 0;
}

function hasPatient($patientId, $entryDate){
	// この患者が登録されているかどうかを返す
	// FrontTable の中で $entryDate に登録されているかどうかを返す
	$date = substr($entryDate, 0, 10);
	$sql = "SELECT * FROM `FrontTable`
	WHERE `patientId`='$patientId' AND `entryDate` like '$date%'";
	echo "$sql --- \n"; //###
	$result=mysql_query($sql);
	if (mysql_num_rows($result) > 0){
		$row=mysql_fetch_array($result);
		if ($row['entryDate'] > $row['updateTime']){
			// 過去に予約されていた場合は entryDate を実際の受付時刻に変更
			$timestamp = date("Y-m-d H:i:s",time());
			$row_id = $row['rowid'];
			$sql = "UPDATE `FrontTable` SET `entryDate`='$entryDate',`updateTime`='$timestamp' WHERE `rowid`='$row_id'";
			echo "$sql --- \n"; //###
			echo "予約を本登録に変更しました ------------ \n"; //###
			$result=mysql_query($sql);
		}
		return TRUE;
	}
	return FALSE;
}
	
function putTimeStamp(){
	// データ更新にともなうタイムスタンプを更新する
	$timestamp = date("Y-m-d H:i:s",time());
	$sql = "SELECT `rowid` FROM `FrontTable` WHERE `patientId`='STAMP'";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// STAMP が存在した
		$row=mysql_fetch_array($result);
		// entryDate を timeStamp として更新
		$sql = "UPDATE `FrontTable` SET `updateTime`='$timestamp'
		WHERE `patientId`='STAMP'";
	} else {							// STAMP が存在しなかった
		$sql = "INSERT INTO `FrontTable` (`patientId`,`updateTime` )
		VALUES ('STAMP','$timestamp')";
	}
	mysql_query($sql);
}
function getTimeStamp($entryDate){
	// タイムスタンプと同じものがあれば "same" なければ、旧スタンプを返す
	$sql = "SELECT * FROM `FrontTable` WHERE `patientId`='STAMP'";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// タイムスタンプが存在した
		$row=mysql_fetch_array($result);
		$updateTime = $row['updateTime'];
		
		// タイムスタンプが同じなら "same" を返す
		if ($updateTime == $entryDate) 
			return "same";
		else // FRONT を再描画
			return $updateTime;
	} else { // タイムスタンプが存在しなかった
		return "empty";
	}
}
    
    function getMessage(){
        // メッセージの入ったレコードをサーチ
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='MESSAGE'";
        $result=mysql_query($sql);
        
        echo "GET_MESSAGE:\n"; //##
        $records = array();
        while ($row=mysql_fetch_array($result)){
            $rec = array();
            $rec['sender'] = $row['owner'];
            $rec['receiver'] = $row['mishuu'];
            $rec['message'] = $row['plan'];
            $rec['docId'] = $row['rowid'];
            $rec['updateTime'] = $row['updateTime'];
            $records[] = $rec;
            
            echo $row['plan']."\n"; //##
        }
        return $records;
    }
	
function getSortOrder($owner){
	// Messenger に表示する受付時刻のソート順を返す
	$sql = "SELECT * FROM `FrontTable` 
	WHERE `patientId`='MESSENGER_ORDER' AND `owner`='$owner'";
	$result=mysql_query($sql);
	echo "$sql \n\n"; //##
	if (mysql_num_rows ($result) > 0){	// MESSENGER_ORDER が存在した
		$row=mysql_fetch_array($result);
		return $row['inOut']; // "1" なら降順ソート "0" なら昇順ソート
	} else { // MESSENGER_ORDER が存在しなかった
		return "0";
	}
}	
	
function messagesToFront(){
	// Messenger 用の message list を返す
	$sql = "SELECT * FROM `MenuTable`
	WHERE `tag`='MESSAGE_NOA_TO_FRONT' ORDER BY `freq`";
	echo "$sql \n"; //##
	$array = array();
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		while ($row=mysql_fetch_array($result)){
			$rec = array();
			$rec['menu'] = $row['menu'];
			$rec['freq'] = $row['freq'];
			$array[$row['menu']] = $rec;
		}
	}
	return $array;
}
	
function getUser($loginName){
	$sql = "SELECT * FROM `UserTable` WHERE `loginName`='$loginName'";
	echo "===== getUser\n $sql \n";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		for ($i=0; $row=mysql_fetch_assoc($result); $i++){ // 連想配列で取り出す
			if (strcmp($row['loginName'], $loginName) == 0){
				/*
				 $array = array();
				 $array['kanjiName'] = $row['kanjiName'];
				 $array['identifier'] = $row['identifier'];
				 $array['hospitalId'] = $row['hospitalId'];
				 */
				return $row;
			}
		}
	}
	return null;
}
	
function encodeArgs($array){
	return join("_|_", $array);
}
function decodeArgs($value){
	return explode("_|_", $value);
}
    
    function isInTime($datetime, $fromTime, $toTime){
        // $datetime が $fromTime,$toTime の間にあれば TRUE を返す
        if (strlen($fromTime) == 0) return TRUE;
        if (strlen($toTime) == 0) return TRUE;
        
        $time = substr($datetime, 11, 8);
        if ($time < $fromTime) return FALSE;
        if ($toTime < $time) return FALSE;
        
        return TRUE;
    }
    
    function insScanDate($patientId){
        // patientId の保険証を最後にスキャンした日付を返す
        $results = array();
        $array = array();
        $dir = "../NOA_ARCHIVE/$patientId/Insurance";
        $files = scandir($dir);
        for ($i=0,$count=count($files); $i < $count; $i++){
            $filename = $files[$i];
            if ($filename == ".") continue;
            if ($filename == "..") continue;
            
            // 行頭に "_" のついた削除済みファイルは無視
            if (substr($filename, 0, 1) == "_") continue;
            
            if (strlen($filename) == 0) continue;
            $array[] = $filename; // filename="03234202_20120113165123.JPG" 形式
        }
        rsort($array); // 逆順にソート
        $results['path'] = $dir;
		$results['filename'] = $array[0]; // 直近のファイル名
        return $results;
    }

    function getDir($dir){
        // $dir 内のファイルをリストアップ
        // ##### $dir は HTTP ではなく FILE-SYSTEM の PATH を示す #####
        $files = scandir($dir, 1); // 逆順にソート
        $count=count($files);
        echo "dir($dir) count($count)\n";
        
        for ($i=0; $i < $count; $i++){
            $filename = $files[$i];
            echo "-- ($filename)\n"; //###
            if ($filename == ".") continue;
            if ($filename == "..") continue;
            if (strlen($filename) == 0) continue;
            echo "-- file ($filename)\n"; //###
            
            $array[] = $filename;
        }
        
        $results = array();
        $results['path'] = $dir;
		$results['files'] = $array;
        
        return $results;
    }
    
    function archiveDir($owner){
        // $dir が無ければ作成
        $dir = "../Users";
        //$dir = "../../NOA_ARCHIVE"; // /test/NOA の場合
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        $dir = "../Users/$owner";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        $dir = "../Users/$owner/FRONT_LAYOUT";
        if (! file_exists($dir)){
            // $dir が無ければ作成
            echo "($dir) is not exist, so I'll make directory. \n"; //##
            mkdir($dir);
        }
        
        return $dir;
    }
	
    function save($owner, $filename, $buff){
        $dir = archiveDir($owner);
        $path = "$dir/$filename";
        
        if (!$handle = fopen($path, 'w')) {
            // $filenameを書き出しモードでオープン
            echo "Cannot open file ($path)";
            return FALSE;
        }
        
        if (fwrite($handle, $buff) === FALSE) {
            // オープンしたファイルに$buffを書き込む
            echo "Cannot write to file ($path)";
            return FALSE;
        } else {
            echo "Saved $patientId to file ($path)";
            fclose($handle);
            return TRUE;
        }
    }
	

	

	
$command=$_GET['command']; $command=htmlspecialchars($command);
$patientId=$_GET['patientId']; $patientId=htmlspecialchars($patientId);
$entryDate=$_GET['entryDate']; $entryDate=htmlspecialchars($entryDate);
$entryDate = decodeSTRING($entryDate);
$owner=$_GET['owner']; $owner=htmlspecialchars($owner);
$value=$_GET['value']; $value=htmlspecialchars($value);
$value = decodeSTRING($value); // lib.php

// DB を開く
// ### セキュリティーを保つには、以下のファイルを外からアクセスできない 
// ### directory に置き、以下の cfg.php の pass をそこへ変更
require_once('../XNOA/cfg.php');

$dbc = mysql_connect($db['host'], $db['user'], $db['pwd']);
$db_select=mysql_select_db($db['dbname']);
mysql_query("set names utf8");

if (strcmp($command,"GET_FRONT_LAYOUT") == 0){
	// FRONT のレイアウトを返す
	// DB 構造をチェック、必要なら新しい構造に調整
	checkDatabseStructure();
    
	$args = decodeObject($value);
	$owner = $args['owner'];
    $buff = "";

    // レイアウト属性を読み込む
	$sql = "SELECT * FROM `FieldTable` WHERE `tag`='FRONT' AND `owner`='$owner'";
	$result=mysql_query($sql);
	echo "$sql ========\n"; //###
	$row = mysql_fetch_array($result);
	if ($row){
        // DB の tag=FRONT に記憶されたレイアウトを読込む：JSON 型式の文字列
        $buff = $row['script'];
    }

    echo "<SEPARATOR>";
    echo $buff;
} else if (strcmp($command,"REMOVE_PATIENT") == 0){
	// args  = $entryDate
	
	putTimeStamp(); // タイムスタンプを更新
		
	$sql = "DELETE FROM `FrontTable` 
	WHERE `entryDate`='$entryDate' AND `patientId`='$patientId'";
	mysql_query($sql);
	echo "$sql\n";
	
	// 変更結果を返す
	echo "<SEPARATOR>";
	echo "削除しました";
} else if (strcmp($command,"PUT_PATIENT") == 0){
	// 本日の受診者を FrontTable へ登録
	// 前回受診時の plan を本日へコピー
	// args  = $value
	$array = decodeArgs($value);
	// 以下は patientEditor.php の registNewPatient() を参照
	$entryDate = $array[0]; // "2008-12-01 21:06:02"
	$patientId = $array[1];
	$kanjiName = $array[2];
	$userCode = $array[3];
	$inOut = $array[4];
	$newPatient = $array[5];
	$groupCode = $array[6];
	$insFee = $array[7];
	$ownFee = $array[8];
	// $mishuu は "2009-01-30 19:16:00,3650" 形式
	$mishuu = $entryDate.",".$array[9];
	$receive = $array[10];
	$owner = $array[11];
	$regist_mode = $array[12];
	
	$answer = array();
	
	putTimeStamp(); // タイムスタンプを更新
	
	if (hasPatientTable($patientId) == 0){
		// patientTable に登録されていない患者は FRONT に登録できない
		echo "<SEPARATOR>";
		$answer['mode'] = "0";
		$answer['message'] = "$patientId は未登録です";
		echo json_encode($answer);
		//echo "$patientId は未登録です";
		return;
	}
	
	if (strlen($regist_mode) && hasPatient($patientId, $entryDate)){
		// すでに当日受診歴があれば重複登録しない
		$date = substr($entryDate, 0, 10);
		echo "<SEPARATOR>";
		$answer['mode'] = "1";
		$answer['message'] = "$date: $patientId は既に登録済みです";
		$answer['patientId'] = $patientId;
		$answer['entryDate'] = $entryDate;
		echo json_encode($answer);
		return;
	}

	if (strlen($kanjiName) == 0){ // 漢字名を NameSection から補完する
		$kanjiName = getKanjiName($patientId);
	}
	
	$anotherId = getAnotherId($patientId);
	
	if (strlen($mishuu) == 0){
		// $mishuu は "2009-01-30 19:16:00,3650" 形式
		$mishuu = getLastMishuu($patientId);
	}

	// 前回受診時の plan を得る
	$plan = getPlan($patientId, $entryDate);

	//echo "<SEPARATOR>";
	$sql = "SELECT `rowid` FROM `FrontTable` 
		WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// 同じ patientId と受付時刻 が存在した
		$row=mysql_fetch_array($result);
		$rowid = $row['rowid'];
		$sql = "UPDATE `FrontTable` SET 
			`kanjiName`='$kanjiName',
			`groupCode`='$groupCode',
			`inOut`='$inOut',
			`newPatient`='$newPatient',
			`insFee`='$insFee',
			`ownFee`='$ownFee',
			`mishuu`='$mishuu',
			`receive`='$receive',
			`plan`='$plan',
			`updateTime`='".date("Y-m-d H:i:s",time())."' 
			WHERE `rowid` = $rowid";
		$mode = 0;
	} else {					// 同じ patientId と受付時刻 が存在しなかった
			$sql = "INSERT INTO `FrontTable` (
				`patientId`,
				`anotherId`,
				`kanjiName`,
				`userCode`,
				`groupCode`,
				`inOut`,
				`newPatient`,
				`insFee`,
				`ownFee`,
				`mishuu`,
				`receive`,
				`plan`,
				`entryDate`,
				`updateTime`,
				`owner` )
			VALUES (
				'$patientId',
				'$anotherId',
				'$kanjiName',
				'$userCode',
				'$groupCode',
				'$inOut',
				'$newPatient',
				'$insFee',
				'$ownFee',
				'$mishuu',
				'$receive',
				'$plan',
				'$entryDate',
				'".date("Y-m-d H:i:s",time())."',
				'$owner')";
		$mode = 1;
	}
	echo "$sql ------------ \n"; //###
	mysql_query($sql);
	
	// 変更結果を返す
	echo "<SEPARATOR>";
	if ($mode == 0){
		$answer['mode'] = "2";
		$answer['message'] = "$kanjiName を更新しました";
		echo json_encode($answer);
		//echo "$kanjiName を更新しました";
	} else {
		$answer['mode'] = "3";
		$answer['message'] = "$kanjiName を登録しました";
		echo json_encode($answer);
		//echo "$kanjiName を登録しました";
	}
} else if (strcmp($command,"PUT_BILL") == 0){
	// args: value
	$array = decodeArgs($value);
	$patientId = $array[0];
	$receive = $array[1];
	$unpaid = $array[2]; // "2009-01-30 19:16:00,3650" 形式

	$now = date("Y-m-d H:i:s",time());
	$sql = "UPDATE `FrontTable`
	SET `receive`='$receive',`checkOutTime`='$now'
	,`updateTime`='$now',`mishuu`='$unpaid'  
	WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
	echo "$sql ------------ \n"; //###
	mysql_query($sql);
	
	// 未収金 unpaid を PatientTable へ記録する
	putUnpaid($patientId, $unpaid);
	
	putTimeStamp(); // タイムスタンプを更新
} else if (strcmp($command,"PUT_PLAN") == 0){
	// args: value
	$args = decodeObject($value);
	$patientId = $args['patientId'];
	$entryDate = $args['entryDate'];
	$owner = $args['owner'];
	$plan = $args['plan'];
	$newEntryDate = $args['newEntryDate'];
	echo "$value ------------ \n"; //###
	
	if ($newEntryDate){
		$sql = "UPDATE `FrontTable`
		SET `plan`='$plan',`entryDate`='$newEntryDate' 
		WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
	} else {
		$sql = "UPDATE `FrontTable`
		SET `plan`='$plan'
		WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
	}
	echo "$sql ------------ \n"; //###
	mysql_query($sql);
	echo "<SEPARATOR>";
	
	putTimeStamp(); // タイムスタンプを更新
} else if (strcmp($command,"STAMP_BEGIN_TIME") == 0){
	// args  = $patientId, $entryDate, $owner
	// カルテを開いた時刻: biginTime を刻印する
	$min = substr($entryDate, 0, 10)." 00:00:00";
	$max = substr($entryDate, 0, 10)." 23:59:59";
	
	echo "<SEPARATOR>";
	$sql = "SELECT * FROM `FrontTable`
		WHERE `patientId`='$patientId' 
		AND `entryDate`<='$max' AND `entryDate`>='$min' ";
	//echo "$sql \n"; // ###
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		$row=mysql_fetch_array($result);
		$sql = "UPDATE `FrontTable` SET 
		`beginTime`='".date("Y-m-d H:i:s",time())."',
		`updateTime`='".date("Y-m-d H:i:s",time())."' 
		WHERE `rowid` = '".$row['rowid']."'";
		echo "$sql \n"; // ###
		mysql_query($sql);
	}
} else if (strcmp($command,"PUT_ENDTIME") == 0){
	// FrontTable の診療終了時刻を更新
	// Messenger で使う
	$args = decodeObject($value);
	// client 側との約束ごと
	$entryDate = $args['entryDate'];
	$endTime = $args['endTime'];
	$updateTime = date("Y-m-d H:i:s",time());
	
	// endTime が "" の場合は、会計中止のアラート・パネルを表示
	if (strlen($endTime) == 0){
		$owner = $args['owner'];
		$to = $args['to']; // 不特定多数に対する "*" の場合がある
		$sender = $args['sender'];
		$receiver = $args['receiver'];
		$message = $args['message'];
		$sql = "UPDATE `FrontTable`
		SET `plan`='$message',`owner`='$owner'
		,`kanjiName`='$sender',`mishuu`='$receiver'
		,`anotherId`='$to',`updateTime`='$updateTime' 
		WHERE `patientId`='STAMP'";
		echo "$sql ------------ \n"; //###
		mysql_query($sql);
	}

	$sql = "SELECT * FROM `FrontTable` WHERE `entryDate`='$entryDate'";
	echo "PUT_ENDTIME:\n$sql \n"; //##
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// 同じ受診日時のレコードが存在した
		$sql = "UPDATE `FrontTable` SET 
		`endTime`='$endTime',
		`updateTime`='$updateTime'
		WHERE `entryDate`='$entryDate'";
		mysql_query($sql);
		echo "$sql \n"; //##
		
		putTimeStamp(); // タイムスタンプを更新
		echo "<SEPARATOR>";
		echo "PUT_ENDTIME -- succeeded \n";
	}
/*} else if (strcmp($command,"PUT_MESSAGE") == 0){
    // to@receiver へメッセージを伝える
    // args: value
    $args = decodeObject($value);
    $owner = $args['owner'];
    $sender = $args['sender'];
    $to = $args['to'];
    $receiver = $args['receiver'];
    $message = $args['message'];
    $docId = $args['docId'];
    $updateTime = date("Y-m-d H:i:s",time());
    echo "$value ------------ \n"; //###
    
    if (strlen($docId) > 0){
        // documentId が指定されているので、そのレコードを更新
        $sql = "SELECT * FROM `FrontTable` WHERE `rowid`='$docId'";
        $result=mysql_query($sql);
        
        $row=mysql_fetch_array($result);
        if ($row && ($row['patientId'] == 'MESSAGE')){ // MESSAGE が存在した
            $sql = "UPDATE `FrontTable` SET `plan`='$message',`kanjiName`='$sender',`mishuu`='$receiver',`anotherId`='$to',`owner`='$owner',`updateTime`='$updateTime' WHERE `rowid`='$docId'";
        }
    } else {
        // documentId が指定されていないので新規レコードを追加
        $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='MESSAGE' AND `owner`='$owner' AND `kanjiName`='$sender'";
        $result=mysql_query($sql);
        
        $row=mysql_fetch_array($result);
        if ($row){
            $rowid = $row['rowid'];
            $sql = "UPDATE `FrontTable` SET `plan`='$message',`kanjiName`='$sender',`mishuu`='$receiver',`anotherId`='$to',`owner`='$owner',`updateTime`='$updateTime' WHERE `rowid`='$rowid'";
        } else {
            $sql = "INSERT INTO `FrontTable` (`patientId`,`owner`,`kanjiName`, `anotherId`,`mishuu`,`plan`,`updateTime`) VALUES ('MESSAGE',  '$owner','$sender','$to','$receiver','$message','$updateTime')";
        }
    }
    echo "$sql ------------ \n"; //###
    mysql_query($sql);
    
    echo "<SEPARATOR>";
    echo "$updateTime \nメッセージを $to へ送りました";
    
    // timeStamp を記憶する
    putTimeStamp();*/
} else if (strcmp($command,"PUT_SORT_ORDER") == 0){
	// FrontTable の診療終了時刻を更新
	// Messenger で使う
	$args = decodeObject($value);
	// client 側との約束ごと
	$owner = $args['owner']; // "1" or "0"
	$sortOrder = $args['sortOrder']; // "1" or "0"
	$updateTime = date("Y-m-d H:i:s",time());
	
	$sql = "SELECT `rowid` FROM `FrontTable` 
	WHERE `patientId`='MESSENGER_ORDER' AND `owner`='$owner'";
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// MESSENGER_ORDER が存在した
		$row=mysql_fetch_array($result);
		$sql = "UPDATE `FrontTable` SET 
		`inOut`='$sortOrder',`updateTime`='$updateTime' 
		WHERE `patientId`='MESSENGER_ORDER' AND `owner`='$owner'";
	} else {							// MESSENGER_ORDER が存在しなかった
		$sql = "INSERT INTO `FrontTable` (
		`patientId`,`owner`,`inOut`,`updateTime`)
		VALUES ('MESSENGER_ORDER','$owner','$sortOrder','$updateTime')";
	}
	mysql_query($sql);
	echo "$sql \n"; //##
	echo "<SEPARATOR>";
	
	putTimeStamp(); // timeStamp を更新
} else if (strcmp($command,"GET_DAILY") == 0){
	// FRONT 日計表レコードを返す
	// Messenger 専用だが、いずれ FRONT もこちらを使う
	$args = decodeObject($value);
	$owner = $args['owner'];
	$entryDate = $args['entryDate'];
	$timeStamp = $args['timeStamp'];
	$min = substr($entryDate, 0, 10)." 00:00:00";
	$max = substr($entryDate, 0, 10)." 23:59:59";
	
	// "タイムスタンプ^送信元^メッセージ" を渡す
	// 以前と変わっていなければ "same"
	$results = array();
	$results['timeStamp'] = getTimeStamp($timeStamp);
	$results['message'] = getMessage();
	$results['sortOrder'] = getSortOrder($owner);
	
    if (strlen($args['timeZone'])){
        $array = explode("-", $args['timeZone']);
        $hh = substr($array[0], 0, 2);
        $mm = substr($array[0], 2, 2);
        $fromTime = "$hh:$mm:00";
        $hh = substr($array[1], 0, 2);
        $mm = substr($array[1], 2, 2);
        $toTime = "$hh:$mm:00";
    } else {
        $fromTime = "";
        $toTime = "";
    }
	
	// 日計表のデータを渡す
	if ($results['sortOrder'] == "1"){
		$sql = "SELECT * FROM `FrontTable`
		WHERE `entryDate`<='$max' AND `entryDate`>='$min' 
		ORDER BY `entryDate` DESC";
	} else {
		$sql = "SELECT * FROM `FrontTable`
		WHERE `entryDate`<='$max' AND `entryDate`>='$min' 
		ORDER BY `entryDate`";
	}
	echo "GET_DAILY:\n $sql \n"; //##
	$result=mysql_query($sql);
    $recs = array();
    while ($row=mysql_fetch_array($result)){
        if ($row['patientId'] == 'STAMP') continue;
        if ($row['patientId'] == 'MESSAGE') continue;
        
        // $fromTime が設定されていれば指定された時間帯以外はスキップ
        if (! isInTime($row['entryDate'], $fromTime, $toTime)) continue;
        echo "got ..".$row['entryDate']." \n"; //##
        
        $unpaidDate = "";
        $unpaid = 0;
        // $row['mishuu'] は "2009-01-30 19:16:00,3650" のような形式
        $mishuu = $row['mishuu'];
        if ($mishuu && (strlen($mishuu) > 0)){
            $array = explode(",", $mishuu);
            if (count($array) > 1){
                $unpaidDate = $array[0];
                $unpaid = $array[1] * 1;
            }
        }
        
        $rec = array();
        $dateAndId = $row['entryDate']."^".$row['patientId'];
        $rec['entryDate'] = $row['entryDate'];
        $rec['userCode'] = $row['userCode'];
        $rec['groupCode'] = $row['groupCode'];
        $rec['inOut'] = $row['inOut'];
        $rec['newPatient'] = $row['newPatient'];
        $rec['point'] = $row['point'];
        $rec['insFee'] = $row['insFee'];
        $rec['ownFee'] = $row['ownFee'];
        $rec['mishuu'] = $unpaid;
        $rec['receive'] = $row['receive'];
        $rec['patientId'] = $row['patientId'];
        $rec['anotherId'] = $row['anotherId'];
        $rec['kanjiName'] = $row['kanjiName'];
        $rec['plan'] = $row['plan'];
        $rec['beginTime'] = $row['beginTime'];
        $rec['endTime'] = $row['endTime'];
        $rec['checkOutTime'] = $row['checkOutTime'];
        $rec['updateTime'] = $row['updateTime'];
        $rec['owner'] = $row['owner'];
        $rec['unpaidDate'] = $unpaidDate; // 追加
        // 保険証を最後にスキャンした日付
        $pid = trim($row['patientId']); // 何かの具合で patientId に空白がついていることあり
        $obj = insScanDate($pid);
        $rec['scanDataPath'] = $obj["path"];
        $rec['scanDateTime'] = $obj["filename"]; 
        $recs[$dateAndId] = $rec;
    }
    
    if (count($recs) > 0)
        $results['records'] = $recs;

	echo "<SEPARATOR>";
	echo json_encode($results);
} else if (strcmp($command,"GET_MONTHLY_LIST") == 0){
	// args  = $entryDate
	$args = decodeObject($value);
	// client 側との約束ごと
	$entryDate = $args['entryDate'];
    if ($args['timeZone']){
        $array = explode("-", $args['timeZone']);
        $hh = substr($array[0], 0, 2);
        $mm = substr($array[0], 2, 2);
        $fromTime = "$hh:$mm:00";
        $hh = substr($array[1], 0, 2);
        $mm = substr($array[1], 2, 2);
        $toTime = "$hh:$mm:00";
    } else {
        $fromTime = "";
        $toTime = "";
    }
	$in = $args['in'] * 1;
	$out = $args['out'] * 1;
	$min = substr($entryDate, 0, 8)."01 00:00:00";
	$max = substr($entryDate, 0, 8)."31 23:59:59";
	
	if (($in > 0) && ($out > 0)){	// 入院・外来両方
		$sql = "SELECT * FROM `FrontTable`
		WHERE `entryDate`<='$max' AND `entryDate`>='$min' 
		ORDER BY `entryDate`";
	} else if (($in > 0) && ($out == 0)){	// 入院のみ
		$sql = "SELECT * FROM `FrontTable`
		WHERE `entryDate`<='$max' AND `entryDate`>='$min' AND `inOut`='on'
		ORDER BY `entryDate`";
	} else if (($in == 0) && ($out > 0)){	// 外来のみ
		$sql = "SELECT * FROM `FrontTable`
		WHERE `entryDate`<='$max' AND `entryDate`>='$min' AND `inOut`=''
		ORDER BY `entryDate`";
	} else {
		echo ""; return;
	}
	echo "$sql \n"; //##
	echo "<SEPARATOR>";
	
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		$array = null; 
		$_date = "";
		while ($row=mysql_fetch_array($result)){
			// 年月日を取り出す
            // timeZone にマッチしないものはスキップ
			$datetime = $row['entryDate'];
            if (! isInTime($datetime, $fromTime, $toTime)) continue;
            
			// 日毎の配列にその日の集計をその日のobjectへ収納
			$date = substr($datetime, 0, 10);
			$array[$date] = calcSum($array[$date], $row);
			// 日が変る毎に前日の集計を echo
			if (strcmp($date, $_date) > 0){
				if ($_date != "") echo encodeArgs($array[$_date])."_||_";
			}
			$_date = $date;
		}
		// 最終日の集計を echo
		echo encodeArgs($array[$_date])."_||_";
		return;
	}
	echo "";
} else if (strcmp($command,"GET_MONTHLY_INS_LIST") == 0){
	// args  = $entryDate
	$args = decodeObject($value);
	$date = $args['entryDate'];
    $min = substr($date, 0, 7)."-01 00:00:00";
    $max = substr($date, 0, 7)."-31 23:59:59";
	
    $sql = "SELECT * FROM `FrontTable`
    WHERE `entryDate`<='$max' AND `entryDate`>='$min' 
    ORDER BY `patientId`";

	echo "$sql \n"; //##
	$result=mysql_query($sql);
    $record = array(); 
    while ($row=mysql_fetch_array($result)){
        $patientId = $row['patientId'];
        $record[$patientId] = $row['kanjiName'];
    }
    
	echo "<SEPARATOR>";
    echo json_encode($record);
} else if (strcmp($command,"GET_USER_LIST") == 0){
	// UserTable の内容を配列に入れて返す
	// Messenger で使う
	$results = array();
	
	// user list を作成
	$sql = "SELECT * FROM `UserTable`";
	echo "$sql \n"; //##
	$array = array();
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){
		while ($row=mysql_fetch_array($result)){
			$ary = array();
			$logname = $row['loginName'];
			$ary['kanjiName'] = $row['kanjiName'];
			$ary['hospitalId'] = $row['hospitalId'];
			$array[$logname] = $ary;
			echo "$logname -> ".$ary."\n"; //##
		}
	}
	$results['userList'] = $array;
	
	// Messenger 用の message list を作成
	$results['messageList'] = messagesToFront();
	
	echo "<SEPARATOR>";
	echo json_encode($results);
/*} else if (strcmp($command,"PUT_MESSAGENGER") == 0){
	// MenuTable にメッセージ項目を追加
	$args = decodeObject($value);
	// client 側との約束ごと
	$tag = "MESSAGE_NOA_TO_FRONT";
	$menuItem = $args['menuItem'];
	$owner = $args['owner'];
	$freq = $args['freq'];
	
	$sql = "SELECT * FROM `MenuTable` 
	WHERE `tag`='$tag' AND `menu`='$menuItem'";
	echo "$sql ========\n"; //###
	$result=mysql_query($sql);
	if (mysql_num_rows ($result) > 0){	// 同じ menuItem が存在した
		$row=mysql_fetch_array($result);
		$rowid = $row['rowid'];
		// menuItem は同じなので freq のみ更新
		if ($freq) $freq = $row['freq'] + 1; // 頻度インクリメント
		
		$sql = "UPDATE `MenuTable` 
		SET `freq`='$freq',`owner`='$owner'
		WHERE `tag`='$tag' AND `menu`='$menuItem'";
	} else { // 同じ menuItem が存在しなかった
		$sql = "INSERT INTO `MenuTable` 
		( `tag`,`freq`,`menu`,`value`,`public`,`updateTime`,`owner` )
		VALUES ( '$tag','0','$menuItem','','','','$owner')";
	}
	echo "$sql ========\n"; //###
	mysql_query($sql);
	
	$array = messagesToFront();
	echo "<SEPARATOR>";
	echo json_encode($array);
} else if (strcmp($command,"REMOVE_MESSAGE") == 0){
	// MenuTable からメッセージ項目を削除
	$args = decodeObject($value);
	// client 側との約束ごと
	$tag = "MESSAGE_NOA_TO_FRONT";
	$menuItem = $args['menuItem'];
	$owner = $args['owner'];
	
	$sql = "DELETE FROM `MenuTable` 
	WHERE `tag`='$tag' AND `menu`='$menuItem'";
	echo "$sql ========\n"; //###
	mysql_query($sql);
	
	$array = messagesToFront();
	echo "<SEPARATOR>";
	echo json_encode($array);*/
} else if (strcmp($command,"LOGIN") == 0){
	// Messenger で使う
	$args = decodeObject($value);
	// client 側との約束ごと
	$loginName = $args['loginName'];
	$passwd = $args['passwd'];
	
	$row = getUser($loginName);
	echo $row['identifier']."\n"; //##
	echo md5($passwd)."\n"; //##
	if (strcmp($row['identifier'], md5($passwd)) == 0){
		// 暗号化してから DB 値と比較する
		// <SEPARATOR> の後に文字があれば成功を示す
		echo "<SEPARATOR>";
		echo json_encode($row);
	}
} else if (strcmp($command,"PUT_LAYOUT_PARTS") == 0){
    // 初期設定のパーツ部分を保存
	$args = decodeObject($value);
	$owner = $args['owner'];
	$updateTime = date("Y-m-d H:i:s",time());

    $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='LAYOUT_PARTS' AND `owner`='$owner'";
	echo "$sql ========\n"; //###
	$result=mysql_query($sql);

    // checkBox, firstItem, timeZone をアーカイブした $value のまま格納
	if (mysql_num_rows ($result) > 0){	// 同じ tag が存在した
		$row=mysql_fetch_array($result);
		$rowid = $row['rowid'];
		$sql = "UPDATE `FrontTable` SET `plan`='$value', `updateTime`='$updateTime' WHERE `rowid`='$rowid'";
	} else { // 同じ menuItem が存在しなかった
		$sql = "INSERT INTO `FrontTable` ( `patientId`,`owner`,`plan`,`updateTime` ) VALUES ( 'LAYOUT_PARTS','$owner','$value','$updateTime')";
	}
	echo "$sql ========\n"; //###
	mysql_query($sql);
    
    // 同時にアーカイブも保存
	$st = date("YmdHi",time());
	$filename = "$st.txt";
    if (save($owner, $filename, $value)){
        echo "<SEPARATOR>";
        echo "バックアップを保存しました";
    } else {
        echo "<SEPARATOR>";
        echo "バックアップが保存できませんでした";
    }
} else if (strcmp($command,"GET_LAYOUT_PARTS") == 0){
    // 初期設定のパーツ部分を読み込む
	$args = decodeObject($value);
	$owner = $args['owner'];
    
    $sql = "SELECT * FROM `FrontTable` WHERE `patientId`='LAYOUT_PARTS' AND `owner`='$owner'";
	$result=mysql_query($sql);
	echo "$sql ========\n"; //###
    
	echo "<SEPARATOR>";
	if ($row = mysql_fetch_array($result)){
        echo $row['plan'];
    }
} else if (strcmp($command,"REMOVE_LAYOUT_PARTS") == 0){
    // 初期設定のパーツ部分を削除
	$args = decodeObject($value);
	$owner = $args['owner'];
    
	$sql = "DELETE FROM `FrontTable` WHERE `patientId`='LAYOUT_PARTS' AND `owner`='$owner'";
	mysql_query($sql);
	echo "$sql\n";
	
	// 変更結果を返す
	echo "<SEPARATOR>";
	echo "$owner のレイアウトを削除しました";
} else if (strcmp($command,"GET_ARCHIVE_FILES") == 0){
    // アーカイブのファイル名の配列を取得
    $args = decodeObject($value);
    $owner = $args['owner'];

    $dir = archiveDir($owner);
	echo "dir($dir)"; //###

    $results = getDir($dir);
    //rsort($results); // 逆順にソート
	echo "results($results)"; //###
    
    echo "<SEPARATOR>";
    echo json_encode($results);
} else if (strcmp($command,"GET_ARCHIVE_FILE") == 0){
    // NOA 形式で保存された配列データを読み出す
    $args = decodeObject($value);
    $owner = $args['owner'];
    $filename = $args['filename'];
    
    $dir = archiveDir($owner);
    $path = "$dir/$filename";
    
    echo "<SEPARATOR>";
    $json = file_get_contents($path);
    echo $json;
} else if (strcmp($command,"REMOVE_ARCHIVE_FILE") == 0){
    $args = decodeObject($value);
    $owner = $args['owner'];
    $filename = $args['filename'];
    
    $dir = archiveDir($owner);
    $path = "$dir/$filename";
    unlink($path);
    
    echo "<SEPARATOR>";
    echo "$filename を削除しました";
} else if (strcmp($command,"GET_USERS") == 0){
    // ユーザのリストを返す
    $sql = "SELECT * FROM `UserTable`";
    echo "$sql \n"; //##
    $array = array();
    $result=mysql_query($sql);
    while ($row=mysql_fetch_array($result)){
        $logname = $row['loginName'];
        $rec = array();
        $rec['userCode'] = $row['userCode'];
        $rec['sectionCode'] = $row['sectionCode'];
        $rec['groupCode'] = $row['groupCode'];
        $rec['loginName'] = $row['loginName'];
        $rec['kanjiName'] = $row['kanjiName'];
        $rec['hospitalId'] = $row['hospitalId'];
        $array[$logname] = $rec;
    }
	echo "<SEPARATOR>";
    echo json_encode($array);
} else
	echo "*** Unknown command: $command ***";


?>
