<?php defined('BASEPATH') OR exit('No direct script access allowed');

trait TransRefPayment {

	/**
	 * Reallocates previously linked payments from reference transactions to the current invoice / bill.
	 *
	 * Use Case:
	 * - When a receipt or payment was originally made against an Estimate, Sales Order, 
	 *   Purchase Quote, or Purchase Order.
	 * - Once the final Sales Invoice or Purchase Bill is created, this function:
	 *   - Unlinks the payments from the earlier references.
	 *   - Reassigns those payments to the new invoice.
	 *   - Updates the due amount accordingly.
	 *
	 * Example:
	 * - A receipt was created for a Sales Estimate.
	 * - When the Sales Invoice is created, this function moves the payment from the Estimate to the Invoice.
	 *
	 * Conditions:
	 * - Only works when creating a Sales Invoice (SALINV) or Purchase Invoice (PURINV).
	 * - Reference types must be among Estimate, Sales Order, Job Order, Purchase Request, or Purchase Order.
	 */
	public function reallocate_referenced_payments(&$data)
	{
		if (
			!TransFlag::$isNewtrans ||
			empty($data['refTtype']) ||
			empty($data['refList']) ||
			!in_array($data['refTtype'], array(EST,SALORD,JOBORD,PUREST,PURORD)) ||
			!in_array($data['tType'], array(SALINV, PURINV))
		) {
			return false;
		}
		/*if (empty($data['id'])  && !empty($data['refTtype']) && $data['refTtype']==EST && $data['tType']==SALINV && !empty($data['refList'])) { */
		$transId = $data['id'];
		$this->CI->db->select('tp.*')->from('trans as t');
		$this->CI->db->join('trans_payment as tp','tp.allotTransId=t.id');
		$where = array(
			't.cId' => $this->cId
		);
		$this->CI->db->where($where);
		$this->CI->db->where_in('tp.allotTransId', $data['refList']);
		$tmp_pay = $this->CI->db->get()->result_array();

		if ($tmp_pay)
		{
			$data['status'] = 'S';
			TransFlag::$reference_payment = true;
			$totAmount = $data['totAmount'];
			foreach ($tmp_pay as $pay)
			{
				$totAmount -= $pay['allotAmt'];
				if ($totAmount >= 0)
				{
					$where = array(
						'cId' => $this->cId
					);
					$this->CI->db->where($where);
					$this->CI->db->where('allotTransId', $pay['allotTransId']);
					$this->CI->db->set('allotTransId',$transId);
					$this->CI->db->update('trans_payment');

					/* reset due amount based refered transaction payments*/
					$this->CI->db->set('dueAmount','dueAmount'.($data['tType']==SALINV?'+':'-').$pay['allotAmt'],false);
					$this->CI->db->where(array('transId' => $pay['transId'], 'conId' => $data['conId']));
					$this->CI->db->update('trans_acc');
				}

				if ($totAmount <= 0)
				{
					break;
				}
			}
		}
	}
}

