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

require_once APPPATH . 'processors/Base_processor.php';

class RentalItemsProcessor extends Base_processor
{
	private $in_tTypes = array(CRNOTE,PURRECP);

	public function init_save(&$postData)
	{
		if (empty($postData['id']))
        {
            return true;
        }

		$ci =& get_instance();

        // assembled items
        $ci->db->query('INSERT INTO ' . $ci->db->dbprefix('contacts_config') . ' (cId,conId,code,value) 
        ' . $this->_assembled_query($postData) . '
         ON DUPLICATE KEY UPDATE value=value - IF(' . (in_array($postData['tType'], $this->in_tTypes) ? 1 : 0) . ', -1, 1) * VALUES(value)');

        if (!$this->valid_qty($postData['conId']))
        {
            return false;
        }

        return true;
	}

	public function post_save(&$postData, &$result)
	{
		$ci =& get_instance();

        // assembled items
        $ci->db->query('INSERT INTO ' . $ci->db->dbprefix('contacts_config') . ' (cId,conId,code,value)  
        ' . $this->_assembled_query($postData, true).'
         ON DUPLICATE KEY UPDATE value=value+VALUES(value)');

        if (!$this->valid_qty($postData['conId']))
        {
            return false;
        }

        $this->CI->db->where(array(
			'cId' => $this->params->cId,
			'value =' => 0
		));
		$this->CI->db->like('code', 'RG');
		$this->CI->db->delete('contacts_config');

        return true;
	}

	private function _assembled_query($trans, $aTrans=false)
    {
    	$out_tTypes = array(SALINV, SALRETAIL, DELCHALLAN);
    	$in_tTypes	= array(CRNOTE, PURRECP);

    	$ci =& get_instance();
 
        $bty_query = 'round((CAST(sum(bi.qty*ti.qty) AS CHAR)+0),2) AS value';
        $qty_query = 'round((CAST(sum(ti.qty) AS CHAR)+0),2) AS value';

        if ($aTrans)
        {
            $bty_query = 'round((CAST(sum(bi.qty*ti.qty) AS CHAR)+0),2) * if(t.tType in ("'.implode('", "',$in_tTypes).'"),-1,1) AS value';
            $qty_query = 'round((CAST(sum(ti.qty) AS CHAR)+0),2) * if(t.tType in ("'.implode('", "',$in_tTypes).'"),-1,1) AS value';
        }

        $bom_query = 'SELECT t.cId,t.conId,CONCAT("RG", bi.itemId) AS code,' . $bty_query .
        ' from '. $ci->db->dbprefix('trans_items') . ' as ti JOIN ' . $ci->db->dbprefix('trans') . ' as t on t.id=ti.transId 
        JOIN ' . $ci->db->dbprefix('bom') . ' as b on b.itemId=ti.itemId and b.bomType=ti.itemType and b.cId=ti.cId
        JOIN ' . $ci->db->dbprefix('bom_items') . ' as bi on bi.bomId=b.id and  bi.pType="C"
        JOIN ' . $ci->db->dbprefix('items') . ' as it on it.itemId=bi.itemId and it.type="R"
        WHERE ti.transId=' . $trans['id'].' AND ti.itemType="Y" 
        AND ((t.tType in ("'.implode('", "',$in_tTypes).'") AND t.reftType not in ("'.implode('", "',$in_tTypes).'")) OR (t.tType in ("'.implode('", "',$out_tTypes).'") AND t.reftType not in ("'.implode('", "',$out_tTypes).'")))
        AND t.categoryCode!="TL" 
        AND t.status not in ("'.implode('", "',$ci->config->item('ignore_status')).'") group by bi.itemId';

        $query = 'SELECT t.cId,t.conId,CONCAT("RG", ti.itemId) AS code,'.$qty_query.
        ' from '. $ci->db->dbprefix('trans_items') . ' as ti JOIN ' . $ci->db->dbprefix('trans') . ' as t on t.id=ti.transId 
        WHERE ti.transId='.$trans['id'].' AND ti.itemType="R" 
        AND ((t.tType in ("'.implode('", "',$in_tTypes).'") AND t.reftType not in ("'.implode('", "',$in_tTypes).'")) OR (t.tType in ("'.implode('", "',$out_tTypes).'") AND t.reftType not in ("'.implode('", "',$out_tTypes).'")))
        AND t.categoryCode!="TL" 
        AND t.status not in ("'.implode('", "',$ci->config->item('ignore_status')).'") group by ti.itemId';

        $query = 'select src.cId,src.conId,src.code,sum(src.value) as value from ('.$query.' UNION ALL '.$bom_query.') src 
        join ob_contacts as c on c.id=src.conId and c.csType not in ("B","L","F") group by code';

        return $query;
    }

	private function valid_qty($conId)
    {
    	$ci =& get_instance();

        $ci->db->select('it.name,c.value')->from('contacts_config as c');
        $ci->db->join('items as it','it.cId=c.cId and c.code=concat("RG",it.itemId)');
        $ci->db->where(array(
			'c.cId' => $this->params->cId,
            'c.conId' => $conId,
			'c.value <' => 0
		));

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

        if (!empty($row['value']))
        {
        	throw new Exception(sprintf(lang('RENTAL_ITEM_GOES_TO_NEGATIVE'), $row['name']));
            return false;
        }

        return true;
    }
}
