<?php

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

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

/**
 * @property MY_Pdf $pdf
 */
class Invoicing_invoice extends MY_BackendController
{
	private $pdf;
	public static $timeslot = true;
	public static $_output = 'I';

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Invoicing_model');
		$this->load->model('Invoice_model');
		$this->load->model('Invoice_item_model');
		$this->load->model('Student_model');
		$this->load->model('Setting_center_model');
		$this->load->model('Tenant_model');
		$this->load->model('Invoice_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->setLanguageArray($l); //設定語言相關字串
		$pdf->setFontSubsetting(true); //產生字型子集（有用到的字才放到文件中）

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

	public function printinvoice()
	{
		$invoiceId = $this->input->get('invoiceId');
//        log_message('debug', 'invoiceId:'.$invoiceId);
		$_output = $this->input->get('output');
		$tenantNo = $this->input->get('tenant_no');

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

		$invoice = $this->Invoicing_model->detail($invoiceId);
		$toc = $this->Invoice_management_model->one()['toc'] ?? '';
		$invoice = array_merge(['toc' => $toc], $invoice);
		$setting = $this->Setting_center_model->detail();
		$mergedcode = $invoice['mergedcode'];
		$isinvoiceinmerge = CommonHelper::checkIfIsInvoiceInMerge($invoice);
		$this->db->trans_strict(TRUE);
		$this->db->trans_start();
		$uploadpath = UPLOADSPATH . DS . 'tenants' . DS . $tenantNo . DS . 'invoice';
		$filename =empty($invoice['issued_name'])? CommonHelper::GUID().'.html' : $invoice['issued_name'] . '.html';
		$filepath = $uploadpath . DS . $filename;
		$invoice = array_merge($invoice, $this->Invoice_model->printed($invoice));
		if($isinvoiceinmerge){
			//find original invoices:
			$invoices = $this->Invoicing_model->getallmerged($mergedcode);
			foreach($invoices as $i){
				$i = array_merge(['toc' => $toc], $i);
				$this->_genInvoice($i,$setting,$filepath);
			}
		}else{
			$this->_genInvoice($invoice,$setting,$filepath);
		}
		$filepath = str_replace('.html', '.pdf', $filepath);
		$this->pdf->Output($filepath, $_output ?: self::$_output);
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE) {
			return $this->load->view('errors/html/error_newtab.php', [
				'message' => '系統發生錯誤，請聯絡技術支援。'
			]);
		}
		exit();
	}

	private function _genInvoice($_invoice,$setting,$filepath){
		$htmlheader = '<table style="font-size:8pt;"><tr><td style="width:58%;" align="left"><img height="50" src="' . base_url() . 'static/images/logo.png"></td>
    <td align="right" style="42%;"><br><br><table>
        <tr>
          <td align="left" style="width:33%;">
            <span style="color: rgb(245, 142, 39); line-height: 50%;">發票號碼 Invoice No:</span>
          </td>
          <td align="right">
              <span style="">' . $_invoice['issued_name'] . '</span>
          </td>
        </tr>
        <tr>
          <td align="left" style="width:33%;">
            <span style="color: rgb(245, 142, 39);">日期Date:</span>
          </td>
          <td align="right">
            <span style="">' . date($setting['tpl_date_format'], time()) . '</span>
          </td>
        </tr>
      </table></td></tr></table>';
		$this->pdf->setHtmlHeader($htmlheader);
		$invoiceItemHtml = [];
		$items = $this->Invoice_item_model->listing_in_print($_invoice['id']);
		foreach ($items as $item) {
			$timeslot = preg_replace('/(\d{4}\-)([^\(]*)(\()([^\)]*)(\))([^\|\|]*)/', '$2$6', $item['item_timeslot']);
			array_push($invoiceItemHtml, $this->invoiceItemHtml($item, $timeslot));
		}
		$text = $this->invoiceHtml($_invoice, $invoiceItemHtml, $setting);
		$file = fopen($filepath, 'w') or die('Permission error');
		fwrite($file, $text);
		fclose($file);
		$this->pdf->AddPage();
		$this->pdf->writeHTML($text, true, 0, true, 0);
	}

	protected function invoiceItemHtml($item, $timeslot)
    {
        $item_timeslot = '';
        $item_timeslots = explode('||', $timeslot);
        foreach ($item_timeslots as $key => $string) {
            if ($key % 2 == 0) $item_timeslot .= '<br>';
            $item_timeslot .= $string;
            if ($key + 1 != count($item_timeslots)) {
                $item_timeslot .= ',&nbsp;&nbsp;';
            }
        }

        return $this->load->view(('backend/invoicing/partials/invoice_item'), [
            'RECIPIENT_NAME' => $item['chi_name'],
            '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' => $item_timeslot,
            'HEIGHT_WITH_COURSE_COUNT' => 125 + $item['course_count'],
            'EXTRA' => $this->Invoicing_model->getExtra($item['id'])
        ], true);
    }

	private function invoiceHtml($_invoice, $invoiceItemHtml, $setting)
	{
		$amttopay=$_invoice['amount_to_pay'];
		return $this->load->view('backend/invoicing/partials/invoice', array(
			'TOC' => $_invoice['toc'],
			'INVOICE_NO' => $_invoice['issued_name'],
			'INVOICE_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' => is_numeric($amttopay)?CommonHelper::money($amttopay):$amttopay,
			'_INVOICE_ITEM_HTML' => implode('', $invoiceItemHtml),
			'THEME_COLOR' => 'rgb(245, 142, 39)',
			'THEME_COLOR_2' => 'rgb(245, 142, 39)',
			'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
			'THEME_THEAD_BGCOLOR' => '#fdebd7',
			'CENTER_NAME' => $this->Tenant_model->detail_no(TenantHelper::getTenant())['name']
		), true);
	}
}
