<?php
/*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */
class CTMobileSettings_SaveSyncManualData_Action extends Vtiger_Save_Action {
	public function process(Vtiger_Request $request) {
		global $adb;
		$mode = $request->get('mode');
        $module = $request->getModule();
       
		if($mode == 'saveDataByRecordId'){
            $tabId = getTabid($request->get('search_module'));
            if (!empty($_FILES["filename"]["tmp_name"])) {
                $fileName = $_FILES["filename"]["tmp_name"];
                //echo $fileName;

                $allowed = array('csv');
                $filename = $_FILES['filename']['name'];
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                if (in_array($ext, $allowed)) {
                    
                    if ($_FILES["filename"]["size"] > 0) {
                        $file = fopen($fileName, "r");
                        $i=0;
                        while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
                            if($i == 0){
                                $i++;
                                continue;
                            }
                           
                            $recordid = trim($column[0]);
                            if(!empty($recordid)){

                                $status = $this->checkRecordExist($recordid,$tabId);
                                               
                                if($status == 1){
                                    $updateQuery = $adb->pquery("UPDATE ct_address_lat_long SET latitude=?,longitude=? WHERE recordid=? AND moduleid=?", array($column[1],$column[2],$recordid,$tabId));
                                }else{
                                    $insertQuery = $adb->pquery("INSERT INTO ct_address_lat_long(recordid,moduleid,latitude,longitude) VALUES(?,?,?,?)", array($recordid,$tabId,$column[1],$column[2]));
                                }
                            }
                            
                        }
                        $result = array('success' => true);
                    }
                }else{
                    
                    $result = array('success' => false, 'msg' => vtranslate('LBL_SELECT_CSV_FILE'));
                    
                }
               
                $response = new Vtiger_Response();
                $response->setResult($result);
                $response->emit();
            }
        }else if($mode == 'saveDataByEntityfield'){
            $entitymodulename = $request->get('entity_search_module');
            $tabId = getTabid($entitymodulename);
            $arrFieldNames = $request->get('search_field_module');
            $arrFileFields = array();
            
            if (!empty($_FILES["fieldfilename"]["tmp_name"])) {
                $fileName = $_FILES["fieldfilename"]["tmp_name"];
                //echo $fileName;

                $allowed = array('csv');
                $filename = $_FILES['fieldfilename']['name'];
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                if (in_array($ext, $allowed)) {
                    if ($_FILES["fieldfilename"]["size"] > 0) {
                        $file = fopen($fileName, "r");
                        $i=0;
                        $checkEmpty = false;

                        //check for wrong template code start
                        while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
                            //take field names
                            if($i == 0){
                                for($k=0; $k<count($column)-2; $k++){
                                    $arrFileFields[] = $column[$k];
                                }
                                $i++;
                            }
                            break;
                        }
                        $templateStatus = $this->checkTemplate($entitymodulename,$arrFileFields);
                        $i=0;
                        if($templateStatus){
                           
                            while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
                                
                                //check for empty value
                                for($k=0; $k<count($column); $k++){
                                    if($column[$k] == "")
                                        $checkEmpty = true;  
                                }
                                if($checkEmpty)
                                    continue;

                                $recordid = $this->getRecordIdByField($entitymodulename,$arrFileFields,$column);
                                
                                if($recordid > 0){
                                   
                                    $status = $this->checkRecordExist($recordid,$tabId);
                                          
                                    $totalField = count($arrFileFields);
                                    $latitude =  $column[$totalField];  
                                    $longitude =  $column[$totalField+1];
                                   
                                    if($status == 1){
                                        $updateQuery = $adb->pquery("UPDATE ct_address_lat_long SET latitude=?,longitude=? WHERE recordid=? AND moduleid=?", array($latitude,$longitude,$recordid,$tabId));
                                    }else{
                                        $insertQuery = $adb->pquery("INSERT INTO ct_address_lat_long(recordid,moduleid,latitude,longitude) VALUES(?,?,?,?)", array($recordid,$tabId,$latitude,$longitude));
                                    }
                                }
                            }
                           
                            $result = array('success' => true);
                        }else{
                            $result = array('success' => false, 'msg' => vtranslate('LBL_INVALID_TEMPLATE',$module ));
                        }
                    }
                }else{
                    $result = array('success' => false, 'msg' => vtranslate('LBL_SELECT_CSV_FILE'));
                }
               
                $response = new Vtiger_Response();
                $response->setResult($result);
                $response->emit();
            }    
        }
	}

    //function that check correct template/csv uploaded or not
    function checkTemplate($module,$fieldnames){
        $checkTemplate = true;
        $moduleModel = Vtiger_Module_Model::getInstance($module);
        $fieldModels = $moduleModel->getFields();

        for($i=0; $i<count($fieldnames); $i++){
            if (!array_key_exists($fieldnames[$i],$fieldModels)){
                $checkTemplate = false;
            }
        }
        return $checkTemplate;
    }

    //function check record exist or not
    function checkRecordExist($recordid,$tabid){
        global $adb;
        $status =0;
        $query = $adb->pquery("SELECT recordid FROM ct_address_lat_long WHERE recordid=? AND moduleid=?", array($recordid,$tabid));

        $numofrows = $adb->num_rows($query);
        if($numofrows > 0)
            $status =1;
        return $status;
    }

    //function to get record id from module and field name
    function getRecordIdByField($module,$arrfieldname,$arrcolumn){
        global $adb, $current_user;
        $basetablename = '';
        $basetableid = '';
        $recordid = 0;
        $tabid = getTabid($module);
       
        
        $moduleModel = Vtiger_Module_Model::getInstance($module);
        $fieldModels = $moduleModel->getFields();
        $fieldModel = $fieldModels[$arrfieldname[0]];

        $basetablename =  $moduleModel->get('basetable');
        $basetableid = $moduleModel->get('basetableid');

        $setFields = array('id');
        $setFields = array_merge($setFields, array_values($arrfieldname));

        $generator = new EnhancedQueryGenerator($module, $current_user);
        $generator->setFields($setFields);
        $query = $generator->getQuery();
            
        for($i=0; $i<count($arrfieldname); $i++){
            if($arrcolumn[$i] != "")
                $query .= " AND ".$arrfieldname[$i]."='".$arrcolumn[$i]."'";
        }
        
        $result = $adb->query($query);
        $noofrows = $adb->num_rows($result);
        if($noofrows > 0)
            $recordid = $adb->query_result($result,0,$basetableid);
      
        return $recordid;
        
    }
}