<?php

use app\libraries\CommonHelper;
use app\libraries\Tenants;
use app\libraries\Userstamp;

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

class Receipt_item_model extends MY_Model
{

	use Tenants;

	public $database;
	public $short = "ri";
	public $table;
	public $tbl;

	// TODO: place this value to setting_center table
	const days_before_payment_next_month = 7;

	public function __construct()
	{
		$this->load->model('Invoice_model');
		$this->load->model('Student_credit_model');
		$this->load->model('Receipt_item_model');
		parent::__construct();
		$this->database = $this->getTenantNo();
		$this->tbl = 'invoicing_receipt_item';
		$this->table = $this->tbl . ' ' . $this->short;
	}

	public function detail_print($id)
	{
		return $this->getOneRow($this->database, $this->tbl, ['id', 'pic_1', 'room_id', 'user_id', 'original_amount', 'amount_to_pay', 'amount_paid', 'issued_name', 'issued_date', 'payment_status', 'source', 'pathname', 'invoice_status'], ['id' => $id, 'status' => 1]);
	}

	public function listing()
	{
		$this->tenant();
		return $this->getAll($this->database, $this->tbl, ['status' => 1]);
	}

	private function getItemsByInvoiceId($invoiceId, $sumup = true)
	{
		if ($sumup) {
			$sql = "SELECT ri.user_id, sum(ri.cash_amount) as cash_amount,sum(ri.cheque_amount) as cheque_amount, sum(ri.atm_amount) as atm_amount FROM `mas_invoicing_receipt_item` ri 
join mas_invoicing_receipt r on ri.receipt_id=r.id
WHERE ri.status=1 and r.invoice_id=?
group by ri.user_id";
			$db = $this->load->database($this->database, TRUE);
			$data = $db->query($sql, $invoiceId)->result_array();
			return $data;
		}else{
			$sql = "SELECT ri.id,ri.user_id, ri.cash_amount,ri.cheque_amount, ri.atm_amount, ri.payment_type_id,ri.payment_date,ri.cheque_bank_name,ri.cheque_no FROM `mas_invoicing_receipt_item` ri 
join mas_invoicing_receipt r on ri.receipt_id=r.id
WHERE ri.status=1 and r.invoice_id=?";
			$db = $this->load->database($this->database, TRUE);
			$data = $db->query($sql, $invoiceId)->result_array();
			return $data;
		}

	}

	/**
	 * @param array $receipts
	 * @param $data
	 */
	private function getAllSumFromReceiptItems($receipts, $invoiceId): array
	{
		$ritems = [];
		if (!empty($receipts)) {
			$ritems = $this->getMergedItems($receipts);
//			print_r($ritems);
			if (!empty($ritems)) {
//				print_r($useritem);
//				print_r($data);
				$inmergeitems = $this->getItemsByInvoiceId($invoiceId);
//				print_r($inmergeitems);
				$allitems = array_merge($inmergeitems, $ritems);
//				print_r($allitems);
				return $allitems;
			}
		}
		return $ritems;
	}

	public function listing_in_invoicing_read($invoiceId): array
	{
		$this->tenant();
		$db = $this->load->database($this->database, TRUE);
		$data = $db->from($this->table_prefix . $this->tbl)
			->where('mas_invoicing_receipt.invoice_id', $invoiceId)
			->where('mas_invoicing_receipt_item.status', 1)
			->join('mas_invoicing_receipt', 'mas_invoicing_receipt_item.receipt_id = mas_invoicing_receipt.id')
			->join('mas_payment_type', 'mas_invoicing_receipt_item.payment_type_id = mas_payment_type.id')
			->select('mas_invoicing_receipt.invoice_id,mas_invoicing_receipt.id as receipt_id,mas_invoicing_receipt_item.user_id,
                mas_invoicing_receipt_item.cash_amount,mas_invoicing_receipt_item.cheque_amount,mas_invoicing_receipt_item.atm_amount,mas_invoicing_receipt_item.amount_paid, mas_invoicing_receipt_item.payment_type_id,
                mas_invoicing_receipt_item.payment_date, 
                mas_payment_type.name as payment_type_name')
			->get()->result_array();
//		log_message('debug','sql:'.$db->last_query());
		$invoice = $this->Invoice_model->detail($invoiceId);
		$mergedcode = $invoice['mergedcode'];
		//$isinvoiceinmerge = $invoice['invoice_status'] !== InvoiceStatus::merged && !empty($mergedcode);
		if (CommonHelper::checkIfIsInvoiceInMerge($invoice)) {
			//find original invoices:
			$invoices = $this->Invoicing_model->getallmerged($mergedcode);
			$ids = [];
			foreach ($invoices as $i) {
				$ids[] = $i['id'];
			}
			$this->load->model('Receipt_model');
			$receipts = $this->getAllIn($this->database, $this->Receipt_model->tbl, [], 'invoice_id', $ids);
			unset($data);
			$data = $this->getAllSumFromReceiptItems($receipts, $invoiceId);
			return $data;
		}
//		$openaftercancelmerged = $invoice['invoice_status'] === InvoiceStatus::openaftercancelmerged;
		if (CommonHelper::checkIfOpenAfterCancelMerged($invoice)) {
			//find the cancelmerged invoice
			$cancelmergedInvoice = $this->Invoice_model->getCancelMergedInvoice($invoice['mergedcode']);
			$ritems = $this->getItemsByInvoiceId($cancelmergedInvoice['id']);
			return array_merge($ritems, $data);
		}
		return $data;
	}

	public function getAllReceiptItemDetail($invoice): array
	{
		$ritems = [];
		$receipts = $this->Receipt_model->getByInvoiceId($invoice['id']);
//		log_message('debug','invoiceid:'.$invoiceId.';empty receipts?'.empty($receipts));
		if (!empty($receipts)) {
			$ids = [];
			foreach ($receipts as $r) {
				$ids[] = $r['id'];
			}
			$strids = implode(',', $ids);
//		print_r($strids);
			$sql = "SELECT id,payment_date, cash_amount, user_id,payment_type_id FROM `mas_invoicing_receipt_item` WHERE receipt_id in ($strids) and status=1 and payment_type_id=?";
			$db = $this->load->database($this->database, TRUE);
			$cashitems = $db->query($sql, PaymentType::Cash)->result_array();
			$sql = "SELECT id,payment_date, cheque_amount, cheque_no,cheque_bank_name, user_id,payment_type_id FROM `mas_invoicing_receipt_item` WHERE receipt_id in ($strids) and status=1 and payment_type_id=?";
			$chequeitems = $db->query($sql, PaymentType::Cheque)->result_array();
			foreach ($chequeitems as $k => $d) {
				$chequeitems[$k]['cheque_bank_name'] = $this->getBankNameByCode($d['cheque_bank_name']);
			}
			$sql = "SELECT id,payment_date, atm_amount, user_id,payment_type_id FROM `mas_invoicing_receipt_item` WHERE receipt_id in ($strids) and status=1 and payment_type_id=?";
			$atmitems = $db->query($sql, PaymentType::ATM)->result_array();
			$ritems = array_merge($cashitems, $chequeitems, $atmitems);
			foreach ($ritems as $k => $v) {
				if (isset($v['payment_date'])) {
					$ritems[$k]['payment_date'] = date('Y-m-d H:i', $v['payment_date']);
				}
				if (isset($v['cash_amount'])) {
					$ritems[$k]['cash_amount'] = CommonHelper::money($v['cash_amount']);
				}
				if (isset($v['cheque_amount'])) {
					$ritems[$k]['cheque_amount'] = CommonHelper::money($v['cheque_amount']);
				}
				if (isset($v['atm_amount'])) {
					$ritems[$k]['atm_amount'] = CommonHelper::money($v['atm_amount']);
				}

			}
		}

		if (CommonHelper::checkIfIsInvoiceInMerge($invoice)) {
			$mergedcode = $invoice['mergedcode'];
			//find original invoices:
			$invoices = $this->Invoicing_model->getallmerged($mergedcode);
			$ids = [];
			foreach ($invoices as $i) {
				$ids[] = $i['id'];
			}
			$receipts = $this->Receipt_model->getByInvoiceIds($ids);
			if (!empty($receipts)) {
				$data = $this->getByReceipts($receipts);
//				print_r($data);
				$cashitems = [];
				$chequeitems = [];
				$atmitems = [];
				foreach ($data as $k => $v) {
					if ($v['payment_type_id'] == PaymentType::Cash) {
						$cashitems[] = ['id' => $v['id'], 'cash_amount' => CommonHelper::money($v['cash_amount']), 'payment_date' => date('Y-m-d H:i', $v['payment_date']), 'payment_type_id' => PaymentType::Cash, 'user_id' => $v['user_id']];
					}
					if ($v['payment_type_id'] == PaymentType::ATM) {
						$atmitems[] = ['id' => $v['id'], 'atm_amount' => CommonHelper::money($v['atm_amount']), 'payment_date' => date('Y-m-d H:i', $v['payment_date']), 'payment_type_id' => PaymentType::ATM, 'user_id' => $v['user_id']];
					}
					if ($v['payment_type_id'] == PaymentType::Cheque) {
						$chequeitems[] = ['id' => $v['id'], 'cheque_amount' => CommonHelper::money($v['cheque_amount']), 'payment_date' => date('Y-m-d H:i', $v['payment_date']), 'payment_type_id' => PaymentType::Cheque, 'user_id' => $v['user_id'], 'cheque_no' => $v['cheque_no'], 'cheque_bank_name' => $this->getBankNameByCode($v['cheque_bank_name'])];
					}
				}
				return empty($ritems) ? array_merge($cashitems, $chequeitems, $atmitems) : array_merge($cashitems, $chequeitems, $atmitems, $ritems);
			}

		}
		if (CommonHelper::checkIfOpenAfterCancelMerged($invoice)) {
			//find the cancelmerged invoice
			$cancelmergedInvoice = $this->Invoice_model->getCancelMergedInvoice($invoice['mergedcode']);
			$cancelmergeditems = $this->getItemsByInvoiceId($cancelmergedInvoice['id'],false);
			foreach($cancelmergeditems as $k=>$v){
				$cancelmergeditems[$k]['payment_date']=date('Y-m-d H:i',$v['payment_date']);
			}
//			print_r($cancelmergeditems);
			$data = array_merge($ritems, $cancelmergeditems);
//			print_r($data);
			return $data;
		}
		return $ritems;
	}

	public function getItemByAtm($atmId)
	{
		$this->tenant();
		return $this->getOneRow($this->database, $this->tbl, ['id', 'amount_paid'], ['atm_id' => $atmId, 'status' => 1]);
	}

	public function detail($id)
	{
		$this->tenant();
		return $this->getOneRow($this->database, $this->tbl, [], ['id' => $id, 'status' => 1]);
	}

	public function detail_in_receipt($receiptId)
	{
		$this->tenant();
		return $this->getOneRow($this->database, $this->tbl, [], ['receipt_id' => $receiptId, 'status' => 1]);
	}

	public function detail_last($invoiceId, $userId)
	{
		$this->tenant();
		$db = $this->load->database($this->database, TRUE);
		return $db->from($this->table_prefix . $this->tbl)
			->where('user_id', $userId)
			->where('invoice_id', $invoiceId)
			->where('status', 1)
			->order('parent_id', 'DESC')
			->find();
	}

	public function create($params)
	{
		$this->tenant();
		$params['id'] = $this->insertDB($this->database, $this->tbl, $params);
		return $params;
	}

	public function update($params, $id)
	{
		$this->tenant();
		$this->saveDB($this->database, $this->tbl, $params, $id);
		return $id;
	}

	public function create_in_checkout($params, $receiptId, $paymenttypeId = NULL, $cashamt = NULL, $chequeamt = NULL, $bankname = NULL, $chequeno = NULL)
	{
		$this->tenant();
		$this->load->model('Invoicing_model');
		$this->load->model('Invoice_item_model');

		$paymentTypeId = intval($params['payment_type_id']) ?? intval($paymenttypeId);
		$cashAmount = empty($params['cash_amount']) ? 0 : floatval($cashamt);
		$chequeAmount = empty($params['cheque_amount']) ? 0 : floatval($chequeamt);
		$chequeBankName = $params['cheque_bank_name'] ?? $bankname ?? null;
		$chequeNo = $params['cheque_no'] ?? $chequeno ?? null;

		$useCredits = empty($params['use_credits']) ? 0 : floatval($params['use_credits']);
		$invoiceId = $params['invoiceId'];
		$invoice = $this->Invoicing_model->detail($invoiceId);
	
		$mergedcode = $invoice['mergedcode'];
		$atmId = $params['atm_id'] ?? null;

//		log_message('debug','paymenttypeid:'.$paymentTypeId);//2
		if ($paymentTypeId == PaymentType::Cash || $paymentTypeId == PaymentType::Paypal) {
			$params['amount_paid'] = $amountPaid = $cashAmount + $useCredits;
		} elseif ($paymentTypeId == PaymentType::Cheque) {
			$params['amount_paid'] = $amountPaid = $chequeAmount + $useCredits;
		} elseif ($paymentTypeId == PaymentType::ATM) {
			$params['amount_paid'] = $amountPaid = $params['amount'] + $useCredits;
		}
		//$isinvoiceinmerge = $invoice['invoice_status'] !== InvoiceStatus::merged && $invoice['user_id']==0 && $invoice['status']!=0;
		$isinvoiceinmerge = CommonHelper::checkIfIsInvoiceInMerge($invoice);
//		log_message('debug','isinvoiceinmerge:'.$isinvoiceinmerge);
		$data = [];
		if (!$isinvoiceinmerge) {
			$diff = floatval($amountPaid) - (floatval($invoice['amount_to_pay'])-floatval($invoice['amount_paid']));
//			log_message('debug','amountpaid:'.$amountPaid.';amounttopay:'.$invoice['amount_to_pay'].';diff:'.$diff);
			if ($diff > 0) {
				//place the surplus to student credit
				$last = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
				if (!empty($last)) {
					$this->Student_credit_model->create([
						'invoice_id' => $invoiceId,
						'student_id' => $invoice['user_id'],
						'receipt_id' => $receiptId,
						'add_credits' => $diff,
						'credit_amount' => $diff + floatval($last['credit_amount']),
						'next_id' => $last['id']
					]);
				} else {
					$this->Student_credit_model->create([
						'invoice_id' => $invoiceId,
						'student_id' => $invoice['user_id'],
						'receipt_id' => $receiptId,
						'add_credits' => $diff,
						'credit_amount' => $diff,
					]);
				}
			}
			if ($paymentTypeId == PaymentType::ATM) {
				$data[] = [
					'receipt_id' => $receiptId,
					'payment_type_id' => $paymentTypeId,
					'payment_date' => time(),
					'atm_amount' => $amountPaid,
					'amount_paid' => $amountPaid,
					'atm_id' => $atmId,
					'user_id' => $invoice['user_id']
				];
			} else if ($paymentTypeId == PaymentType::Cash) {
				$data[] = [
					'receipt_id' => $receiptId,
					'payment_type_id' => $paymentTypeId,
					'payment_date' => time(),
					'cash_amount' => $amountPaid,
					'amount_paid' => $amountPaid,
					'user_id' => $invoice['user_id']
				];
			} else if ($paymentTypeId == PaymentType::Cheque) {
				$data[] = [
					'receipt_id' => $receiptId,
					'payment_type_id' => $paymentTypeId,
					'payment_date' => time(),
					'cheque_amount' => $amountPaid,
					'cheque_bank_name' => $chequeBankName,
					'cheque_no' => $chequeNo,
					'amount_paid' => $amountPaid,
					'user_id' => $invoice['user_id']
				];
			}
		} else { //merged
			//find original invoices:
			$invoices = $this->getAll($this->database, $this->Invoicing_model->tbl, ['id', 'amount_to_pay', 'amount_paid', 'mergedcode', 'user_id'], ['invoice_status' => InvoiceStatus::merged]);
			$invoiceIds = [];
			$total_amount_to_pay = 0;
			$totalamountpaid=0;
			$factors = [];
			foreach ($invoices as $i) {
				if ($i['mergedcode'] === $mergedcode) {
					$total_amount_to_pay += floatval($i['amount_to_pay']);
					$totalamountpaid += floatval($i['amount_paid']);
					$factors[] = ['invoiceId' => $i['id'], 'amount_to_pay' => floatval($i['amount_to_pay']), 'amount_paid' => floatval($i['amount_paid']), 'user_id' => $i['user_id']];
					$invoiceIds [] = $i['id'];
				}
			}
			//update credit if amountpaid > netamountpayable:
			$diff = floatval($amountPaid) - ($total_amount_to_pay-$totalamountpaid);
			if ($diff > 0) {
				//place the surplus to student credit
				$last = $this->Student_credit_model->detail_in_last_credit($invoice['user_id']);
				if (!empty($last)) {
					$this->Student_credit_model->create([
						'invoice_id' => $invoiceId,
						'student_id' => $invoice['user_id'],
						'receipt_id' => $receiptId,
						'add_credits' => $diff,
						'credit_amount' => $diff + floatval($last['credit_amount']),
						'next_id' => $last['id']
					]);
				} else {
					$this->Student_credit_model->create([
						'invoice_id' => $invoiceId,
						'student_id' => $invoice['user_id'],
						'receipt_id' => $receiptId,
						'add_credits' => $diff,
						'credit_amount' => $diff,
					]);
				}
			} else {
				$factorscount = count($factors);
				$paid = 0;
				foreach ($factors as $k => $v) {
					if ($k === ($factorscount - 1)) {
						break;
					}
					$tmpsum = $amountPaid * floatval($v['amount_to_pay']);
					$payment = floor($tmpsum / $total_amount_to_pay);
					$paid += $payment;
					$invoicepaid = $payment + floatval($v['amount_paid']);
					$this->Invoicing_model->update(['amount_paid' => $invoicepaid], $v['invoiceId']);

					if ($paymentTypeId === PaymentType::ATM) {
						$data[] = [
							'receipt_id' => $receiptId,
							'payment_type_id' => $paymentTypeId,
							'payment_date' => time(),
							'atm_amount' => $payment,
							'amount_paid' => $payment,
							'atm_id' => $atmId,
							'user_id' => $v['user_id']
						];
					} else {
						if ($paymentTypeId == PaymentType::Cash || $paymentTypeId == PaymentType::Paypal) {
							$data[] = [
								'receipt_id' => $receiptId,
								'payment_type_id' => $paymentTypeId,
								'payment_date' => time(),
								'cash_amount' => $payment,
								'amount_paid' => $payment,
								'user_id' => $v['user_id']
							];
						} elseif ($paymentTypeId == PaymentType::Cheque) {
							$data[] = [
								'receipt_id' => $receiptId,
								'payment_type_id' => $paymentTypeId,
								'payment_date' => time(),
								'cheque_amount' => $payment,
								'cheque_bank_name' => $chequeBankName,
								'cheque_no' => $chequeNo,
								'amount_paid' => $payment,
								'user_id' => $v['user_id']
							];
						}
					}
				}
				$lastfactor = end($factors);
				$payment = $amountPaid - $paid;
				$invoicepaid = $payment + $lastfactor['amount_paid'];
				$this->Invoicing_model->update(['amount_paid' => $invoicepaid], $lastfactor['invoiceId']);
				if ($paymentTypeId === PaymentType::ATM) {
					$data[] = [
						'receipt_id' => $receiptId,
						'payment_type_id' => $paymentTypeId,
						'payment_date' => time(),
						'amount_paid' => $payment,
						'atm_amount' => $payment,
						'user_id' => $lastfactor['user_id'],
						'atm_id' => $atmId
					];
				} else {
					if ($paymentTypeId == PaymentType::Cash || $paymentTypeId == PaymentType::Paypal) {
						$data [] = [
							'receipt_id' => $receiptId,
							'payment_type_id' => $paymentTypeId,
							'payment_date' => time(),
							'cash_amount' => $payment,
							'amount_paid' => $payment,
							'user_id' => $lastfactor['user_id'],
						];
					} elseif ($paymentTypeId == PaymentType::Cheque) {
						$data [] = [
							'receipt_id' => $receiptId,
							'payment_type_id' => $paymentTypeId,
							'payment_date' => time(),
							'cheque_amount' => $payment,
							'cheque_bank_name' => $chequeBankName,
							'cheque_no' => $chequeNo,
							'amount_paid' => $payment,
							'user_id' => $lastfactor['user_id'],
						];
					}
				}
			}
		}

		$db = $this->load->database($this->database, TRUE);
//		log_message('debug','empty data?'.empty($data));
		$db->insert_batch($this->table_prefix . $this->tbl, $data);
		return $params;
	}

	public function getItemByIds($receiptId, $atmId)
	{
		return $this->getOneRow($this->database, $this->tbl, ['id', 'atm_amount'], ['receipt_id' => $receiptId, 'atm_id' => $atmId, 'status' => 1]);
	}

	public function getDetailByIds($receiptId, $userId)
	{
		$data = $this->getOneRow($this->database, $this->tbl, ['id', 'payment_type_id', 'payment_date', 'cash_amount', 'cheque_amount', 'cheque_bank_name', 'cheque_no', 'atm_amount', 'remark', 'user_id', 'amount_paid'], ['receipt_id' => $receiptId, 'user_id' => $userId, 'status' => 1]);
		if (!empty($data)) {
			$db = $this->load->database('default', TRUE);
			$banks = $db->query('Select code, chi_name from bank')->result_array();
			foreach ($banks as $b) {
				if ($b['code'] === $data['cheque_bank_name']) {
					$data['cheque_bank_name'] = $b['chi_name'];
					break;
				}
			}
		}
		return $data;
	}

	public function getByReceipts($receipts)
	{
		$ids = [];
		foreach ($receipts as $r) {
			$ids[] = $r['id'];
		}
		$data = $this->getAllIn($this->database, $this->tbl, [], 'receipt_id', $ids, true, ['status' => 1]);
		return $data;
	}

	public function getItemsByReceiptId($receiptId)
	{
		$data = $this->getAll($this->database, $this->tbl, ['id', 'payment_type_id', 'payment_date', 'cash_amount', 'cheque_amount', 'cheque_bank_name', 'cheque_no', 'atm_amount', 'remark', 'user_id', 'amount_paid'], ['receipt_id' => $receiptId, 'status' => 1]);
		foreach ($data as $k => $d) {
			$data[$k]['cheque_bank_name'] = $this->getBankNameByCode($d['cheque_bank_name']);
		}
		return $data;
	}

	public function getItemsByAtmId($atmId, $fields = [])
	{
		$_fields = empty($fields) ? ['id', 'receipt_id', 'atm_amount','amount_paid'] : $fields;
		return $this->getAll($this->database, $this->tbl, $_fields, ['atm_id' => $atmId, 'status' => 1]);
	}

	public function deleteIn($ids)
	{
		return $this->deleteDB($this->database, $this->tbl, $ids, true);
	}

	public function all()
	{
		return $this->getAll($this->database, $this->tbl, [], ['status=>1']);
	}

	public function getMergedItems($receipts)
	{
		$ids = [];
		foreach ($receipts as $r) {
			$ids[] = $r['id'];
		}
		$strids = implode(',', $ids);
//		print_r($strids);
		$sql = "SELECT user_id, sum(cash_amount) as 'cash_amount',sum(cheque_amount) as 'cheque_amount',sum(atm_amount) as 'atm_amount' FROM `mas_invoicing_receipt_item` WHERE receipt_id in ($strids) and status=1 group by user_id";
		$db = $this->load->database($this->database, TRUE);
		$data = $db->query($sql)->result_array();
		return $data;
	}

	public function getBanks()
	{
		$db = $this->load->database('default', TRUE);
		return $db->query('Select code, chi_name from bank')->result_array();
	}

	public function getBankNameByCode($code)
	{
		$banks = $this->getBanks();
		foreach ($banks as $b) {
			if ($b['code'] === $code) {
				return $b['chi_name'];
			}
		}
	}

	public function getUsersForTransfer($id)
	{
		return [$this->Student_model->all(), $this->detail($id)['user_id']];
	}

	public function void($id)
	{
		$ritem = $this->detail($id);
		$this->Receipt_model->update(['status' => 0], $ritem['receipt_id']);
		$this->update([
			'status' => 0
		], $id);
		return $ritem;//for refund only
	}

	public function getAmountPaidByIds($inmergeInvoiceId, $receiptId, $userId)
	{
		$this->load->model('Invoicing_model');
		$this->load->model('Receipt_model');
		$db = $this->load->database($this->database, TRUE);
		$db->from($this->table_prefix . $this->tbl);
		$invoice = $this->Invoicing_model->detail($inmergeInvoiceId);
//		log_message('debug','userid:'.$userId.';receiptid:'.$receiptId);
		$amountpaid_inmerge = $db->select_sum('amount_paid')->where(['user_id' => $userId, 'status' => 1,'receipt_id'=>$receiptId])->get()->row()->amount_paid;
		//find original invoices:
		$invoices = $this->Invoicing_model->getallmerged($invoice['mergedcode']);
		$ids = [];
		foreach ($invoices as $i) {
			if ($i['user_id'] == $userId) {
				$ids[] = $i['id'];
			}
		}
//		log_message('debug','ids count:'.count($ids));
		$receiptIds = [];
		if(!empty($ids)){
			$receipts = $this->Receipt_model->getByInvoiceIds($ids);
//		log_message('debug','receipts count:'.count($receipts));
			foreach ($receipts as $receipt) {
				$receiptIds[] = $receipt['id'];
			}
			if(!empty($receiptIds)){
				$db->from($this->table_prefix . $this->tbl);
				$amountpaid_original = $db->select_sum('amount_paid')->where_in('receipt_id', $receiptIds)->where(['user_id' => $userId, 'status' => 1])->get()->row()->amount_paid;
				$db->reset_query();
				$db->from($this->table_prefix . $this->tbl);
				return ($amountpaid_original + $amountpaid_inmerge);
			}
		}
		return $amountpaid_inmerge;
	}
}
