<?php

use app\libraries\CommonHelper;

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

class Invoicing extends MY_ApiController
{

	use \app\libraries\Json;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Invoicing_model');
		$this->load->model('Invoice_model');
		$this->load->model('Receipt_model');
		$this->load->model('Student_credit_model');
		$this->load->model('Payment_type_model');
		$this->load->model('Receipt_item_model');
	}

	public function getusers()
	{
		$mode = $this->input->get('mode');
		$id = $this->input->get('id');
		if ($mode === 'invoice') {
			list($users, $userId) = $this->Invoicing_model->getUsersForTransfer($id);
		} else { //receiptitem
			list($users, $userId) = $this->Receipt_item_model->getUsersForTransfer($id);
		}
		echo json_encode(['success' => true, 'getusers' => true, 'users' => $users, 'defaultuser' => $userId], JSON_UNESCAPED_UNICODE);
	}

	public function transfer()
	{
		$mode = $this->input->get('mode');
		$id = $this->input->get('id');
		$studentId = $this->input->get('studentId');
		if ($mode === 'invoice') {
			$invoice = $this->Invoicing_model->detail($id);
			$amtpaid = $invoice['amount_paid'] ?? 0;
			$last_transferee = $this->Student_credit_model->detail_in_last_credit($studentId);
			$receipt = $this->Receipt_model->getOneByInvoiceId($id);
			$last_transferor = $this->Student_credit_model->getByStudentIdReceiptId($invoice['user_id'], $receipt['id']);
			if (empty($last_transferee) && empty($last_transferor)) {
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $amtpaid, 'invoice_id' => $id, 'student_id' => $studentId]);
			} else if (empty($last_transferee) && !empty($last_transferor)) {
				$this->Student_credit_model->create(['student_id' => $last_transferor['student_id'], 'use_credits' => $last_transferor['credit_amount'], 'credit_amount' => 0, 'next_id' => $last_transferor['id']]);
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $amtpaid, 'invoice_id' => $id, 'student_id' => $studentId]);
			} else if (!empty($last_transferee) && empty($last_transferor)) {
				$totalcredit = floatval($last_transferee['credit_amount']) + $amtpaid;
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $totalcredit, 'invoice_id' => $id, 'student_id' => $studentId, 'next_id' => $last_transferee['id']]);
			} else if (!empty($last_transferee) && !empty($last_transferor)) {
				$this->Student_credit_model->create(['student_id' => $last_transferor['student_id'], 'invoice_id' => $id, 'use_credits' => $last_transferor['credit_amount'], 'credit_amount' => 0, 'next_id' => $last_transferor['id']]);
				$totalcredit = floatval($last_transferee['credit_amount']) + $amtpaid;
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $totalcredit, 'invoice_id' => $id, 'student_id' => $studentId, 'next_id' => $last_transferee['id']]);
			}
			$this->Invoice_model->void($id);
			//remove the student from enrollment:
			$this->load->model('Event_enrollment_model');
			$this->Event_enrollment_model->RemoveStudentByInvoiceId($id);
			$this->Receipt_model->void($id);
		} else { //receiptitem
			$ritem = $this->Receipt_item_model->detail($id);
			$amtpaid = $ritem['amount_paid'] ?? 0;
			$last_transferee = $this->Student_credit_model->detail_in_last_credit($studentId);
			$last_transferor = $this->Student_credit_model->getByStudentIdReceiptId($ritem['user_id'], $ritem['receipt_id']);
			if (empty($last_transferee) && empty($last_transferor)) {
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $amtpaid, 'receipt_item_id' => $id, 'student_id' => $studentId]);
			} else if (empty($last_transferee) && !empty($last_transferor)) {
				$this->Student_credit_model->create(['student_id' => $last_transferor['student_id'], 'use_credits' => $last_transferor['credit_amount'], 'credit_amount' => 0, 'next_id' => $last_transferor['id']]);
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $amtpaid, 'receipt_item_id' => $id, 'student_id' => $studentId]);
			} else if (!empty($last_transferee) && empty($last_transferor)) {
				$totalcredit = floatval($last_transferee['credit_amount']) + $amtpaid;
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $totalcredit, 'receipt_item_id' => $id, 'student_id' => $studentId, 'next_id' => $last_transferee['id']]);
			} else if (!empty($last_transferee) && !empty($last_transferor)) {
				$this->Student_credit_model->create(['student_id' => $last_transferor['student_id'], 'receipt_item_id' => $id, 'use_credits' => $last_transferor['credit_amount'], 'credit_amount' => 0, 'next_id' => $last_transferor['id']]);
				$totalcredit = floatval($last_transferee['credit_amount']) + $amtpaid;
				$this->Student_credit_model->create(['add_credits' => $amtpaid, 'credit_amount' => $totalcredit, 'receipt_item_id' => $id, 'student_id' => $studentId, 'next_id' => $last_transferee['id']]);
			}
			$invoice = $this->Invoicing_model->detail($this->input->get('invoiceId'));
			$newamtpaid = $invoice['amount_paid'] - $amtpaid;
			$paymentstatus = $newamtpaid == 0 ? PaymentStatus::pending : PaymentStatus::partialpaid;
//			log_message('debug','newamtpaid:'.$newamtpaid.';paymentstatus:'.$paymentstatus);
			$this->Invoicing_model->update(['amount_paid' => $newamtpaid, 'payment_status' => $paymentstatus,'invoice_status'=>InvoiceStatus::open], $invoice['id']);
			$this->Receipt_item_model->void($id);
		}
		echo json_encode(['success' => true, 'data' => []], JSON_UNESCAPED_UNICODE);
	}

	public function refund()
	{
		$this->load->model('Invoicing_refund_model');
		$mode = $this->input->get('mode');
		$id = $this->input->get('id');
		if ($mode === 'invoice') {
			$invoice = $this->Invoice_model->void($id);
			$last = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
			if (!empty($last) && !empty($last['receipt_id'])) { //amountpaid > amounttopay
				if ($id == $last['invoice_id']) {
					//remove current credit
					$this->Student_credit_model->create(['student_id' => $invoice['user_id'], 'invoice_id' => $invoice['id'], 'use_credits' => $last['credit_amount'], 'credit_amount' => 0, 'next_id' => $last['id']]);
				}
				$newId = $this->Invoicing_refund_model->add($id, $invoice['amount_paid'], $mode);
				//remove the student from enrollment:
				$this->load->model('Event_enrollment_model');
				$this->Event_enrollment_model->RemoveStudentByInvoiceId($id);
				$this->Receipt_model->void($id);
				echo json_encode(['success' => $newId > 0, 'data' => []], JSON_UNESCAPED_UNICODE);
			}
		} else { //receiptitem
			$receiptItem = $this->Receipt_item_model->void($id);
			$invoice = $this->Invoicing_model->detail($this->input->get('invoiceId'));
			$last = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
			if (!empty($last) && !empty($last['receipt_id'])) { //amountpaid > amounttopay
				if ($receiptItem['receipt_id'] == $last['receipt_id']) {
					//remove current credit
					$this->Student_credit_model->create(['student_id' => $invoice['user_id'], 'invoice_id' => $invoice['id'], 'receipt_item_id' => $id, 'use_credits' => $last['credit_amount'], 'credit_amount' => 0, 'next_id' => $last['id']]);
				}
			}
			$invoice = $this->Invoicing_model->detail($this->input->get('invoiceId'));
			$newamtpaid = $invoice['amount_paid'] - $receiptItem['amount_paid'];
			$paymentstatus = $newamtpaid == 0 ? PaymentStatus::pending : PaymentStatus::partialpaid;
			$this->Invoicing_model->update(['amount_paid' => $newamtpaid, 'payment_status' => $paymentstatus, 'invoice_status' => InvoiceStatus::open], $invoice['id']);
			$newId = $this->Invoicing_refund_model->add($id, $receiptItem['amount_paid'], $mode);
			echo json_encode(['success' => $newId > 0, 'data' => []], JSON_UNESCAPED_UNICODE);
		}
	}

	public function getreceiptsbyinvoice()
	{
		$invoiceId = $this->input->get('invoiceId');
		$data = $this->Receipt_model->getByInvoiceId($invoiceId);
		echo json_encode(['success' => true, 'getreceipts' => true, 'data' => $data], JSON_UNESCAPED_UNICODE);
	}

	public function getbystudent()
	{
		$name = $this->input->get('name');
		$studentno = $this->input->get('studentno');
		$mobile = $this->input->get('mobile');
		$ipage = $this->input->get('ipage');
		$mpage=$this->input->get('mpage');
		//return [$ipaging,$istart,$iend,$iprevlink,$inextlink, $mpaging,$mstart,$mend,$mprevlink,$mnextlink];
		if (! ($result = $this->Invoicing_model->getbystudent($name, $studentno, $mobile,$ipage,$mpage))) {
			echo json_encode(['success' => false], JSON_UNESCAPED_UNICODE);
			return;
		}
		list($ipaging, $istart, $iend, $iprevlink, $inextlink, $mpaging, $mstart, $mend, $mprevlink, $mnextlink) = $result;
		echo json_encode(['success' => true, 'getbystudent' => true, 'ipaging' => $ipaging, 'istart' => $istart,'iend'=>$iend,'iprevlink'=>$iprevlink,'inextlink'=>$inextlink,'mpaging' => $mpaging, 'mstart' => $mstart,'mend'=>$mend,'mprevlink'=>$mprevlink,'mnextlink'=>$mnextlink], JSON_UNESCAPED_UNICODE);
	}

	public function getbyselectedno()
	{
		$selectedno = $this->input->get('selectedno');
		list($student, $data) = $this->Invoicing_model->getbyselectedno($selectedno);
		echo json_encode(['success' => true, 'getbyselectedno' => true, 'student' => $student, 'data' => $data], JSON_UNESCAPED_UNICODE);
	}

	public function getInvoices()
	{
		$merged = $this->Invoicing_model->getInvoices();
		echo json_encode(['success' => true, 'getInvoices' => true, 'data' => $merged], JSON_UNESCAPED_UNICODE);
	}

	public function unmerge()
	{
		$this->Invoicing_model->unmerge($this->input->get('id'));
		echo json_encode(['success' => true, 'unmerged' => true, 'data' => []], JSON_UNESCAPED_UNICODE);
	}

	public function getunmerged()
	{
		$unmerged = $this->Invoicing_model->getunmerged($this->input->get('id'));
		$this->load->model('Receipt_model');
		echo json_encode(['success' => true, 'getunmerged' => true, 'data' => $unmerged, 'orphanreceipts' => []], JSON_UNESCAPED_UNICODE);
	}

	public function getmerged()
	{
		$merged = $this->Invoicing_model->getmerged($this->input->get('id'));
		echo json_encode(['success' => true, 'getmerged' => true, 'data' => $merged], JSON_UNESCAPED_UNICODE);
	}

	public function linkinvoice()
	{
		$ret = $this->Invoicing_model->linkinvoice($this->input->get('invoiceId'), $this->input->get('receiptId'));
		echo json_encode(['success' => true, 'linkinvoice' => true, 'data' => $ret], JSON_UNESCAPED_UNICODE);
	}

	public function getAllInvoices()
	{
		list($invoices, $merged) = $this->Invoicing_model->all();
		echo json_encode(['success' => true, 'getAllInvoices' => true, 'invoices' => $invoices, 'merged' => $merged], JSON_UNESCAPED_UNICODE);
	}

	public function getbyinvoiceno()
	{
		$invoices = $this->Invoicing_model->detailbyinvoiceno($this->input->get('invoiceno'));
		echo json_encode(['success' => true, 'getbyinvoiceno' => true, 'data' => $invoices], JSON_UNESCAPED_UNICODE);
	}

	// TODO: amend listing_invoices_studentId condition
	public function listing_invoices_receipts()
	{
		$this->is_get();

		$params = $this->input->get();
		$studentId = $params['student_id'];
		$tenantNo = $params['tenant_no'];

		$this->Invoicing_model->setTenantNo($tenantNo, true);
		$i = $this->Invoicing_model->listing_invoices_studentId($studentId);
		$r = $this->Invoicing_model->listing_receipts_studentId($studentId);

		echo $this->respond(['invoices' => $i, 'receipts' => $r]);
	}

	public function merge()
	{
		$this->is_post();
		$this->is_json();

		$invoiceIds = $this->json['invoice_ids'];
		$tenantNo = $this->json['tenant_no'];

		$this->Invoicing_model->setTenantNo($tenantNo, true);
		$this->session->set_userdata(['tenant_no' => $tenantNo]);
		$mergedId = $this->Invoicing_model->merge($invoiceIds);

		echo $this->respond(['invoice_id' => (string)$mergedId]);
	}

	public function getInvoicesByStudentId()
	{
		$studentId = $this->input->get('id');
		echo json_encode(['success' => true, 'data' => $this->Invoicing_model->getAllInvoicesByStudentId($studentId)], JSON_UNESCAPED_UNICODE);
	}

}
