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

require_once APPPATH . 'processors/Base_processor.php';

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

		$discount = get_rights("BSIDI");
		$row = get_rights("BSIMD");
		
		if (!in_array($postData['tType'],array(SALINV,SALRETAIL,DBNOTE)) || empty($discount['actionRights']) || empty($row['actionRights']))
		{
			return true;
		}

		$ci->db->select('ti.itemName, ((ti.discAmount / (IF(t.includeTax=1, ti.itemTotal, ti.taxableAmount) + ti.discAmount)) * 100) AS totDiscPercent');
		$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->where(array(
			'ti.cId'	=> $this->params->cId,
			'ti.transId'	=> $postData['id']
		));
		$ci->db->having("totDiscPercent > " . $row['actionRights']);
		$tmp = $ci->db->get()->row_array();

		if (!empty($tmp['itemName']))
		{
			throw new Exception(sprintf(lang('ITEM_EXCEEDS_MAX_DISCOUNT'), $tmp['itemName'], $row['actionRights'].'%'));
			return false;
		}

		return true;
	}
}
