<?php

function wareki($currentDate){
	if (strlen(trim($currentDate)) == 0) return "";
	
	$ary = explode(" ", $currentDate);
	$array = explode("-", $ary[0]);
	$yy = $array[0] * 1;
	$mm = $array[1] * 1;
	$dd = $array[2] * 1;
	if ($yy == 0) return "";
	
	if ($yy > 1988){
		$yy -= 1988;
		$nengou = "平成".$yy;
	}
	else if ($yy > 1925) {
		$yy -= 1925;
		$nengou = "昭和".$yy;
	}
	else if ($yy > 1911) {
		$yy -= 1911;
		$nengou = "大正".$yy;
	}
	else {
		$yy -= 1867;
		$nengou = "明治".$yy;
	}
	return $nengou."年".$mm."月".$dd."日";
//	$st = $nengou."年".$mm."月".$dd."日";
//	return mb_convert_encoding($st, "SJIS", "UTF-8");
}

function age($patientId, $currentDate){
	$yy = substr($patientId, 4, 2);
	$mm = substr($patientId, 0, 2);
	$dd = substr($patientId, 2, 2);
	$bday = "19$yy$mm$dd" - 0;
	$yy1 = substr($currentDate, 0, 4);
	$mm1 = substr($currentDate, 5, 2);
	$dd1 = substr($currentDate, 8, 2);
	$now = "$yy1$mm1$dd1" - 0;
	return floor(($now - $bday) / 10000);
}

function showDayTitle($date){
	$yy1 = substr($date, 0, 4);
	$mm1 = substr($date, 5, 2);
	$dd1 = substr($date, 8, 2);
	$hour = substr($date, 11, 2);
	$min = substr($date, 14, 2);
	$sec = substr($date, 17, 2);
	$time = mktime($hour, $min, $sec, $mm1, $dd1, $yy1);
	$w = date("w", $time);
	$weeks = array("日","月","火","水","木","金","土");
	$week = $weeks[$w];
//	$week = mb_convert_encoding($weeks[$w], "SJIS", "UTF-8");
	return date("Y-m-d", $time)."($week)".date("H:i:s", $time);
}
	
function foldCount($buff){
	// 改行された行数を返す
	$array = explode("\n", $buff);
	return count($array);
}

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("\&quot;", $val);
	$val = implode("\"", $array);
	$array = explode("%x8;", $val);
	$val = implode("$", $array);
	$array = explode("%x9;", $val);
	$val = implode("'", $array);
	return $val;
}
	
/////////////////////////////
// DB アクセス 　　　　　　　　//

// DB を開いて該当レコードを読み込む
function openDB(){
	$db=mysql_connect("localhost","root","root") or error_func();
	$db_select=mysql_select_db("NOA");
	mysql_query("set names utf8");
}

function getValue($patientId, $entryDate, $tag){
	$array = explode(".", $tag);
	$table = $array[0];
	$field = $array[1];
	$dateCondition = "`entryDate`<='$entryDate'"; // 過去履歴も印刷
	
	// 該当する診療行為（薬剤、処置名、など）を DB から取り出して返す
	if (strcmp($table, "UniversalSection") == 0){
		$query = "SELECT * FROM `UniversalSection` 
			WHERE `patientId`='$patientId' AND $dateCondition 
			AND `field`='$field'
			ORDER BY `entryDate` DESC";
		$field = "dataString"; // field を UniversalSection 用に置換
	}
	else {
		$query = "SELECT * FROM `$table` 
			WHERE `patientId`='$patientId' AND $dateCondition
			ORDER BY `entryDate` DESC";
	}
	
	$result=mysql_query($query);
	while ($row=mysql_fetch_array($result)){
		if (strlen($row[$field]) > 0)
            return $row[$field];
//			return mb_convert_encoding($row[$field], "SJIS", "UTF-8");
	}
	return "";
}

function getUserInfo($loginName, $tag){
	$array = explode(".", $tag);
	$table = $array[0];
	$field = $array[1];
	
	// 該当する診療行為（薬剤、処置名、など）を DB から取り出して返す
	$query = "SELECT * FROM `$table` WHERE `loginName`='$loginName'";
	$result=mysql_query($query);
	if (mysql_num_rows ($result) > 0){
		while ($row=mysql_fetch_array($result)){
			if ($row[$field])
                return $row[$field];
//				return mb_convert_encoding($row[$field], "SJIS", "UTF-8");
		}
	}
	return "*** $tag ***";
}

function codeName($code){
	$key = "/$code";
	$query = "SELECT `name` FROM `PriceList` WHERE `alias`='$key'";
	$result=mysql_query($query);
	if (mysql_num_rows ($result) > 0){
		$row=mysql_fetch_array($result);
		$codeAndName = $row['name'];
		if ($codeAndName){ // "11 初診" 形式から "初診" のみ取り出す
			$array = explode(" ", $codeAndName);
            return $array[1];
//			return mb_convert_encoding($array[1], "SJIS", "UTF-8");
		}
	}
	return $code;
}

function shohouFormat($value){
	// code^alias^name^point^unitName^min^standard^max^width^effect^memo|...
	// のような形式を処方フィールド形式にして返す
	$records = explode('|', $value);
	$count = count($records);
	$results = array();
	for ($i=0; $i < $count; $i++){
		$ln = trim($records[$i]);
		if (strlen($ln) == 0) continue;
		
		$array = explode('^', $ln);
		if (count($array) > 6){
			$code = $array[0];
			$name = $array[2];
			if ($code < 120){
				$unit = $array[6];
				$unitName = $array[4];
				$results[$i] = "$name ( $unit $unitName )";
			}
			else {
				$freq = $array[5];
				$unitName = $array[3];
				$results[$i] = "---------- $name ( $freq $unitName )";
			}
		}
		else
			return $value; // 処方フォーマットではないので、そのまま表示
	}
	return join("\n", $results);
}

function treatmentFormat($value){
	// 1_|_12_|_shosin_|_初診_|__|__|_273
	// isOenFee_|_code_|_alias_|_name_|_dose_|_unitName_|_point
	// のような形式を診療フィールド形式にして返す

	$records = explode("\n", $value);
	$count = count($records);
	for ($i=0; $i < $count; $i++){
		$ln = $records[$i];
		$array = explode("_|_", $ln);
		if (count($array) > 6){
			$isOwnFee = ($array[0]) ? " 自費" : "";
			$code = $array[1] * 1;
			$name = $array[3];
			$dose = $array[4];
			$unitName = trim($array[5]);
			$point = $array[6];
			$unit = ($unitName) ? "($dose $unitName)" : "";
			if ($code == 99){
				// "_|_99_|__|_合計[健保(686 x 3 = 2050)自費(5400)] 7450_|__|__|_"
				$records[$i] = $array[3];
			}
			else {
				$cd = codeName($code);
				$records[$i] = "$cd [".$name." ".$unit."] ".$point." ".$isOwnFee;
			}
		}
		else
			return $value; // 診療フォーマットではないので、そのまま表示
	}
	return join("\n", $records);
}

function get($patientId, $entryDate, $label, $tag, $option){
	$value = getValue($patientId, $entryDate, $tag);
	
	if (strcmp($tag, "ProgressSection.treatment") == 0)
		$value = treatmentFormat($value);
	else if (strcmp($tag, "ProgressSection.prescription") == 0)
		$value = shohouFormat($value);
	
	if (strcmp($option, "wareki") == 0) $value = wareki($value);
	
	return (strlen($label)) ? $label."($value) " : $value;
}

function noaCell($w, $pdf, $label, $tag, $option){
	$contents = trim(get("", $tag, $option));
	if (strlen($contents) == 0) return;

	// "<BR/>" を改行に変換（処方欄などで必要）
	$contents = str_replace("<BR/>", "\n", $contents);

	$pdf->SetFont(KOZMIN,'B', 7);
	
	// separator
	$x = $pdf->GetX(); $y = $pdf->GetY();
	$pdf->Line($x, $y, $x + $w, $y);
	
	// label
	$labelWidth = 12;
	$fieldHeight = 3.5;
	$pdf->SetXY($x, $y);
	$pdf->Cell($labelWidth, $fieldHeight, $label, 0, 0, 'L');
	
	// pregress note
	$pdf->MultiCell($w - $labelWidth, $fieldHeight, $contents, 0, 'L');
}

function hasUpdate($patientId, $entryDate, $table){
	// テーブルの中に当日更新されたものがあれば その数、なければ 0 を返す
	// 当月初めての受診なら 1 を返す
	$from = substr($entryDate, 0, 8)."01 00:00:00";
	$query = "SELECT * FROM `ProgressSection`
		WHERE `patientId`='$patientId'
		AND `entryDate`>'$from' AND `entryDate`<='$entryDate'";
	$result=mysql_query($query);
	$count = 0;
	while ($row=mysql_fetch_array($result)){ // entryDate の数をカウント
		if (strcmp($row['entryDate'], $edate) != 0)
			$count++;
		$edate = $row['entryDate'];
	}
	if ($count == 1) return 1;
	
	// テーブルの中に当日更新されたものがあれば、その数を返す
	$query = "SELECT * FROM `$table`
		WHERE `patientId`='$patientId' AND `entryDate`='$entryDate'";
	$result=mysql_query($query);
	
	return mysql_num_rows($result);
}
	

?>