<?php

/**
 * VGS Listview Colors
 *
 * @package        VGS Listview Colors
 * @author         Conrado Maggi
 * @license        Commercial
 * @copyright      2018 VGS Global - www.vgsglobal.com
 * @version        Release: 1.0
 */


class VGSListviewColors_VGSListviewColorsAjax_Action extends Vtiger_IndexAjax_View {

    public function process(Vtiger_Request $request) {
        switch ($request->get('mode')) {
            case 'saveListviewColor':
                $db = PearDatabase::getInstance();
                $moduleid = getTabid($request->get('moduleName'));
                $conditionsFormatToSave = VGSListviewColors_Layout_Model::getWorkFlowFilterFromAdvanceFilter($request->get('conditions'));
                if(is_numeric($request->get('recordid'))){
                    $sql = "UPDATE vtiger_vgslistviewcolors SET description=?, conditions=?, color=? WHERE vgslistviewcolorsid=?";
                    $params = array($request->get('description'), Zend_Json::encode($conditionsFormatToSave), $request->get('selectedColor'), $request->get('recordid'));
                }else{
                    $sql = "INSERT INTO vtiger_vgslistviewcolors (moduleid, description, conditions, color) VALUES (?,?,?,?)";
                    $params = array($moduleid, $request->get('description'), Zend_Json::encode($conditionsFormatToSave), $request->get('selectedColor'));
                }
		      $result = $db->pquery($sql,$params);
                $response = new Vtiger_Response();
                $response->setEmitType(Vtiger_Response::$EMIT_JSON);
                $response->setResult(array('caption' => vtranslate('Saved', 'VGSListviewColors')));
                $response->emit();
                break;

            case 'deleteColumnsForModule':
                $db = PearDatabase::getInstance();
        $result = $db->pquery("DELETE FROM vtiger_vgslistviewcolors WHERE vgslistviewcolorsid=? LIMIT 1",array($request->get("record_id")));
                $affectedRows = $db->getAffectedRowCount($result);

                $response = new Vtiger_Response();
                $response->setEmitType(Vtiger_Response::$EMIT_JSON);
                $response->setResult(array('caption' => vtranslate('JS_DELETED_SUCCESSFULLY_FOR', 'VGSListviewColors')));
                $response->emit();
                break;
            case 'getModuleListviewColor':
                global $current_user;
                $moduleid = getTabid($request->get('moduleName'));
                $moduleName = $request->get('moduleName');
                $ids = $request->get('ids');
                $data = [];
                $existLayout = false;
                $db = PearDatabase::getInstance();
        		$result = $db->pquery("SELECT * FROM vtiger_vgslistviewcolors WHERE moduleid=?",array($moduleid));
                if($db->num_rows($result) > 0){
                    $i = 0;
                    $existLayout = true;
                    while ($row = $db->fetchByAssoc($result)) {
                        $data[$i]['conditions'] = json_decode(html_entity_decode($row['conditions'],ENT_COMPAT,'UTF-8'),true);
                        $data[$i]['color'] = html_entity_decode($row['color'],ENT_COMPAT,'UTF-8');
                        $i++;
                    }
                }

                $resp=array();

                foreach ($ids as $key => $id) {
                    foreach ($data as $key2 => $value) {
                        if($this->validator($value['conditions'],$id,$moduleName))
                            $resp[]=array('id' => $id, 'color' =>$value['color']);
                    }
                }
                

                $response = new Vtiger_Response();
                $response->setEmitType(Vtiger_Response::$EMIT_JSON);
                $response->setResult(array('resp' => $resp, 'existLayout' => $existLayout));
                $response->emit();
                break;
            
        }
    }

    public function validator($conditions,$id,$moduleName){

        $allConditions = true;
        $anyConditions = false;
        foreach ($conditions as $key => $condition) {
            if(!$allConditions){
                return false;
            }
            if($anyConditions){
                return true;
            }
            $fieldName = $condition['fieldname'];
            $fieldValue = $condition['value'];
            $valueType = $condition['valuetype'];
            $operation = $condition['operation'];
            $joincondition = $condition['joincondition'];
            $elementData = '';//to store necesary data related to the element. ex. date-format
            $savedValue = '';//to store db value of field
            
            $elementValue = ''; //value from row

            $focus = CRMEntity::getInstance($moduleName);
            $focus->id=$id;
            $focus->retrieve_entity_info($focus->id,$moduleName);

            $elementValue=$focus->column_fields[$fieldName];

            //compare
            if($joincondition == 'and' || $joincondition == ''){
                if(!$this->validate($fieldName,$fieldValue,$valueType,$operation,$elementValue,$elementData,$savedValue)){
                    $allConditions = false;
                }
            }else{
                if($this->validate($fieldName,$fieldValue,$valueType,$operation,$elementValue,$elementData,$savedValue)){
                    $anyConditions = true;
                }
            }
        }
        if($anyConditions){
            return true;
        }else if($allConditions){
            return true;
        }else{
            return false;
        }
    }

    public function validate($fieldName,$fieldValue,$valueType,$operation,$elementValue,$elementData,$savedValue){
        switch($operation){
            case 'is':
                return (strcmp($elementValue, $fieldValue) == 0);
                break;
            case 'contains':
                return (strpos($elementValue, $fieldValue) !== false);
                break;
            case 'does not contain':
                return (strpos($elementValue, $fieldValue) === false);
                break;
            case 'starts with':
                return startsWith($elementValue, $fieldValue);
                break;
            case 'ends with':
                return endsWith($elementValue, $fieldValue);
                break;
            case 'is empty':
                return (empty($elementValue));
                break;
            case 'is not empty':
                return (!empty($elementValue));
                break;
            case 'less than':
                return ((float)($elementValue) < (float)($fieldValue));
                break;
            case 'greater than':
                return ((float)($elementValue) > (float)($fieldValue));
                break;
            case 'not equal to':
                return ((float)($elementValue) != (float)($fieldValue));
                break;
            case 'less than or equal to':
                return ((float)($elementValue) <= (float)($fieldValue));
                break;
            case 'greater than or equal to':
                return ((float)($elementValue) >= (float)($fieldValue));
                break;
            case 'between':
                $dateArray = split(',', $fieldValue);
                $begin = date('Y-m-d', strtotime($dateArray[0]));
                $end = date('Y-m-d', strtotime($dateArray[0]));
                $elementdate = date('Y-m-d', strtotime($elementValue));

                return (($elementdate > $begin) && ($elementdate < $end));
                break;
            case 'is added':
                return true;//how to implement this?
                break;
            case 'equals':
                return ((float)($elementValue) == (float)($fieldValue));
                break;
            case 'is not':
                $elementdate = date('Y-m-d', strtotime($elementValue));
                $otherdate = date('Y-m-d', strtotime($fieldValue));

                return (($elementdate != $otherdate));
                break;
            case 'is today':
                $elementdate = date('Y-m-d', strtotime($elementValue));
                $today = date('Y-m-d', strtotime());

                return (($elementdate == $today));
                break;
            case 'is tomorrow':
                $tomorrow=date('Y-m-d',strtotime("+1 days"));;
                $elementdate = date('Y-m-d', strtotime($elementValue));
                return (($elementdate == $tomorrow));
                break;
            case 'is yesterday':
                $yesterday=date('Y-m-d',strtotime("-1 days"));
                $elementdate = date('Y-m-d', strtotime($elementValue));
                return (($elementdate == $yesterday));
                break;
            case 'less than hours before'://how to implement this?
                return true;
                break;
            case 'less than hours later'://how to implement this?
                return true;
                break;
            case 'more than hours before'://how to implement this?
                return true;
                break;
            case 'more than hours later'://how to implement this?
                return true;
                break;
            case 'in less than'://how to implement this?
                return true;
                break;
            case 'in more than'://how to implement this?
                return true;
                break;
            default://how to implement this?
                return false;
                break;
            
                
        }

    }

}

//Aux Functions
function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);

    return $length === 0 || 
    (substr($haystack, -$length) === $needle);
}