<?php
    
    function convert($obj, $name){
        // JSON から文字を取り出して返す
        $st = $obj[$name];
        return ($st) ? mb_convert_encoding($st, "SJIS", "UTF-8") : "";
    }
    
    function dateOf($label, $dateTime){
        // 日時文字列から年月日のみを返す
        if (!$dateTime) return $label;
        if (strlen($dateTime) == 0) return $label;
        
        $array = explode(" ", $dateTime);
        return $label.$array[0];
    }
    
    function makeRow($pdf, $x, $y, $label, $obj, $code){
        // 明細書の各行を生成
        // ラベル
        $w = 40;
        $pdf->SetXY($x, $y);
        $label = mb_convert_encoding($label, "SJIS", "UTF-8");
        $pdf->Cell($w, 5, $label, 1, 0, 'L');
        // 保険
        $x += $w;
        $pdf->SetXY($x, $y);
        $obj2 = $obj['ins'];
        $st = mb_convert_encoding($obj2[$code], "SJIS", "UTF-8");
        $pdf->Cell($w, 5, $st, 1, 0, 'R');
        // 自費
        $x += $w;
        $pdf->SetXY($x, $y);
        $obj2 = $obj['own'];
        $st = mb_convert_encoding($obj2[$code], "SJIS", "UTF-8");
        $pdf->Cell($w, 5, $st, 1, 0, 'R');
    }
    
    function makeRow2($pdf, $x, $y, $label, $ins, $own){
        // 明細書の各行を生成
        // ラベル
        $w = 40;
        $pdf->SetXY($x, $y);
        $label = mb_convert_encoding($label, "SJIS", "UTF-8");
        $pdf->Cell($w, 5, $label, 1, 0, 'L');
        // 保険
        if ($ins){
            $x += $w;
            $pdf->SetXY($x, $y);
            $ins = mb_convert_encoding($ins, "SJIS", "UTF-8");
            $pdf->Cell($w, 5, $ins, 1, 0, 'R');
        } else
            $pdf->Cell($w, 5, "", 0, 0, 'R');
        // 自費
        if ($own){
            $x += $w;
            $pdf->SetXY($x, $y);
            $own = mb_convert_encoding($own, "SJIS", "UTF-8");
            $pdf->Cell($w, 5, $own, 1, 0, 'R');
        }
    }
    
	define('FPDF_FONTPATH','/Applications/MAMP/htdocs/FPDF/fpdf153/font/');
	require_once '../FPDF/fpdf153/mbfpdf.php';
	
	// サイズの定数
	$pageWidth = 170;			// 外枠全体の幅
	$pageHeight = 110;			// 外枠全体の高さ
	$topMargin = 8;				// 画面上端からのマージン
	$leftMargin = 5;			// 画面左端から左カラムまでのマージン
    $frameLeft = 50;            // 外枠左端の位置
    $rowHeight = 7;             // 行の高さ
    
    $colWidth = $pageWidth / 4;
    $col0 = $leftMargin;
    $col1 = $leftMargin + $colWidth;
    $col2 = $leftMargin + $colWidth * 2;
    $col3 = $leftMargin + $colWidth * 3 - 3;
    
	$pdf=new MBFPDF('P', 'mm', array(180, 256)); // B5
	
	$pdf->AddMBFont(KOZMIN ,'SJIS');
	$pdf->AddMBFont(GOTHIC ,'SJIS');
	$pdf->AddMBFont(BIG5, 'SJIS');
	
    // docMaker.js から送られた JSON をオブジェクトに decode 
    // class 外で処理した $obj が認識されないのでここで処理
    $value = $_GET['value']; $value = stripslashes($value);
    $obj = json_decode($value, true);
	
	$pdf->Open();
	$pdf->AddPage();
    
    ///// HEADER /////////////////////////////////////////////////
    
    // タイトル
    $x = $col0;
    $y = $topMargin;
    $pdf->SetFont(KOZMIN,'B', 11);
	$pdf->SetXY($x, $y);
    $st = mb_convert_encoding('診療費請求書兼領収書', "SJIS", "UTF-8");
    $h = 5;
    $w = $frameLeft - $leftMargin;
	$pdf->Cell($w, $h, $st, 0, 0, 'L');
    $pdf->SetFont(KOZMIN,'B', 10);
    
    // カルテID
    $y += $rowHeight; 
    $pdf->SetXY($x, $y);
    $st = mb_convert_encoding("カルテ番号：".$obj["patientId"], "SJIS", "UTF-8");
	$pdf->Cell($w, $h, $st, 0, 0, 'L');
    
    // 氏名
    $x = $col1;
    $st = mb_convert_encoding("氏名：".$obj["patientName"]." 様", "SJIS", "UTF-8");
	$pdf->Cell($w, $h, $st, 0, 0, 'L');
    
    ///// 明細フレーム //////////////////////////////////////////////
    // 明細を表示
    $x = $col0;
    $y += $rowHeight + 2;
    makeRow2($pdf, $x, $y, NULL, "保険適用", "保険適用外（自費）"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "初・再診料等", $obj, "10"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "投薬", $obj, "20"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "注射", $obj, "30"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "処置", $obj, "40"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "手術・麻酔", $obj, "50"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "検査", $obj, "60"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "画像診断", $obj, "70"); $y += $rowHeight;
    makeRow($pdf, $x, $y, "その他", $obj, "80"); $y += $rowHeight;
    $st = $obj["insuranceClass"]." ( ".$obj["paymentRatio"]." 割 )　".$obj["point"];
    $insFee = $obj["insFee"];
    $ownFee = $obj["ownFee"];
    $tax = $obj["tax"]; //###
    $st2 = ($tax * 1 > 0) ? "小計　$ownFee" : " ";
    makeRow2($pdf, $x, $y, "合計点数", $st, $st2); $y += $rowHeight;
    if ($tax * 1 > 0){
        $st2 = "消費税　$tax";
        $ownTotal = $ownFee + $tax;
        makeRow2($pdf, $x, $y, " ", " ", $st2); $y += $rowHeight;
    } else {
        $ownTotal = $ownFee;
    }
    makeRow2($pdf, $x, $y, "負担金額", $insFee."円", $ownTotal."円"); 
	
    ///// FOOTER //////////////////////////////////////////////
    
    // 医療機関名
    $x = $col0;
    $y += $rowHeight + 1; 
    $footerY = $y; // コメント印刷の位置決めに使われる
    $pdf->SetXY($x, $y);
    $st = $obj["hospitalName"];
    $st = mb_convert_encoding($st, "SJIS", "UTF-8");
    $pdf->SetFont(KOZMIN,'B', 14);
    $pdf->Cell($pageWidth, 5, $st, 0, 0, 'L');
    
    // 医療機関住所
    $x = $col0;
    $y += $rowHeight;
    $pdf->SetXY($x, $y);
    $st = $obj["hospitalAddress"]."　電話：".$obj["hospitalPhone"];
    $st = mb_convert_encoding($st, "SJIS", "UTF-8");
    $pdf->SetFont(KOZMIN,'B', 11);
    $pdf->Cell($pageWidth, 5, $st, 0, 0, 'L');
    
    ///// 右側フレーム //////////////////////////////////////////////
    // 発行日
    $x = $col3;
    $y = $topMargin;
	$pdf->SetXY($x, $y);
    $st = dateOf("発行日：", $obj["publishedDate"]);
    $date = mb_convert_encoding($st, "SJIS", "UTF-8");
	$pdf->Cell($w, $h, $date, 0, 0, 'L');
    
    // 受診日
    $y += $rowHeight;
	$pdf->SetXY($x, $y);
    $st = dateOf("診察日：", $obj["currentDate"]);
    $date = mb_convert_encoding($st, "SJIS", "UTF-8");
	$pdf->Cell($w, $h, $date, 0, 0, 'L');
    $y += 2;
    
    $total = $ownTotal + $insFee;
    
    // 未払額があった場合
    $unpaid = $obj["unpaidFee"] * 1;
    if ($unpaid){
        // 今回請求額
        $y += $rowHeight;
        $pdf->SetXY($x, $y);
        $st = "今回請求額：".$total."円";
        $date = mb_convert_encoding($st, "SJIS", "UTF-8");
        $pdf->Cell($w, $h, $date, 0, 0, 'R');
         // 前回請求額
        $y += $rowHeight;
        $pdf->SetXY($x, $y);
        $st = "前回未払額：".$unpaid."円";
        $date = mb_convert_encoding($st, "SJIS", "UTF-8");
        $pdf->Cell($w, $h, $date, 0, 0, 'R');
        $total += $unpaid;
    }
    
    // 割引額
    $discountRatio = $obj["discountRatio"] * 1;
    if ($discountRatio){
        $y += $rowHeight;
        $pdf->SetXY($x, $y);
        $discount = floor($total * $discountRatio / 1000) * 10;
        $st = "割引：△ ".$discount."円";
        $date = mb_convert_encoding($st, "SJIS", "UTF-8");
        $pdf->Cell($w, $h, $date, 0, 0, 'R');
        $total -= $discount;
    }
    
    // 請求総額
    $y += $rowHeight;
	$pdf->SetXY($x, $y);
    $st = "合計請求額：".$total."円";
    $date = mb_convert_encoding($st, "SJIS", "UTF-8");
	$pdf->Cell($w, $h, $date, 1, 0, 'R');
    
    // コメント
    $x = $col3;
    $y = $footerY - 40;
	$pdf->SetXY($x, $y);
    $st = "領収印なきものは無効です。領収書は再発行できません。税金の医療費控除などのため大切に保管してください。";
    $st = mb_convert_encoding($st, "SJIS", "UTF-8");
    $h = 5;
    $pdf->SetFont(KOZMIN,'B', 10);
    $pdf->MultiCell($colWidth + 6, $h, $st, 0, 'L');
    
    // 領収印
    $x = $col3 + 15;
    $y = $pdf->GetY() + 3;
    $pdf->SetXY($x, $y);
    $st = mb_convert_encoding("領収印", "SJIS", "UTF-8");
    $pdf->SetFont(KOZMIN,'B', 7);
    $pdf->MultiCell(15, 15, $st, 1, 'C');
    $pdf->SetFont(KOZMIN,'B', 10);
    
    
	$pdf->Output();
    
?>