<?php

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

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

class Invoicing_invoice extends MY_BackendController
{

    /**
     * @var Tcpdf
     */
    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(Tcpdf::PDF_PAGE_ORIENTATION, Tcpdf::PDF_UNIT, Tcpdf::PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->AddTTFFont('IBming');
        // set document information
        $pdf->SetCreator(Tcpdf::PDF_CREATOR);
        $pdf->SetAuthor(Tcpdf::PDF_AUTHOR);
        $pdf->SetTitle('Notice');
        $pdf->SetSubject('Notice');
        $pdf->SetKeywords('Notice');
        $pdf->setPrintHeader();
        $pdf->setPrintFooter();
        $pdf->SetAutoPageBreak(TRUE, Tcpdf::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 = $toc[0]['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:11px;">
<tr>    
<td style="padding:0;width:70%;" align="left" >
    <tr>
    <img height="80"  src="' . base_url() . 'assets/backend/images/logo-live-education.png">
    &nbsp;
    <img height="80"  src="' . base_url() . 'assets/backend/images/live_education_mini_banner.png">
    </tr>
</td>


    <td style="width:30%;" align="right">
    <br><br><br>
            <table style="font-size:8px;">
            <tr>
            <td style="width: 37%;padding:0;" align="left"><span style="color:black;">發票號碼:</span></td>
            <td style="width: 63%;padding:0;" align="right"><span>' . $_invoice['invoice_number'] . '</span></td>
            </tr>    
            <tr>
            <td style="width: 37%;padding:0;" align="left"><span style="color: black;">日期:</span></td>
            <td style="width: 63%;padding:0;" align="right"><span>' . date("Y-m-d",$_invoice['issued_date'] ). '</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("P","A4");
        $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' => 'black',
            '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(86, 51, 49)',
            'THEME_COLOR_2' => 'rgb(86, 51, 49)',
            'THEME_THEAD_COLOR_BORDER_BOTTOM' => '#f8b87a',
            'THEME_THEAD_BGCOLOR' => 'rgb(211,200,196)',
            //'CENTER_NAME' => $this->Tenant_model->detail_no(TenantHelper::getTenant())['name']
        ), true);
    }
}
