<?php

use app\libraries\CommonHelper;
use app\libraries\DateHelper;

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

class Invoicing_read extends MY_BackendController
{

	public function __construct()
	{
		parent::__construct();

		$this->load->model('Event_model');
		$this->load->model('Event_timeslot_model');
		$this->load->model('Event_enrollment_item_model');
		$this->load->model('Room_model');
		$this->load->model('Teacher_model');
		$this->load->model('Course_model');
		$this->load->model('Student_model');
		$this->load->model('Course_category_model');
		$this->load->model('Course_subcategory_model');
		$this->load->model('Invoice_model');
		$this->load->model('Invoice_item_model');
		$this->load->model('Receipt_model');
		$this->load->model('Invoicing_model');
	}

	public function index($invoiceId)
	{
//        log_message('debug','invoiceid:'.$invoiceId);//102
		if ($this->input->method() == 'post') {
			$params = $this->input->post();
			$this->Event_enrollment_item_model->update_in_event_attendance($params);
		}

		$invoice = $this->Invoicing_model->detailforread($invoiceId);
		$isinvoiceinmerge = CommonHelper::checkIfIsInvoiceInMerge($invoice);
		$invoiceItems = [];

		$teacher = $this->Teacher_model->detail($invoice['pic_1']);
		$room = $this->Room_model->detail($invoice['room_id']);

		$credit = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
		$creditamt = !empty($credit)?$credit['credit_amount']:0;
//		log_message('debug','creditamt:'.$creditamt);

		$items = $this->Invoice_item_model->listing_in_invoice($invoiceId);

		foreach ($items as $item) {
			if ($item['event_id'] && $item['event_enrollment_id']) {
				$timeslot = explode('||', trim($item['item_timeslot']));
				$slotheight = substr_count(trim($item['item_timeslot']), '||') * 1.1;
				array_push($invoiceItems, [
					'invoice_id' => $item['invoice_id'],
					'id' => $item['id'],
					'chi_name' => $item['chi_name'],
					'item_name' => trim($item['item_name']),
					'item_timeslot' => $timeslot,
					'slotheight' => $slotheight,
					'amount' => CommonHelper::money(trim($item['amount'])),
					'creditstxt' => CommonHelper::money($creditamt),
					'credits' => $creditamt,
					'extra' => $item['extra'],
					'user_id' => $item['user_id']
				]);
			}
		}

		$receiptItems = $this->Receipt_item_model->listing_in_invoicing_read($invoiceId);

		$teachername = '';
		if (!empty($teacher)) {
			$teachername = empty($teacher['chi_name']) ? sprintf('%s %s', $teacher['eng_firstname'], $teacher['eng_lastname']) : $teacher['chi_name'];
		}
		$allreceiptitemdetail = $this->Receipt_item_model->getAllReceiptItemDetail($invoice);//繳款明細
//		print_r($allreceiptitemdetail);

		$banklist = json_decode(file_get_contents(FCPATH . 'uploads/bank.json'), true);
		$bank = [];
		foreach ($banklist as $b) {
			$bank[] = $b['Bank_Code'] . ' ' . $b['Bank_Name_EN'] . ' ' . $b['Bank_Name_ZH'];
		}
		$canshowvoidbtn = empty($credit['use_credits']) && in_array($invoice['payment_status'], [PaymentStatus::partialpaid, PaymentStatus::paid]);
//		log_message('debug','canshowvoidbtn?'.$canshowvoidbtn);
		$canshowpaybtn = $invoice['payment_status'] !== PaymentStatus::paid;
		$this->view('backend/invoicing/read', [
			'issued_date' => $invoice['issued_date'],
			'student_chi_name' => empty($student) ? '' : $student['chi_name'],
			'receipt_items' => $receiptItems,
			'items' => $invoiceItems,
			'amount_paid' => CommonHelper::money($this->Invoicing_model->getCurrentAmountPaid($invoiceId)),
			'net_amount_payable' => $invoice['net_amount_payable'],
			'invoice_status' => $invoice['invoice_status'],
			'payment_status' => $invoice['payment_status'],
			'teacher_name' => $teachername,
			'room_name' => empty($room) ? '' : $room['name'],
			'id' => $invoiceId,
			'canshowvoidbtn' => $canshowvoidbtn,
			'canshowpaybtn'=>$canshowpaybtn,
			'merged' => $invoice['user_id'] == 0,
			'isinvoicemerge' => $isinvoiceinmerge,
			'allreceiptitemdetail' => $allreceiptitemdetail,//繳款明細
			'openaftercancelmerged' => $invoice['invoice_status'] === InvoiceStatus::openaftercancelmerged,
			'bankinfo' => json_encode($bank, JSON_UNESCAPED_UNICODE)
		]);
	}

}
