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

require_once APPPATH . 'processors/Base_processor.php';

class NegativeItemsProcessor extends Base_processor
{
	public function post_save(&$postData, &$result)
	{
		$ci =& get_instance();

		$ci->db->select('ti.itemName, ti.qty AS orgQty, ti.qty - sum(if(ref_ti.qty && tref.bId=' . $this->params->bId . ', ref_ti.qty, 0)) AS qty',false);
		$ci->db->from('trans AS t');
		$ci->db->join('trans_items AS ti', 'ti.transid=t.id  AND t.id=' . $postData['id'] . ' and t.cId=' . $this->params->cId);
		$ci->db->join('trans_ref AS ref_tf', "ref_tf.reftransId = t.id", "left");
		$ci->db->join("trans AS tref", "tref.id=ref_tf.transId", "left");//ignore trans refered in other branches ex SI to SH
		$ci->db->join('trans_items AS ref_ti', 'ref_ti.refTitemId=ti.id and ref_ti.transId = ref_tf.transId', "left");
		$ci->db->join('items AS i', 'ti.itemId = i.itemId AND ti.cId=i.cId', 'left');
		$ci->db->join("itemrelunits as iru", "iru.itemId=ti.itemId AND iru.relUnitName=ti.unit", "left");
		$ci->db->where(array(
			'ti.cId'		=> $this->params->cId,
			'ti.transId'	=> $postData['id']
		));
		$ci->db->group_by('ti.id,ti.itemAttrId');
		$ci->db->having('qty < ', 0);

		$tmp = $ci->db->get()->row_array();

		if ($tmp)
		{
			throw new Exception(sprintf(lang('ITEM_GOES_TO_NEGATIVE'), $tmp['itemName']));
			return false;
		}
	}
}
