<?php
/*****************************************
 * 
 *      @description  : Array To String Conversion  
 *      @Author       : Outright 
 *      @Date         : 
 *      @param   array        ---> $input_arr  :  array value to convert into string  
 *      @return  string|false ---> $return_str :  Return's the string on success or false on fail      
 *      @since 1.0.0
 * 
 * ***************************************/
function outright_array_to_sql($input_arr){
  if(!is_array($input_arr)){
		return false ; 
  }	
  $return_str ="'".implode("','",$input_arr)."'";
  return $return_str;
}

/*****************************************
 * 
 *     @description : Enum to array convertion
 *     @Author      : Outright 
 *     Date         :  
 *     @param     string --->$enum_string      : Enum string;       
 *     @param     string --->$enum_string_js   : Enum js string;              
 *     @return    array|false --->$enum_string_js : Return's the enum_string_js array on success or false on fail  ;    
 *     @since 1.0.0
 * 
 * ***************************************/		

 function outright_convert_enum_to_array($enum_string,$enum_string_js){		
	$final_ret_array = array();
	$enum_string     = str_replace('^',"",$enum_string);
	$final_ret_array = explode(',',$enum_string);
	$enum_string_js  = str_replace('^',"#",$enum_string_js);
	$enum_string_js  = str_replace('#,',",",$enum_string_js);
	$final_ret_array['enum_js'] = substr($enum_string_js,0,-1);
	return $final_ret_array?$enum_string_js:false;				
 }

/*****************************************
 * 
 *     @description : option to array convert 
 *     @Author      : Outright 
 *     Date         :  
 *     @param     string --->$sql           : mysql query value                                                           
 *     @param     string --->$key_col       : colomn key value                                                                
 *     @param     string --->$val_col       : value  of the colomn                                                                
 *     @return    string|false --->$option  : Returns string value on success or false in fail                                                             
 *     @since 1.0.0
 * 
 * ***************************************/ 
 
function outright_convert_options_from_sql($sql,$key_col,$val_col,$selected=false){
		$options_array = outright_run_id_name_sql($sql,$key_col,$val_col,$selected);	
		$option        = outright_convert_options_from_array($options_array,$selected);
		return $option?$option:false;
	}

/*****************************************
 * 
 *     @description  : Array to html drop down convert 
 *     @Author       : Outright 
 *     @Date         :  
 *     @param       array--->$optionArr : options array;
 *     @param       int|string--->$selected : selected value for drop down list ;
 *     @return  string|false ---> $option :  Return's the string on success or false on fail  ;    
 *     @since 1.0.0
 * 
 * ***************************************/

function outright_convert_options_from_array($optionArr,$selected){
	foreach($optionArr as $key => $values){
	   $sel = '';
	   if($key == $selected){
		   $sel = "selected";
	   }
	   $option .= "<option value='".$key."' ".$sel." >".$values."</option>";
	}
   return $option?$option:false;
}
/*****************************************
 * 
 *     @description : Get colomns from table
 *     @Author      : Outright 
 *     Date         :  
 *     @param     string --->$table       : table name                                                          
 *     @return    array  : Returns array value on success 
 *     @since 1.0.0
 * 
 * ***************************************/ 
 
function outright_getcolumns($table) {
	global $db;
	$sql = "SHOW columns FROM ".$table;
	$rwo = $db->query($sql);
	$ar = array();
	$matchcols = array();
	$i = 0;
	while($res = $db->fetchByAssoc($rwo)){
		$matchcols[] = $res['Field'];
		$ar[$i] = array('fname'=> $res['Field'], 'ftype' => $res['Type']);
		$i++;
	}
	return array('cols'=>$matchcols, 'detail'=>$ar);
}

/*****************************************
 * 
 *     @description : Get user details
 *     @Author      : Outright 
 *     Date         :  
 *     @param     string --->$userID      : user id                                                              
 *     @return    obj|false  : Returns Obj value on success or false on fail
 *     @since 1.0.0
 * 
 * ***************************************/
 
function outright_load_user($userID){
	$user_bean = new User();
	$user_bean->retrieve($userID);
	return $user_bean?$user_bean:false;
}

/*********************
 *start outright_load
 * @description : Get user details
 * @Author      : Outright Systems
 * Date         :  
 * @param     string --->$userID      : user id                                                              
 * @return    obj|false  : Returns Obj value on success or false on fail
 * @since 1.0.0
 ******************/
function outright_run_id_name_sql($sql,$field1,$field2,$ret_str=0){
	global $db;
	$fin_res = array();
	$retrun_str ='';
	$row =$db->query($sql);
	while($res=$db->fetchByAssoc($row)){	
	$fin_res[$res[$field1]] =$res[$field2];	
	}
	
	if($ret_str){
	return outright_array_to_sql_string($fin_res);
	}
	return $fin_res;
}

	function outright_get_custom_fields($mod)
	{
        $outright_sql = "SELECT * FROM fields_meta_data where custom_module = '".$mod."' and deleted = 0";
        $res = outright_run_sql($outright_sql);
        return $res;        
	}
	
	function outright_get_module_fields($module_name = NULL){
	global $app_list_strings;
		if($module_name){
				$fieldArr = outiright_return_ModuleFields($module_name);
				unset($fieldArr['id']);	
				return $fieldArr;
			}
		else{
				$fieldArr = array();
				$moduleList = outright_getModuleName_list();
				foreach( $moduleList as $key => $values ){
						if($values){
								$fieldArr[$key] = outiright_return_ModuleFields($values);
							}
					}
				unset($fieldArr['id']);	
				return $fieldArr;
			}
	}
	




function outright_built_config(array $configOptions = null,$config_loader=true, $dieOnError = false){
	global $sugar_config; 
	if(is_null($configOptions)){
		$configOptions = $sugar_config;
	}
	if($config_loader){
		if(!file_exists('config.php')){
			require_once('config_outright.php');
		 }
		 if(file_exists('config.php')){
			 require_once('config.php');
		 }
	 }
	 if($sugar_config == false && !isset($sugar_config) && empty($sugar_config)){
		 
			$connect_error[]  = "Error has been occured while creatiing a config file . Please refer to outrightcrm.log for details.";
			$err_msg[]        = "Unable to load the data from config_outright.php(or)config.php file please check your directory structure file is existed or not." ;
			if(!$GLOBALS['log']->fatal($err_msg)){
				  outrigt_error_log($this->logfile,$err_msg);
			}
			if($dieOnError) {
				if(isset($GLOBALS['app_strings']['ERR_NO_DB'])) {
					outright_die($GLOBALS['app_strings']['ERR_NO_DB']);
				} else {
				  outright_die("Unable to load the data from config_outright.php(or)config.php file please check your directory structure file is existed or not.");
				}
			} 
			$_SESSION['outright_errors'] = $connect_error ;
			return false;
			
	 }
	 $sugar_config['installer_locked']         = true ;
	 $sugar_config['dbconfig']['db_host_name'] = $configOptions['db_host_name'];
	 $sugar_config['dbconfig']['db_user_name'] = $configOptions['db_user_name'];
	 $sugar_config['dbconfig']['db_password']  = $configOptions['db_password'];
	 $sugar_config['dbconfig']['db_name']      = $configOptions['db_name'] ;
	 $sugar_config['site_url']                 = $configOptions['site_url'] ;
	 $build_config  = outright_array_to_file_write('sugar_config',$sugar_config, 'config.php', $mode="w", $header='' ); 
	 if($build_config)
		return  true ;
	
} 
function outright_get_correct_bean($mod_name){
	global $beanFiles;
	
	$new_bean = BeanFactory::newBean($mod_name);
	// last chance if bean still not retrieved
	if(!$new_bean){
		$GLOBALS['log']->fatal("Your bean name was incorrect! Please correct it in your code".$mod_name);
		if($beanFiles[$mod_name]){
		require_once $beanFiles[$mod_name];
		$new_bean = new $mod_name;
		}
	}
	return $new_bean;
}

/*****************************************
 * start outright_run_sql
 *      @description  : Fetch the data from data base and 
 *      @Author       : Outright 
 *      @Date         : 
 *      @param   string      ---> $sql :  mysql query value; 
 *      @return  array|false ---> $fin_res :  Return's the array on success or false on fail      
 *      @since 1.0.0
 * 
 * ***************************************/

function outright_run_sql($sql){
	global $db;
 
	$fin_res = array();
	$row =$db->query($sql);
	while($res=$db->fetchByAssoc($row)){	
	$fin_res[] =$res;	
	}
	return $fin_res ? $fin_res:false;
}/** End outright_run_sql**/

/*****************************************
 *start outright_run_sql_one_row 
 *      Returns the only one row from data base 
 *      @Author       : Outright 
 *      @Date         :  
 *      @param       string--->$sql : sql query value  ;
 *      @return  array|false ---> $fin_res :  Return's the array on success or false on fail      
 *      @since 1.0.0
 * 
 * ***************************************/
 
function outright_run_sql_one_row($sql){
	global $db;
	$row = $db->query($sql);
	$res = $db->fetchByAssoc($row);
	return $res?$res:false;
}/** End outright_run_sql_one_row**/



function outright_html_table( $data  ){
$table_html = '<table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view table-responsive"><tr>';

   $rows = array();
$fields = array_keys( $data[0]);

foreach( $fields as $field ){
$table_html .="<th scope='col' class='hidden-xs' style='color:green'>".$field."</th>";
}
$table_html .='</tr>';
$table_html .= '<tr><td style="text-align:center color:green" colspan="'.count($fields).'"><b>Total Records '.count($data).'</b></td></tr>';
   foreach ($data as $row) {
         $table_html .= "<tr>";
 foreach( $row as $col ){
  $table_html .= "<td style='padding: 11px 8px 5px 5px !important'>".$col."</td>";
 }
  $table_html .= "</tr>";
   }
$table_html .="</table>";
return $table_html;
}

function ors_get_all_module_fields( $module_load = NULL){
						global $app_list_strings;
						if(  !$module_load){
						$module_load =$_REQUEST['module'];
						}
			$fields =array(''=>'none');

			if( $module_load->source_module && $module_load->source_module !='Home'){
			$module_fields = outright_retrieve( $module_load->source_module ,false);
									foreach( $module_fields->field_defs as $name => $arr ){
										if(isset($arr['vname']) && $arr['vname'] != ''){
														$fields[$name] = rtrim(translate($arr['vname'],$mod->module_dir), ':');
														}
												 else {
														  $fields[$name] = $name;
										}				
									}
			}
			return $fields;
}


function outright_html_table_new( $data ,$module=false,$hide_data =false ,$table_id =false ,$table_class =false ,$row_buttons = false ,$edit_remove =false ,$key =false ){
		$sugar_url = $GLOBALS['sugar_config']['site_url'];

if( !$data[0]){
$data[0] =$data;
}

                if( $hide_data ==1 ){
                $hide_css ='style="display:none"';
                }
                $table_html = '<table cellpadding="0" cellspacing="0" width="100%" border="0" class="table table-striped table-fit '.$table_class.'"" id ="'.$table_id.'" '.$hide_css.'> <thead class="thead-light"><tr><th>#</th>';
                $rows = array();
                $fields = array_keys( $data[0] );

$name_fl =array(
	'id',
'first_name',
'last_name',
'document_name',
);
$skip_col=array(
'id',
	'envelopeId',
);

                foreach( $fields as $field ){
if( in_array($field , $skip_col)){
                      continue;
                                                        }
                    $field =str_replace("_"," ",$field);
                                        $field =str_replace("-"," ",$field);

                    $table_html .="<th scope='col' class='hidden-xs' style='color:green;text-align: center;font-size:16px;'>".ucwords($field)."</th>";
                }
                $table_html .='</tr></thead>';
                //$table_html .= '<tr scope="row"><td style="text-align:center color:green" colspan="'.count($fields).'"><b>Total Records '.count($data).'</b></td></tr>';
                        if( count($data) ){
                                           foreach ($data as $row) {
                                                $cnt++;
                                                $table_html .= "<tr scope='row'><td >".$cnt."</td>";
                                            
                                                foreach( $row as $fld=>$col ){
                                                        if( in_array($fld , $skip_col)){
                                                        continue;
                                                        }
                                                            if( in_array($fld , $name_fl)){

                                                                  $table_html .= "<td style = 'text-align: center' scope='col'><a target='_blank' href='".$sugar_url."/index.php?action=DetailView&module=".$module."&record=".$row['id']."' class='edit_me' id='".$row['document_name']."' '>".$col."</a></td>";
                                                            }
                                                    else{
														if($fld == 'link'){
															$table_html .= "<td style = 'text-align: left' scope='col'><a href='$col' target='_blank'>Click Here</a></td>";
														}else{
															$table_html .= "<td style = 'text-align: left' scope='col'>".$col."</td>";
														}
                                                    }
                                                }

                                              $table_html .= "</tr>";
                                        }
                        }
        
                        $table_html .="</table>";

                        return $table_html;
}


function outright_get_all_fields( $module_load = NULL){
						global $app_list_strings;
						if(  !$module_load){
						$module_load =$_REQUEST['module'];
						}
			$fields =array(''=>'none');

			if( $module_load->source_module && $module_load->source_module !='Home'){
			$module_fields = outright_retrieve( $module_load->source_module ,false);
									foreach( $module_fields->field_defs as $name => $arr ){
										if(isset($arr['vname']) && $arr['vname'] != ''){
														$fields[$name] = rtrim(translate($arr['vname'],$mod->module_dir), ':');
														}
												 else {
														  $fields[$name] = $name;
										}				
									}
			}

			return $fields;
}
//----------returns field name and field value using field label
 function outright_return_field_name_and_value($mod_bean, $fld_label, $return_value =false ){
		global $app_list_strings;
		$fields = array();		
		$fld_label = trim($fld_label);
				foreach($mod_bean->field_defs as $name => $arr){
				$crm_label =  rtrim(translate($arr['vname'],$mod_bean->module_dir), ':');						
								  if(strtolower($fld_label) ==strtolower($arr['name'])) {
									   $val = $mod_bean->$fld_label;
										$name =$arr['name'];
										break;
									}
									else if(isset($arr['vname']) && $arr['vname'] != '' && strtolower($fld_label) ==strtolower($crm_label)){
									$name =$arr['name'];
									 $val = $mod_bean->$name;
									break;
									}                
				}				
				if(  $return_value ){
					return $val;
				}
				 return $name;
  }


function outright_create_link($record_id,$record_module,$record_name = false){
	if($record_name){
		$created_link = '<a target="_blank" href="'.$GLOBALS['sugar_config']['site_url'].'/index.php?module='.$record_module.'&action=DetailView&record='.$record_id.'">'.$record_name.'</a>';
	}else{
		$created_link = '<a target="_blank" href="'.$GLOBALS['sugar_config']['site_url'].'/index.php?module='.$record_module.'&action=DetailView&record='.$record_id.'">View Record</a>';
	}
	return $created_link;
}


function outright_get_email_records( $email_address ){
	echo $sql ="SELECT bean_id,bean_module  FROM email_addr_bean_rel as er inner join email_addresses as e on er.email_address_id=e.id where e.email_address='".$email_address ."' and e.deleted =0 and er.deleted =0 ";		
	$customer_results = outright_run_sql($sql);

	$contact = false;
	$return_array=array();
	
	 foreach( $customer_results as $key=>$customer_result){
		 $bean_table = strtolower( $customer_result['bean_module'] );
		 $sql ='select id from '.$bean_table.' where deleted =0 and id="'.$customer_result['bean_id'].'"';
		 $result = outright_run_sql_one_row( $sql );
		 if($result){
				$return_array[$customer_result['bean_module']][]=$customer_result['bean_id'];
				$return_array['all'][] =$customer_result['bean_id'];
		 }
	 }
	 return $return_array;
}

function outright_clean_string($string) {
	return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}


	function outright_add_cron($function_name, $cron_name){
		$cronBean = BeanFactory::newBean( 'Schedulers' );
		$cronBean->retrieve_by_string_fields( array('job'=>'function::'.$function_name) );
		if( !$cronBean->id ){
			$cronBean = BeanFactory::newBean('Schedulers');
			$cronBean->name = $cron_name;
			$cronBean->status = "Active";
			$cronBean->job = "function::".$function_name;
			$cronBean->job_interval = "*::*::*::*::*";
			$cronBean->save();
		}

	}

	function outright_remove_cron($function_name){
		$cronBean = BeanFactory::newBean( 'Schedulers' );
		$cronBean->retrieve_by_string_fields( array('job'=>'function::'.$function_name) );
		if( $cronBean->id ){
			$cronBean->mark_deleted( $cronBean->id);
			$cronBean->save();
		}

	}

function outright_return_fields_by_type($module_name, $type ){
	$return['none']='--None--';
    $record_bean = outright_retrieve( $module_name );
    foreach( $record_bean->field_defs as $key => $single_record){
        if($single_record['type']==$type){
            $return[$single_record['name']]=rtrim(translate($single_record['vname'],$record_bean->module_dir), ':');
        }
    }
    return $return;
}

function outright_return_vardefs($module_name, $type=false, $name=false ){
	if($name){
		$record_bean = outright_retrieve( $module_name );
		foreach( $record_bean->field_defs as $key => $single_record){
			if($single_record['name']==$name){
				$return[]=$single_record;
			}
		}
		return $return;
	}else{
		$record_bean = outright_retrieve( $module_name );
		foreach( $record_bean->field_defs as $key => $single_record){
			if($single_record['type']==$type){
				$return[]=$single_record;
			}
		}
		return $return;
	}

}


function outright_is_user_role_allowed( $rol_value, $user_id = false ){
    global $current_user;
    if( !$user_id ){
        $user_id = $current_user->id;
    }
    $roles_sql="SELECT * FROM acl_roles_users WHERE role_id='".$rol_value."' AND user_id='".$user_id."' AND deleted=0";
    $role_res =outright_run_sql($roles_sql);
    if( $role_res ){
        return true;
    }
    return false;
}

function outright_is_user_team_allowed( $team_id, $user_id = false ){
    global $current_user;
    if( !$user_id ){
        $user_id = $current_user->id;
    }  
    
    $team_groups_sql="SELECT * FROM securitygroups_users WHERE securitygroup_id='".$team_id."' AND user_id='".$user_id."' AND deleted=0";
    $role_res =outright_run_sql($team_groups_sql);
    if( $role_res ){
        return true;
    }
    return false;
}

function outright_cron_enabled_check(){
    $sql = 'SELECT * FROM job_queue WHERE deleted=0 and date(date_entered)=CURRENT_DATE()';
    $result = outright_run_sql($sql);
    if($result){
        return true;
    }
    return false;
}

function ouright_retrieve_list($module, $where=false, $order_by=false, $direction=false, $limit_from=false, $limit_to=false){
    $append_lst='';
    if(empty($order_by)){
        $append_lst.=' ORDER BY date_entered';	
    }else{
        $append_lst.=' ORDER BY '.$order_by;
    }
    if(empty($direction)){
        $append_lst .= ' DESC';
    }else{
        $append_lst .= ' '.$direction;
    }
    if(empty($limit_from) AND empty($limit_to)){
        $append_lst .= ' LIMIT 0,100';

    }else{
        $append_lst .= ' LIMIT '.$limit_from.','.$limit_to;
    }
	

    $module_name = strtolower($module);
    $check = 'SHOW TABLES LIKE "'.$module_name.'_cstm"';
    $checktbl = outright_run_sql_one_row($check);
    if($checktbl){
        $cond = ' WHERE m.deleted=0';
        if(array_key_exists('deleted', $where)){
            $cond = ' WHERE m.deleted='.$where['deleted'];
            unset($where['deleted']);
        }
        if($where){
            if(is_array($where)){
                foreach( $where as $key => $single_record ){
                    $cond .= " AND m.".$key."='".$single_record."'";
                }
            }else{
                $msg = 'Pass array in WHERE clause !';
                return $msg;
            }           
        }
        echo $sql ="SELECT * FROM ".$module_name." AS m INNER JOIN ".$module_name."_cstm AS ct ON m.id=ct.id_c".$cond.$append_lst;
        $result =outright_run_sql($sql);
        return $result;
    }else{
        $cond = ' WHERE deleted=0';
        if(array_key_exists('deleted', $where)){
            $cond = ' WHERE deleted='.$where['deleted'];
            unset($where['deleted']);
        }
        if($where){
            if(is_array($where)){
                foreach( $where as $key => $single_record ){
                    $cond .= " AND ".$key."='".$single_record."'";
                }
            }else{
                $msg = 'Pass array in WHERE clause !';
                return $msg;
            }           
        }
        echo $sql = 'SELECT * FROM '.$module_name.$cond.$append_lst;
        $result = outright_run_sql($sql);
        return $result;
    }
}

function outright_get_daily_report($module, $group_by='status'){
    $sql = 'SELECT '.$group_by.', count(id) as Count FROM '.strtolower($module).' WHERE deleted=0 GROUP BY '.$group_by;
    $result = outright_run_sql($sql);
    $tbl1 = outright_html_table_new($result);
    $sqll = 'SELECT * FROM '.strtolower($module).' WHERE deleted=0 AND date(date_entered)=CURDATE() LIMIT 50';
    $result1 = outright_run_sql($sqll);
    $tbl2 = outright_html_table_new($result1, $module);
    $ret = $tbl1.'<br><br>'.$tbl2;
    return $ret;
}