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

require_once APPPATH . 'processors/Transaction_processor.php';
require_once APPPATH . 'processors/traits/TransRefPayment.php';

class Purinv_processor extends Transaction_processor
{
	use TransRefPayment;
/*
	public function __construct()
	{
		parent::__construct();
		// $this->ci =& get_instance();
	}
*/
	public function init_save(&$postData)
	{
		parent::init_save($postData);

		$this->_check_purchase_charges($postData);
	}

/*
	public function addValidator(&$transData)
	{
		parent::addValidator(new TransValidator($transData));
		// parent::addValidator(new SalinvValidator());
		// parent::addValidator(new SalinvValidator());
	}

	public function process_before_save(&$transData, &$postData)
	{
		parent::process_before_save($transData, $postData);

		
	}

	public function process_after_save(&$retData, &$postData)
	{
		parent::process_after_save($transData, $postData);
	}

	public function process_related_transaction($newtType, $newTransId, $tType, $transId, &$newTransData, &$postData)
	{
		parent::process_related_transaction($newtType, $newTransId, $tType, $transId, $newTransData, $postData);
	}
*/

	private function _check_purchase_charges(&$data)
	{
		if (!isset($data['tType']) || $data['tType'] != PURINV)
		{
			return true;
		}
		if (empty($data["details"]))
		{
			return false;
		}
		$itemIds = array_column($data["details"], "itemId");

		if (empty($itemIds))
		{
			return true;
		}

		$ci =& get_instance();

		$itemIds = $ci->db->select("GROUP_CONCAT(itemId) AS itemId")->from("items")->where('cId', $this->params->cId)->where_in("itemId", $itemIds)->where(array(
			"type" => "G",
			"isInventory" => 1
		))->get()->row_array();

		if (empty($itemIds) || empty($itemIds["itemId"]))
		{
			return true;
		}

		$itemIds = explode(",", $itemIds["itemId"]);

		$chargesField = array();
		if (!empty($data["fields"]))
		{
			foreach($data["fields"] as $field)
			{
				if (!empty($field["fType"]) && $field["fType"] == "charges" && (empty($field["unit"]) || $field["unit"] != "LBT"))
				{
					$chargesField[] = $field["fId"];
				}
			}
		}

		$taxableAmount	= 0;
		$totalExpenses	= 0;
		$totalCharges = 0;
		$systemCharges = 0;
		foreach ($data["details"] as $detail)
		{
			$isGrid = !empty($detail["settings"]) && !empty($detail["settings"]["isGrid"]) && $detail["settings"]["isGrid"] == 1;

			if (!empty($detail["custFields"]) && !empty($chargesField))
			{
				foreach($chargesField as $fId)
				{
					if (!empty($detail["custFields"]["cf_" . $fId]))
					{
						if(is_array($detail["custFields"]["cf_" . $fId]) && $detail["custFields"]["cf_" . $fId]["val"])
						{
							$systemCharges += (float)$detail["custFields"]["cf_" . $fId]["val"];
						}
						else
						{
							$systemCharges += (float)$detail["custFields"]["cf_" . $fId];
						}
					}
				}
			}

			if (in_array($detail["itemId"], $itemIds))
			{
				$taxableAmount += $detail["taxableAmount"];

				if (!empty($detail["chargesAmount"]))
				{
					$totalCharges += $detail["chargesAmount"];
				}
			}

			$unit = !empty($detail["unit"]) ? $detail["unit"] : (!empty($detail["uom"]) ? $detail["uom"] : "");

			if ($unit == "ASV" && !$isGrid)
			{
				$totalExpenses += (float)$detail["taxableAmount"];
			}
			else if (!$isGrid && in_array($unit, array("ABT", "AAT", "AAL")) && !empty($detail["chargesAmount"]) && $detail["chargesAmount"] > 0)
			{
				$totalExpenses += (float)$detail["chargesAmount"];
			}
		}

		$currFraction = 2;
		$salSettings = get_company("salSettings");
		if (!empty($salSettings))
		{
			$currFraction	= !empty($salSettings["currFraction"])	? $salSettings["currFraction"]	: 2;
		}

		if (round($totalCharges, $currFraction) != round($totalExpenses + $systemCharges, $currFraction))
		{
			throw new Exception("Total Charges amt not match with total expenses");
			return false;
		}
/*
		$lastDetail = null;
		$_chargesAmount = 0;
		foreach ($data["details"] as &$detail)
		{
			if (in_array($detail["itemId"], $itemIds))
			{
				$detail["chargesAmount"] = floor(($detail["taxableAmount"] / $taxableAmount) * $totalExpenses);
				$_chargesAmount += $detail["chargesAmount"];
				$lastDetail = &$detail;
			}
		}

		if ($lastDetail && $_chargesAmount != $totalExpenses)
		{
			$lastDetail["chargesAmount"] += ($totalExpenses - $_chargesAmount);
		}
*/
		return true;
	}
}
