<?php
	
	////////////////////////////////
	// print ALL PAGES with FPDF  //
	////////////////////////////////
	
	define('FPDF_FONTPATH','/Applications/MAMP/htdocs/FPDF/fpdf153/font/');
	require('../FPDF/fpdf153/mbfpdf.php');
	
	function headerWidth(){
		return 160;
	}
    
    function topMargin(){
        return 15;
    }
	
	function leftMargin(){
		return 10;
	}
	
	function lineHeight(){
		return 5;
	}
	
	function labelWidth(){
		return 20;
	}
    
    function getLayout($owner){
        // LAYOUT を取得
        $sql = "SELECT * FROM `FieldTable` WHERE `owner`='$owner' AND `direction`='CELL' ORDER BY `numbering`";
        $result=mysql_query($sql);
        
        $layout = array();
        while ($row=mysql_fetch_array($result)){
            if ($row['hitAndRun'] * 1 > 0) continue; // 非表示セルはスキップ

            $rec = array();
            $rec['tag'] = $row['tag']; // 必要
            //$rec['buttonType'] = $row['buttonType'];
            //$rec['menuType'] = $row['menuType'];
            //$rec['menuAction'] = $row['menuAction'];
            //$rec['hitAndRun'] = $row['hitAndRun']; // 
            //$rec['fieldType'] = $row['fieldType'];
            // direction は「FieldTable 検索専用キー: CELL」固定なので使わない
            //$rec['disabled'] = $row['disabled'];
            //$rec['editor'] = $row['editor'];
            $rec['id'] = $row['id'];
            //$rec['script'] = $row['script'];
            //$rec['bgcolor'] = $row['bgcolor'];
            $rec['label'] = $row['label'];
            $rec['numbering'] = $row['numbering']; // LAYOUT で使う
            //$rec['study'] = $row['study'];
            //$rec['fontSize'] = $row['fontSize'];
            //$rec['fontFamily'] = $row['fontFamily'];
            //$rec['color'] = $row['color'];
            $layout[] = $rec;
        }
        return $layout;
    }
    
    function showHeader($pdf){
        // ヘッダーを印刷
        $headerHeight = 10;
        $pdf->SetFont(KOZMIN,'B', 12); // ヘッダー用にゴシックにする

        $y = topMargin();
        $x = leftMargin();
        
        // 左寄せで、カルテID 氏名
        $patientId = $_GET['patientId'];
        $name = $_GET['patientKanjiName'];
        $title = "$patientId $name 様";
        $title = mb_convert_encoding($title, "SJIS", "UTF-8");
        $pdf->SetXY($x, $y);
        $pdf->Cell(headerWidth(), $headerHeight, $title, 0, 0, 'L');
        
        // 右寄せで ページ番号
        $pdf->SetFont(KOZMIN,'B', 8);
        $pdf->SetXY($x + labelWidth() - 20, $y + 2);
        $pageNum = 'Page '.$pdf->PageNo();
        $pdf->Cell(headerWidth(), 5, $pageNum, 0, 0,'R');
       
        // 罫線
        $pdf->SetDrawColor(0, 0, 0);
        $pdf->setLineWidth(0.5);
        $y = $pdf->GetY() + $headerHeight - 4;
        $pdf->Line($x, $y, $x + headerWidth(), $y);
        
        $pdf->Ln($headerHeight); // Line break
    }
    
    $_oldValues;
	function showCell($pdf, $label, $val){
        // $label, $val 行を生成し表示
        global $_oldValues;

        if (!$val || (strcmp($val,"") == 0) && $_oldValues){
            // $val が "" の場合は前回データをコピーして使用
            $val = $_oldValues[$label];
        }
        
        // データが空の欄は印刷せずスキップ
		if (($val != "　") && (strlen(trim($val)) > 0)){
            $x = leftMargin();
            // LABEL --------------------
            $y = $pdf->GetY();
            $pdf->Text($x, $y + lineHeight() - 2, $label);
            // VALUE ---------------------
            // 以下で $val をコンバートすると $_oldValues() の再利用で２重コンバートになってしまう
            $st = mb_convert_encoding($val, "SJIS", "UTF-8");
            $pdf->SetXY($x + labelWidth(), $y);
            $w = headerWidth() - labelWidth() - 5;
            // ### MultiCell() に newLine() を噛ませられないので、そこで改ページした際
            // ### ページ・ヘッダーがつかないことがある
            $pdf->MultiCell($w, lineHeight(), $st, 0, 'J');
            // 罫線 ----------------------
            $y = $pdf->GetY();
            $pdf->setLineWidth(0.1);
            $pdf->Line($x, $y, $x + headerWidth(), $y);
        }
        
        // $label に対応する $val を記憶しておく
        if (!$_oldValues) $_oldValues = array();
        $_oldValues[$label] = $val;
	}
    
    function newLine($pdf){
        $y = $pdf->GetY();
        if ($y > 210){
            $pdf->AddPage(); // 改ページ
            showHeader($pdf);
        }
    }
    function _newLine($y, $pdf){
        // デバッグ・ダンプ用
        if ($y > 230){
            $pdf->AddPage(); // 改ページ
            return 10;
        } else {
            // 改行する
            return $y + 5;
        }
    }
    
    function compDateTime($a, $b){
        // $a[date], $b[date] を比較
        $cmp = strcmp($a->entryDate, $b->entryDate);
        if ($cmp > 0)
            return 1;
        else if ($cmp == 0)
            return 0;
        else
            return (-1);
    }
    
    // DB を開く ==========================
	require("printLib.php");
	$db=mysql_connect("localhost","root","root") or error_func();
	$db_select=mysql_select_db("NOA");
	mysql_query("set names utf8");
	openDB();

    // 印刷の準備 ==========================
	$pdf = new MBFPDF('P', 'mm', array(180, 256)); // B5
    // $pdf = new _MBFPDF('P', 'mm', array(180, 256)); // B5
	$pdf->SetTopMargin(topMargin());
	$pdf->SetAutoPageBreak(true, 15);
	$pdf->AddMBFont(KOZMIN ,'SJIS');
	$pdf->AddMBFont(GOTHIC ,'SJIS');
	$pdf->AddMBFont(BIG5, 'SJIS');
	$pdf->SetFont(KOZMIN,'B', 8);
	$pdf->Open();
	$pdf->AddPage();
    
	$x = leftMargin();
	$y = 0; // $pdf->GetY();
    $w = 160;
	$pdf->SetXY($x, $y);
    
    // 予め保存されたデータ・ファイルを読み込む =================
	$dumpPath = $_GET['path'];
    $json = file_get_contents($dumpPath);
    $obj = json_decode($json, TRUE);
    
    // レイアウト構造を読み込む ==============================
	$owner = $_GET['owner']; // HTML で URL に添付されたパラメータ ====
    $layoutArray = getLayout($owner);
        
    // ProgressSection 以外を表示
    showHeader($pdf);
    foreach ($layoutArray as $num=>$rec){
        $id = $rec['id'];
        if ($id == "P") continue;
        
        $tag = $rec['tag'];
        $label = $rec['label'];
        $label = mb_convert_encoding($label, "SJIS", "UTF-8");
        $num = $rec['numbering'];
        $ary = explode(".", $tag);
        $table = $ary[0]; // テーブル名
        $field = $ary[1]; // フィールド名
        if ($table == "PatientTable"){
            $val = $obj['patientTable'][$field];
            showCell($pdf, $label, $val);
        } else if ($table == "NameSection"){
            $val = $obj['nameSection'][$field]['val'];
            showCell($pdf, $label, $val);
        } else if ($table == "AddressSection"){
            $val = $obj['addressSection'][$field]['val'];
            showCell($pdf, $label, $val);
        } else if ($table == "BasicSection"){
            $val = $obj['basicSection'][$field]['val'];
            showCell($pdf, $label, $val);
        } else if ($table == "MalitalSection"){
            $val = $obj['maritalSection'][$field]['val'];
            showCell($pdf, $label, $val);
        } else if ($table == "UniversalSection"){
            $val = $obj['universalSection'][$field]['val'];
            showCell($pdf, $label, $val);
        } else if ($table == "HealthInsurance"){
            $val = $obj['healthInsurance'][$field]['val'];
            showCell($pdf, $label, $val);
        } else if ($table == "PublicInsurance"){
            $val = $obj['publicInsurance'][$field]['val'];
            showCell($pdf, $label, $val);
        }

        newLine($pdf);
    }

    // ProgressSection を表示
    $history = $obj['progressSection'];
    ksort($history); // 日付が逆順だったので日付順にソート

    $y = $pdf->GetY();
    $birthDate = $obj['patientTable']['birthDate'];
    foreach ($history as $date=>$rec){
        $label = mb_convert_encoding("受診日", "SJIS", "UTF-8");
        $daytitle = showDayTitle($date);
        $age = age($birthDate, $date);
        $sai = mb_convert_encoding("才", "SJIS", "UTF-8");
        $y = $pdf->GetY() + 3;
        $pdf->SetXY($x, $y);
        $st = "$label $date $daytitle ( $age $sai )";
        $pdf->MultiCell(headerWidth(), 6, $st, 1, 'L');

        $y = $pdf->GetY() + 3;
        $pdf->SetXY($x, $y);
        newLine($pdf);
        
        foreach ($layoutArray as $num=>$rec){
            $id = $rec['id'];
            if ($id != "P") continue;
            
            $tag = $rec['tag'];
            $ary = explode(".", $tag);
            $table = $ary[0]; // テーブル名
            $field = $ary[1]; // フィールド名
            $label = $rec['label'];
            $label = mb_convert_encoding($label, "SJIS", "UTF-8");
            $val = $obj['progressSection'][$date][$field]['val'];
            showCell($pdf, $label, $val);
            newLine($pdf);
        }
    }
    // 罫線 -----------------
    $pdf->Line($x, $y, $x + $w, $y);
    
    
    // ### deubg 用 dump -----------------------------------------
    $_debug = FALSE;
    if ($_debug){
        $y += 5;
        foreach ($obj as $tabname=>$rec){
            $pdf->Text($x, $y, $tabname); // テーブル名
            $y = _newLine($y, $pdf);
            
            foreach ($rec as $label=>$val){
                $type = gettype($val);
                if ($type == "array"){
                    $pdf->Text($x + 5, $y, "$label"); // フィールド名 or entryDate
                    $y = _newLine($y, $pdf);
                    foreach ($val as $label2=>$val2){
                        $type2 = gettype($val2);
                        if ($type2 == "array"){
                            $pdf->Text($x + 10, $y, "$label2"); // 属性名 or フィールド名
                            $y = _newLine($y, $pdf);
                            foreach ($val2 as $label3=>$val3){
                                $type3 = gettype($val3);
                                if ($type3 == "array"){
                                    $pdf->Text($x + 15, $y, "$label3"); // 属性名
                                    $y = _newLine($y, $pdf);
                                    $val3 = "array $val3";
                                }
                                $val3 = mb_convert_encoding($val3, "SJIS", "UTF-8");
                                $pdf->Text($x + 15, $y, "$label3 ($val3)"); 
                                $y = _newLine($y, $pdf);
                            }
                        } else {
                            $val2 = mb_convert_encoding($val2, "SJIS", "UTF-8");
                            $pdf->Text($x + 10, $y, "$label2 ($val2)"); 
                            $y = _newLine($y, $pdf);
                        }
                    }
                } else {
                    $val = mb_convert_encoding($val, "SJIS", "UTF-8");
                    $pdf->Text($x + 5, $y, "$label ($val)"); 
                    $y = _newLine($y, $pdf);
                }
            }
        }
    }
    
	$pdf->Output();
    
    
    ?>