<?php

use app\libraries\CommonHelper;
use app\libraries\DefinedException;
use app\libraries\TenantHelper;

defined('BASEPATH') or exit('No direct script access allowed');

/**
 * @property MY_Pdf $pdf
 */
class Invoicing_receipt extends MY_BackendController
{
    private $pdf;
    public static $timeslot = false;
    private $ritems = [];
    private $mergedritems = [];
    private $isinvoiceinmerge;
    private $totalitempayment;
    private $inmergeInvoiceId;
    private $receiptId;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Invoicing_model');
        $this->load->model('Invoice_model');
        $this->load->model('Invoice_item_model');
        $this->load->model('Receipt_model');
        $this->load->model('Receipt_item_model');
        $this->load->model('Student_model');
        $this->load->model('Student_credit_model');
        $this->load->model('Setting_center_model');
        $this->load->model('Payment_type_model');
        $this->load->model('Tenant_model');
        $this->load->model('Receipt_management_model');

        $this->init();
    }

    protected function init()
    {
        ini_set('memory_limit', "-1");

        $pdf = new MY_Pdf(MY_Pdf::PDF_PAGE_ORIENTATION, MY_Pdf::PDF_UNIT, MY_Pdf::PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->AddTTFFont('IBming');
        // set document information
        $pdf->SetCreator(MY_Pdf::PDF_CREATOR);
        $pdf->SetAuthor(MY_Pdf::PDF_AUTHOR);
        $pdf->SetTitle('Notice');
        $pdf->SetSubject('Notice');
        $pdf->SetKeywords('Notice');
        $pdf->setPrintHeader();
        $pdf->setPrintFooter();
        $pdf->SetAutoPageBreak(TRUE, MY_Pdf::PDF_MARGIN_BOTTOM);  //設定自動分頁
        //        $pdf->SetAutoPageBreak(TRUE, 40);  //設定自動分頁
        // $pdf->setLanguageArray($l); //設定語言相關字串
        $pdf->setFontSubsetting(true); //產生字型子集（有用到的字才放到文件中）

        $this->pdf = clone $pdf;
        unset($pdf);
    }

	public function printreceipt_old()
    {
        $this->receiptId = $this->input->get('receiptId');
        $_output = $this->input->get('output');
        $tenantNo = $this->input->get('tenant_no');

        if ($tenantNo && $_output) {
            TenantHelper::setTenant($tenantNo);
        }

        $invoiceId = $this->Receipt_model->getInvoiceIdById($this->receiptId);
        $invoice = $this->Invoicing_model->detail($invoiceId);
        $receipt = $this->Receipt_model->detail_last_print($this->receiptId, $invoice['user_id']);
        if (!$receipt) {
            throw new DefinedException('先付款，後收據。');
        }
        $setting = $this->Setting_center_model->detail();
        $uploadpath = UPLOADSPATH . DS . 'tenants' . DS . $tenantNo . DS . 'receipt';
        $filename = $receipt['issued_name'] . '.html';
        $filepath = $uploadpath . DS . $filename;
        $mergedcode = $invoice['mergedcode'];
        $this->isinvoiceinmerge = CommonHelper::checkIfIsInvoiceInMerge($invoice);
        //		log_message('debug','isinvoiceinmerge:'.$this->isinvoiceinmerge);
        if ($this->isinvoiceinmerge) {
            $this->inmergeInvoiceId = $invoice['id'];
            //find original invoices:
            $invoices = $this->Invoicing_model->getallmerged($mergedcode);
            $ids = [];
            foreach ($invoices as $i) {
                $ids[] = $i['id'];
            }
            //			log_message('debug','ids:'.implode(',',$ids));
            $receipts = $this->Receipt_model->getByInvoiceIds($ids);
            if (!empty($receipts)) {
                //			log_message('debug','receipts count:'.count($receipts));//4
                $ritems = $this->Receipt_item_model->getByReceipts($receipts);
                //			log_message('debug','ritems count:'.count($ritems));//4
                $this->mergedritems = $this->Receipt_item_model->getMergedItems($receipts);
                //			log_message('debug','count#1:'.count($this->ritems));//2
                if (!empty($this->mergedritems)) {
                    foreach ($this->mergedritems as $k => $v) {
                        foreach ($ritems as $r) {
                            if ($v['user_id'] == $r['user_id']) {
                                if ($r['payment_type_id'] == PaymentType::Cash) {
                                    $this->mergedritems[$k] = array_merge(['payment_date' => $r['payment_date']], $this->mergedritems[$k]);
                                }
                                if ($r['payment_type_id'] == PaymentType::Cheque) {
                                    $this->mergedritems[$k] = array_merge(['payment_date' => $r['payment_date'], 'cheque_no' => $r['cheque_no'], 'cheque_bank_name' => $this->Receipt_item_model->getBankNameByCode($r['cheque_bank_name'])], $this->mergedritems[$k]);
                                }
                                if ($r['payment_type_id'] == PaymentType::ATM) {
                                    $this->mergedritems[$k] = array_merge(['payment_date' => $r['payment_date']], $this->mergedritems[$k]);
                                }
                            }
                        }
                    }
                }
            }

            $this->ritems = $this->Receipt_item_model->getItemsByReceiptId($receipt['id']);
            //			log_message('debug','here');
            foreach ($invoices as $invoice) {
                $this->_genreceiptM($invoice, $setting, $filepath, $receipt['issued_name'], $receipt['remark']);
                //                log_message('debug','here');
            }
        } else {
            $this->ritems = $this->Receipt_item_model->getItemsByReceiptId($receipt['id']);
            //			log_message('debug','ritems count:'.count($this->ritems));
            $this->_genreceipt($receipt, $setting, $filepath);
        }
        // PRESET PATH
        $filepath = str_replace('.html', '.pdf', $filepath);
        try {
            $this->pdf->Output($filepath, $_output ?: 'I');
            $this->db->trans_complete();
            if ($this->db->trans_status() === FALSE) {
                return $this->load->view('errors/html/error_newtab.php', [
                    'message' => '系統發生錯誤，請聯絡技術支援。'
                ]);
            }
            exit();
        } catch (DefinedException $ex) {
            $this->db->trans_rollback();
            return $this->load->view('errors/html/error_newtab', [
                // 408 - The request has been timed out.
                'message' => '系統發生錯誤，請聯絡技術支援。'
            ]);
        } catch (Exception $ex) {
            $this->db->trans_rollback();
            log_message('error', $ex->getMessage());
            return $this->load->view('errors/html/error_newtab', [
                // 408 - The request has been timed out.
                'message' => '系統發生錯誤，請聯絡技術支援。'
            ]);
        }
    }

	public function printreceipt()
	{
		$this->receiptId = $this->input->get('receiptId');
		$_output = $this->input->get('output');
		$tenantNo = $this->input->get('tenant_no');

		if ($tenantNo && $_output) {
			TenantHelper::setTenant($tenantNo);
		}

		$receipt_output = $this->Receipt_model->output_detail($this->receiptId);

		$uploadpath = UPLOADSPATH . DS . 'tenants' . DS . $tenantNo . DS . 'receipt';
		$filename = $receipt_output['issued_name'] . '.html';
		$filepath = $uploadpath . DS . $filename;

		$receipt_output['tenant_no'] = $tenantNo;
		$receipt_output['pathname'] = $filepath;

		$this->_genReceipt($receipt_output);

		// PRESET PATH
		$filepath = str_replace('.html', '.pdf', $receipt_output['pathname']);
		try {
			$this->pdf->Output($filepath, $_output ?: 'I');
			$this->db->trans_complete();
			if ($this->db->trans_status() === FALSE) {
				return $this->load->view('errors/html/error_newtab.php', [
					'message' => '系統發生錯誤，請聯絡技術支援。'
				]);
			}
			exit();
		} catch (DefinedException $ex) {
			$this->db->trans_rollback();
			return $this->load->view('errors/html/error_newtab', [
				// 408 - The request has been timed out.
				'message' => '系統發生錯誤，請聯絡技術支援。'
			]);
		} catch (Exception $ex) {
			$this->db->trans_rollback();
			log_message('error', $ex->getMessage());
			return $this->load->view('errors/html/error_newtab', [
				// 408 - The request has been timed out.
				'message' => '系統發生錯誤，請聯絡技術支援。'
			]);
		}
	}

	private function _genReceipt($receipt_output)
	{
		$this->db->trans_strict(TRUE);
		$this->db->trans_start();

//		$receipt = array_merge($receipt, $this->Receipt_model->printed($receipt));
		$receiptItemHtml = [];
		$paymentHtml = [];

//		$invoiceId = $this->Receipt_model->getInvoiceIdById($receipt['id']);
//		$invoice = $this->Invoicing_model->detail($invoiceId);
//
//		$invoiceItems = $this->Invoice_item_model->listing_in_print($invoice['id']);

//		foreach ($invoiceItems as $item) {
//			$timeslot = preg_replace('/(\d{4}\-)([^\(]*)(\()([^\)]*)(\))([^\|\|]*)/', '$2$6', $item['item_timeslot']);
//			array_push($receiptItemHtml, $this->receiptItemHtml($item, $timeslot));
//		}
//
//		if (!empty($this->ritems)) {
//			foreach ($this->ritems as $ritem) {
//				$this->totalitempayment += floatval($ritem['amount_paid']);
//			}
//			array_push($paymentHtml, $this->receiptPaymentItemHtml($this->ritems, 0, [], $invoice['amount_paid']));
//		}

		$receipt_header = $this->receiptHeader($receipt_output);
		$receipt_body = $this->receiptHtml($receipt_output);
//		$receipt_body = '';

		$receiptHtmlFile = fopen($receipt_output['pathname'], 'w') or die('Unable to generate receipt file!');
		fwrite($receiptHtmlFile, $receipt_body);
		fclose($receiptHtmlFile);
		if (!isset($this->pdf)) {
			$this->init();
		}
		$this->pdf->setHtmlHeader($receipt_header);
		//            $this->pdf->SetHeaderMargin(40);//useless
		$this->pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
		$this->pdf->AddPage('P', 'A5');
		$this->pdf->writeHTML($receipt_body, true, 0, true, 0);
		$this->pdf->setHtmlHeader($receipt_header);
		$this->pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
		//            $this->pdf->SetHeaderMargin(40);//useless
		$this->pdf->AddPage('P', 'A5');
		$this->pdf->writeHTML($receipt_body, true, 0, true, 0);
	}

	protected function receiptHeader($receipt_output)
	{
		return '<!-- HEADER  -->
<!-- COMPANY PROFILE --><table style="font-size:5px;">
<tr>    <td style="padding:0;width:34%;" align="left"><img height="25" src="' . base_url() . 'static/images/logo.png"></td>
    <td style="padding:0;width:66%;" align="right">
      <table style="font-size:6px;">
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">收據號碼Receipt No:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . $receipt_output['issued_name'] . '</span></td>
        </tr>    
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">發票號碼Invoice No:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . $receipt_output['invoice_number'] . '</span></td>
        </tr>    
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">日期Date:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . $receipt_output['issued_date'] . '</span></td>
        </tr>
      </table>
    </td>
  </tr>  
</table>';
	}

	protected function receiptItemHtml($receipt_output)
	{
//		$extra = $this->Invoicing_model->getExtra($item['id']);
//		$timeslots = [];
//		foreach (json_decode($receipt_output['event_timeslots'], true) as $timeslot) {
//			$ts = $timeslot['starttime'] . '-' . $timeslot['endtime'];
//			if (! array_key_exists($ts, $timeslots)) {
//				$timeslots[$ts] = [];
//			}
//			$timeslots[$ts][] = date('m-d(D)', strtotime($timeslot['course_date']));
//		}
//		$ts_output = [];
//		foreach ($timeslots as $key => $ts) {
//			$ts_output[] = $key . ' (' . implode(',', $ts) . ')';
//		}
		$timeslots = '';
		foreach (json_decode($receipt_output['event_timeslots'], true) as $idx => $timeslot) {
			$timeslots .= date('m-d', strtotime($timeslot['course_date'])) . ' ' . $timeslot['starttime'] . '-' . $timeslot['endtime'] . ', ';
			if ($idx % 2 != 0) {
				$timeslots .= '<br />';
			}
		}
		return $this->load->view('backend/invoicing/partials/receipt_A5_item', [
			'RECIPIENT_NAME' => sprintf('%s %s', $receipt_output['student_chi_name'], $receipt_output['student_phone']),
			'ITEM' => $receipt_output['event_display_name'],
			'PRICE' => $receipt_output['invoice_amount'] ? CommonHelper::currency($receipt_output['invoice_amount']) : '',
			'QTY' => $receipt_output['quantity'] ? $receipt_output['quantity'] : '',
			'DISCOUNT' => $receipt_output['discount_amount'] > 0 ? CommonHelper::currency($receipt_output['discount_amount']) : '-',
			'AMOUNT' => CommonHelper::currency($receipt_output['invoice_amount']),
			'THEME_ITEM_COLOR_BORDER_BOTTOM' => '#f8b87a',
			'ITEM_TIMESLOT' => $timeslots,
//			'HEIGHT_WITH_COURSE_COUNT' => 150 + $item['course_count'],
			'HEIGHT_WITH_COURSE_COUNT' => 151,
			'EXTRA' => json_decode($receipt_output['extra_fee_items'], true),
		], true);
	}

	protected function receiptPaymentItemHtml($receipt_output)
	{
//		if ($userId > 0) {
//			$amountpaid = floatval($this->Receipt_item_model->getAmountPaidByIds($this->inmergeInvoiceId, $this->receiptId, $userId));
//			//			log_message('debug','userid:'.$userId.';invoiceamountpaid:'.$invoiceamountpaid.';amountpaid:'.$amountpaid);
//			$historicpayment = $invoiceamountpaid - $amountpaid;
//			//			log_message('debug','historicpayment:'.$historicpayment);
//		} else {
//			$historicpayment = $invoiceamountpaid - $this->totalitempayment;
//		}
		$ritems = [
			[
			'payment_date' => $receipt_output['payment_date'],
			'amount_paid' => $receipt_output['cash_amount'] + $receipt_output['atm_amount'] + $receipt_output['cheque_amount'],
			'payment_type_id' => $receipt_output['payment_type_id'],
			'cheque_bank_name' => $receipt_output['cheque_bank_name'],
			'cheque_no' => $receipt_output['cheque_no'],
			'cash_amount' => $receipt_output['cash_amount'],
			'atm_amount' => $receipt_output['atm_amount'],
			'cheque_amount' => $receipt_output['cheque_amount'],
			]
		];

		return $this->load->view('backend/invoicing/partials/receipt_payment_item', [
			'items' =>
				$ritems,
			'PAYMENT_TYPE_NAME' => '現金',
			'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
			'THEME_COLOR' => 'rgb(245, 142, 39)',
			'THEME_COLOR_2' => 'rgb(245, 142, 39)',
			'THEME_THEAD_BGCOLOR' => '#fdebd7',
			'isinvoiceinmerge' => false,
//			'userId' => $userId,
			'mergeditems' => [],
//			'HISTORIC_PAYMENT' => $historicpayment,
		], true);
	}

	protected function receiptHtml($receipt_output)
	{
		$totalAmount = $receipt_output['invoice_amount'] - $receipt_output['discount_amount'] + $receipt_output['total_extra_fee'];
		$paymentReceived = $receipt_output['amount_paid_before'];
		$invoiceBalance = $totalAmount - $receipt_output['amount_paid_before'];
		switch ($receipt_output['payment_type_id']) {
			case PaymentType::Cash:
				$remainBalance = $invoiceBalance - $receipt_output['cash_amount'];
				break;
			case PaymentType::Cheque:
				$remainBalance = $invoiceBalance - $receipt_output['cheque_amount'];
				break;
			case PaymentType::ATM:
				$remainBalance = $invoiceBalance - $receipt_output['atm_amount'];
				break;
		}
		return $this->load->view('backend/invoicing/partials/receipt_A5', [
			'TOC' => $receipt_output['toc'],
			'REMARK' => $receipt_output['remark'] ?? '',
			'RECEIPT_NO' => $receipt_output['issued_name'],
			'RECEIPT_DATE' => $receipt_output['issued_date'],
			'TPL_CENTER_NAME' => $receipt_output['tpl_center_name'],
			'TPL_CENTER_TEL' => $receipt_output['tpl_center_tel'],
			'TPL_CENTER_ADDRESS' => $receipt_output['tpl_center_address'],
//			'TOTAL_AMOUNT_DUE' => number_format($totalAmount, 2, '.', ','),
			'TOTAL_AMOUNT' => CommonHelper::currency($totalAmount),
			'PAID_AMOUNT' => CommonHelper::currency($paymentReceived),
			'INVOICE_BALANCE' => CommonHelper::currency($invoiceBalance),
			'NET_AMOUNT_PAYABLE' => CommonHelper::currency($remainBalance),
			'_RECEIPT_ITEM_HTML' => $this->receiptItemHtml($receipt_output),
			'_RECEIPT_PAYMENT_ITEM_HTML' => $this->receiptPaymentItemHtml($receipt_output),
			'THEME_COLOR' => 'rgb(245, 142, 39)',
			'THEME_COLOR_2' => 'rgb(245, 142, 39)',
			'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
			'THEME_THEAD_BGCOLOR' => '#fdebd7',
			'ADD_CREDIT' => $receipt_output['credit_added'],
			'USE_CREDIT' => $receipt_output['credit_used'],
//			'CENTER_NAME' => $this->Tenant_model->detail_no(TenantHelper::getTenant())['name'],
			'PIC_NAME' => null
		], true);
	}

	private function _genreceiptM($invoice, $setting, $filepath, $issuedname, $remark = '')
    {
        $this->db->trans_strict(TRUE);
        $this->db->trans_start();

        $receiptItemHtml = [];
        $paymentHtml = [];
        $invoiceItems = $this->Invoice_item_model->listing_in_print($invoice['id']);
        //		log_message('debug','here');
        foreach ($invoiceItems as $item) {
            $timeslot = preg_replace('/(\d{4}\-)([^\(]*)(\()([^\)]*)(\))([^\|\|]*)/', '$2$6', $item['item_timeslot']);
            array_push($receiptItemHtml, $this->receiptItemHtml($item, $timeslot));
        }
        //		log_message('debug','here');
        if (!empty($this->ritems)) {
            foreach ($this->ritems as $ritem) {
                $this->totalitempayment += floatval($ritem['amount_paid']);
            }
            array_push($paymentHtml, $this->receiptPaymentItemHtml($this->ritems, $invoice['user_id'], $this->mergedritems, $invoice['amountpaid']));
        }
        //		log_message('debug','here');
        $receiptHtmlFile = fopen($filepath, 'w') or die('Unable to generate receipt file!');
        $text = $this->receiptHtmlM($invoice, $receiptItemHtml, $paymentHtml, $setting, $issuedname, $remark);
        //		log_message('debug','here');
        fwrite($receiptHtmlFile, $text);
        fclose($receiptHtmlFile);
        if (!isset($this->pdf)) {
            $this->init();
        }
        $htmlheader = '<!-- HEADER  -->
<!-- COMPANY PROFILE --><table style="font-size:5px;">
<tr>    <td style="padding:0;width:34%;" align="left"><img height="25" src="' . base_url() . 'static/images/logo.png"></td>
    <td style="padding:0;width:66%;" align="right">
      <table style="font-size:6px;">
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">收據號碼Receipt No:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . $issuedname . '</span></td>
        </tr>    
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">日期Date:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . date($setting['tpl_date_format'], time()) . '</span></td>
        </tr>
      </table>
    </td>
  </tr>  
  <tr><td align="left" style="padding:0;"><span style="color: rgb(245, 142, 39);">' . $setting['tpl_center_name'] . '</span></td></tr>
        <tr><td align="left" style="padding:0;"><span>' . $setting['tpl_center_tel'] . '</span></td></tr>
        <tr><td align="left" style="padding:0;"><span>' . $setting['tpl_center_address'] . '</span></td></tr>
</table>';
        $this->pdf->setHtmlHeader($htmlheader);
        //            $this->pdf->SetHeaderMargin(40);//useless
        $this->pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
        $this->pdf->AddPage('P', 'A5');
        $this->pdf->writeHTML($text, true, 0, true, 0);
        $this->pdf->setHtmlHeader($htmlheader);
        $this->pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
        //            $this->pdf->SetHeaderMargin(40);//useless
        $this->pdf->AddPage('P', 'A5');
        $this->pdf->writeHTML($text, true, 0, true, 0);
    }

    private function _genreceipt_old($receipt, $setting, $filepath)
    {
        $this->db->trans_strict(TRUE);
        $this->db->trans_start();

        $receipt = array_merge($receipt, $this->Receipt_model->printed($receipt));
        $receiptItemHtml = [];
        $paymentHtml = [];

        $invoiceId = $this->Receipt_model->getInvoiceIdById($receipt['id']);
        $invoice = $this->Invoicing_model->detail($invoiceId);

        $invoiceItems = $this->Invoice_item_model->listing_in_print($invoice['id']);
        foreach ($invoiceItems as $item) {
            $timeslot = preg_replace('/(\d{4}\-)([^\(]*)(\()([^\)]*)(\))([^\|\|]*)/', '$2$6', $item['item_timeslot']);
            array_push($receiptItemHtml, $this->receiptItemHtml($item, $timeslot));
        }

        if (!empty($this->ritems)) {
            foreach ($this->ritems as $ritem) {
                $this->totalitempayment += floatval($ritem['amount_paid']);
            }
            array_push($paymentHtml, $this->receiptPaymentItemHtml($this->ritems, 0, [], $invoice['amount_paid']));
        }

        $receiptHtmlFile = fopen($filepath, 'w') or die('Unable to generate receipt file!');
        $text = $this->receiptHtml($invoice, $receipt, $receiptItemHtml, $paymentHtml, $setting);
        fwrite($receiptHtmlFile, $text);
        fclose($receiptHtmlFile);
        if (!isset($this->pdf)) {
            $this->init();
        }
        $htmlheader = '<!-- HEADER  -->
<!-- COMPANY PROFILE --><table style="font-size:5px;">
<tr>    <td style="padding:0;width:34%;" align="left"><img height="25" src="' . base_url() . 'static/images/logo.png"></td>
    <td style="padding:0;width:66%;" align="right">
      <table style="font-size:6px;">
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">收據號碼Receipt No:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . $receipt['issued_name'] . '</span></td>
        </tr>    
        <tr>
          <td style="width: 37%;padding:0;" align="left"><span style="color: rgb(245, 142, 39);">日期Date:</span></td>
          <td style="width: 63%;padding:0;" align="right"><span>' . date($setting['tpl_date_format'], time()) . '</span></td>
        </tr>
      </table>
    </td>
  </tr>  
  <tr><td align="left" style="padding:0;"><span style="color: rgb(245, 142, 39);">' . $setting['tpl_center_name'] . '</span></td></tr>
        <tr><td align="left" style="padding:0;"><span>' . $setting['tpl_center_tel'] . '</span></td></tr>
        <tr><td align="left" style="padding:0;"><span>' . $setting['tpl_center_address'] . '</span></td></tr>
</table>';
        $this->pdf->setHtmlHeader($htmlheader);
        //            $this->pdf->SetHeaderMargin(40);//useless
        $this->pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
        $this->pdf->AddPage('P', 'A5');
        $this->pdf->writeHTML($text, true, 0, true, 0);
        $this->pdf->setHtmlHeader($htmlheader);
        $this->pdf->SetMargins(PDF_MARGIN_LEFT, 25, PDF_MARGIN_RIGHT);
        //            $this->pdf->SetHeaderMargin(40);//useless
        $this->pdf->AddPage('P', 'A5');
        $this->pdf->writeHTML($text, true, 0, true, 0);
    }

    protected function receiptPaymentItemHtml_old($ritems, $userId = 0, $mergeditems = [], $invoiceamountpaid = 0)
    {
        if ($userId > 0) {
            $amountpaid = floatval($this->Receipt_item_model->getAmountPaidByIds($this->inmergeInvoiceId, $this->receiptId, $userId));
            //			log_message('debug','userid:'.$userId.';invoiceamountpaid:'.$invoiceamountpaid.';amountpaid:'.$amountpaid);
            $historicpayment = $invoiceamountpaid - $amountpaid;
            //			log_message('debug','historicpayment:'.$historicpayment);
        } else {
            $historicpayment = $invoiceamountpaid - $this->totalitempayment;
        }
        return $this->load->view('backend/invoicing/partials/receipt_payment_item', [
            'items' =>
            $ritems,
            'PAYMENT_TYPE_NAME' => '現金',
            'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
            'THEME_COLOR' => 'rgb(245, 142, 39)',
            'THEME_COLOR_2' => 'rgb(245, 142, 39)',
            'THEME_THEAD_BGCOLOR' => '#fdebd7',
            'isinvoiceinmerge' => $this->isinvoiceinmerge,
            'userId' => $userId,
            'mergeditems' => $mergeditems,
            'HISTORIC_PAYMENT' => $historicpayment,
        ], true);
    }

    protected function receiptItemHtml_old($item, $timeslot)
    {
        $extra = $this->Invoicing_model->getExtra($item['id']);
        return $this->load->view('backend/invoicing/partials/receipt_A5_item', [
            'RECIPIENT_NAME' => sprintf('%s %s', $item['chi_name'], $item['content1_phone']),
            'ITEM' => $item['item_name'],
            'PRICE' => $item['unit_price'] ? CommonHelper::money((int)$item['unit_price']) : '',
            'QTY' => $item['qty'] ? (int)$item['qty'] : '',
            'DISCOUNT' => $item['discount'] > 0 ? CommonHelper::money((int)$item['discount']) : '-',
            'AMOUNT' => CommonHelper::money((int)$item['amount']),
            'THEME_ITEM_COLOR_BORDER_BOTTOM' => '#f8b87a',
            'ITEM_TIMESLOT' => explode('||', $timeslot),
            'HEIGHT_WITH_COURSE_COUNT' => 150 + $item['course_count'],
            'EXTRA' => $extra
        ], true);
    }

    protected function receiptHtmlM($invoice, $receiptItemHtml, $paymentHtml, $setting, $issuedname, $remark = '')
    {
        $studentCredit = $this->Student_credit_model->getAddUseCreditsForPrint($invoice['user_id'], $invoice['id']);
        $addcredit = 0;
        $usecredit = 0;
        if (!empty($studentCredit)) {
            $usecredit = CommonHelper::money($studentCredit['use_credits']);
            $addcredit = CommonHelper::money($studentCredit['add_credits']);
        }

        $toc = $this->Receipt_management_model->one()['toc'] ?? '';
        //        log_message('debug','redeiptid:'.$this->receiptId);
        $netamountpayable = floatval($invoice['amounttopay']) - floatval($invoice['amount_paid']);
        if ($netamountpayable < 0) {
            $netamountpayable = 0;
        }
        return $this->load->view('backend/invoicing/partials/receipt_A5', [
            'TOC' => $toc,
            'REMARK' => $remark,
            'RECEIPT_NO' => $issuedname,
            'RECEIPT_DATE' => date($setting['tpl_date_format'], time()),
            'TPL_CENTER_NAME' => $setting['tpl_center_name'],
            'TPL_CENTER_TEL' => $setting['tpl_center_tel'],
            'TPL_CENTER_ADDRESS' => $setting['tpl_center_address'],
            'TOTAL_AMOUNT_DUE' => $invoice['amount_to_pay'],
            'NET_AMOUNT_PAYABLE' => CommonHelper::money($netamountpayable),
            '_RECEIPT_ITEM_HTML' => implode('', $receiptItemHtml),
            '_RECEIPT_PAYMENT_ITEM_HTML' => implode('', $paymentHtml),
            'THEME_COLOR' => 'rgb(245, 142, 39)',
            'THEME_COLOR_2' => 'rgb(245, 142, 39)',
            'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
            'THEME_THEAD_BGCOLOR' => '#fdebd7',
            'ADD_CREDIT' => $addcredit,
            'USE_CREDIT' => $usecredit,
            'CENTER_NAME' => $this->Tenant_model->detail_no(TenantHelper::getTenant())['name'],
            'PIC_NAME' => null,
        ], true);
    }

    protected function receiptHtml_old($invoice, $receipt, $receiptItemHtml, $paymentHtml, $setting)
    {
        $studentCredit = $this->Student_credit_model->getAddUseCreditsForPrint($invoice['user_id'], $invoice['id']);
        $addcredit = 0;
        $usecredit = 0;
        if (!empty($studentCredit)) {
            $usecredit = CommonHelper::money($studentCredit['use_credits']);
            $addcredit = CommonHelper::money($studentCredit['add_credits']);
        }

        $toc = $this->Receipt_management_model->one()['toc'] ?? '';
        $netamountpayable = floatval($invoice['amount_to_pay']) - floatval($invoice['amount_paid']);
        if ($netamountpayable < 0) {
            $netamountpayable = 0;
        }
        return $this->load->view('backend/invoicing/partials/receipt_A5', [
            'TOC' => $toc,
            'REMARK' => $receipt['remark'] ?? '',
            'RECEIPT_NO' => $receipt['issued_name'],
            'RECEIPT_DATE' => date($setting['tpl_date_format'], time()),
            'TPL_CENTER_NAME' => $setting['tpl_center_name'],
            'TPL_CENTER_TEL' => $setting['tpl_center_tel'],
            'TPL_CENTER_ADDRESS' => $setting['tpl_center_address'],
            'TOTAL_AMOUNT_DUE' => CommonHelper::money($invoice['amount_to_pay']),
            'NET_AMOUNT_PAYABLE' => CommonHelper::money($netamountpayable),
            '_RECEIPT_ITEM_HTML' => implode('', $receiptItemHtml),
            '_RECEIPT_PAYMENT_ITEM_HTML' => implode('', $paymentHtml),
            'THEME_COLOR' => 'rgb(245, 142, 39)',
            'THEME_COLOR_2' => 'rgb(245, 142, 39)',
            'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
            'THEME_THEAD_BGCOLOR' => '#fdebd7',
            'ADD_CREDIT' => $addcredit,
            'USE_CREDIT' => $usecredit,
            'CENTER_NAME' => $this->Tenant_model->detail_no(TenantHelper::getTenant())['name'],
            'PIC_NAME' => null
        ], true);
    }
}
