<?php
/****************************************
/*  Author  : Kvvaradha
/*  Module  : FA Customization
/*  E-mail  : admin@kvcodes.com
/*  Version : 1.0
/*  Http    : www.kvcodes.com
*****************************************/

//---------------------------------------------------------------------------------------

// Add, Edit, Delete, Get And Get Join 

//---------------------------------------------------------------------------------------
if(!function_exists('FA_Insert')) {
function FA_Insert($table_name, $data, $default_company=null, $show_sql=false){
    if($default_company != null && $default_company != "0_" && is_string($default_company))
        $sql0 = "INSERT INTO  ".$default_company.$table_name." (";
    else
        $sql0 = "INSERT INTO ".TB_PREF.$table_name."(";
    $sql1 = " VALUES (";
    foreach($data as $key=>$value){
        $sql0 .= "`".$key."`,";
        if(is_array($value)) { 
            if($value[1] == 'date')             
                $sql1 .=  db_escape(date2sql($value[0])).",";
            if($value[1] == 'float')
                $sql1 .= $value.",";
            if($value[1] == 'noesc')
                $sql1 .= "`".$key."` = '". $value[0]."',";
        }else 
            $sql1 .= db_escape($value).",";
    } 
    $sql0 = substr($sql0, 0, -1).")";
    $sql1 = substr($sql1, 0, -1).")";
   
    db_query($sql0.$sql1, "Could not insert data to table {$table_name}", $show_sql);
    return  db_insert_id();
}
}

if(!function_exists('FA_Update')) {
function FA_Update($table_name, $primary_key, $data, $default_company=null, $show_query=false){

    if(FA_db_Has_Data_on_Table($table_name, $primary_key, $default_company, $show_query)){
       if($default_company != null && $default_company != "0_" && is_string($default_company))
            $sql0 = "UPDATE ".$default_company.$table_name." SET";
        else
            $sql0 = "UPDATE ".TB_PREF.$table_name." SET ";
        foreach($data as $key=>$value){
            if(is_array($value)) { 
                if($value[1] == 'date')             
                    $sql0 .= "`".$key."` = ". db_escape(date2sql($value[0])).",";
                if($value[1] == 'float')
                    $sql0 .= "`".$key."` = ". $value.",";
                if($value[1] == 'noesc')
                    $sql0 .= "`".$key."` = '". $value[0]."',";
            }else {
                $sql0 .= "`".$key."` = ".db_escape($value).",";
            }
        }
        $sql0 = substr($sql0, 0, -1);
        $sql0 .= " where 1=1";
        foreach($primary_key as $key=>$value){
            if(is_array($value)) { 
                if(isset($value[2]))
                    $operator = $value[2];
                else
                    $operator = '=';

                if($value[1] == 'date')             
                    $sql0 .= " AND ".$key." ".$operator." ". db_escape(date2sql($value[0]));
                elseif($value[1] == 'float')
                    $sql0 .= " AND ".$key." ".$operator." ". $value;
                else
                    $sql0 .= " AND ".$key." ".$operator." ". db_escape($value[0]);
            }else{
                if(is_numeric($value)){
                    $sql0 .=" AND ". $key." = ".$value;
                }else
                   $sql0 .= " AND ".$key." = ".db_escape($value);
            }
        }
       return  db_query($sql0, "Could not update data on table {$table_name}", $show_query);
    }else{
        foreach($primary_key as $key => $value){
            if($key != 'id')
                $data[$key] = $value;
        }
         return FA_Insert($table_name, $data, $default_company, $show_query);
    }     
}
}
if(!function_exists('FA_db_Has_Data_on_Table')) {
    function FA_db_Has_Data_on_Table($table_name, $primary_key =false, $default_company = null, $show_query=false){    
       
       if($default_company != null && $default_company != "0_" && is_string($default_company))
            $sql = "SELECT COUNT(*) FROM ".$default_company.$table_name." WHERE 1=1";
        else
            $sql = "SELECT COUNT(*) FROM ".TB_PREF.$table_name." WHERE 1=1";
        if($primary_key){
            foreach($primary_key as $key=>$value){
                if(is_array($value)) { 
                    if($value[1] == 'date')             
                        $sql .= " AND ".$key." = ". db_escape(date2sql($value[0])).",";
                    if($value[1] == 'float')
                        $sql .= " AND ".$key." = ". $value.",";
                }else{
                    if(is_numeric($value)){
                        $sql .=" AND ". $key." = ".$value;
                    }else
                       $sql .= " AND ".$key." = ".db_escape($value);
                }
            }
        }
        return  fa_check_empty_result($sql, $show_query);
    }
}

function fa_check_empty_result($sql, $show_sql=false){
	$result = db_query($sql, "could not do check empty query", $show_sql);	
	
	$myrow = db_fetch_row($result);
	return is_array($myrow) ? $myrow[0] > 0 : false;
}
if(!function_exists('html_specials_encode')){
    function html_specials_encode($str)
    {
        return $value = @htmlspecialchars($str);
    }
}
if(!function_exists('db_escape')) {
    function db_escape($value = "", $nullify = false){
        global $db;
        if(is_float($value)){
            $value =round($value,8);
        }elseif(is_string($value)) 
            $value = trim($value);        

        $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
        $value = html_specials_encode($value);

        //reset default if second parameter is skipped
        $nullify = ($nullify === null) ? (false) : ($nullify);

        //check for null/unset/empty strings
        if ((!isset($value)) || (is_null($value)) || ($value === "")) {
            $value = ($nullify) ? ("NULL") : ("''");
        } else {
            if (is_string($value)) {
                $value = "'" . mysqli_real_escape_string($db, $value) . "'";
                //value is a string and should be quoted; 
            } else if (!is_numeric($value)) {
                //value is not a string nor numeric
                display_error("ERROR: incorrect data type send to sql query");
                echo '<br><br>';
                exit();
            }
        }
        if(strpos($value, '&quot;')){
           $value =str_replace("&quot;", '"', $value);
        }
        return $value;
    }
}

if(!function_exists('FA_GetDataJoinRow')) {
    function FA_GetDataJoinRow($main_table, $joins, $columns = array(), $conditions=null, $order_by= null, $group_by = null){
        return FA_GetDataJoin($main_table, $joins, $columns, $conditions, $order_by, $group_by, true);
    }
}

if(!function_exists('FA_Delete')) {
    function FA_Delete($table_name, $conditions, $default_company=null){
    
            $sql0 = "DELETE FROM ".TB_PREF.$table_name." WHERE 1=1";
        foreach ($conditions as $key=>$value) {
            $sql0 .= " AND ".$key."=".db_escape($value);
        }
        $result = db_query($sql0, "Could not delete data from {$table_name}");
        return $result;
    }
}

if(!function_exists('FA_GetQueryResult')){
    function FA_GetQueryResult($sql, $res=false){
        $result = db_query($sql, "Can't get results");
        if(db_num_rows($result) > 0 ){
            if($res == 's'){
                $row = db_fetch($result);
                return $row[0];
            } elseif($res == 'r'){
                return db_fetch($result);
            }   else{
                $final = array();
                while($row = db_fetch($result))
                    $final[] = $row;
                return $final;
            }
        } else
            return false;
    }
}
if(!function_exists('FA_GetDataJoin')) {
    function FA_GetDataJoin($main_table, $joins, $columns=array(), $conditions=null, $order_by = null, $group_by = null, $single=false, $sql=false, $default_company=null,$limit=null){
        $sql0 = "SELECT ";
       
            $tbpref = TB_PREF;

        if(count($columns)>0){
            foreach ($columns as $value) {
                $sql0 .= $value.",";
            }
            $sql0 = substr($sql0, 0, -1);
        }else{
            $sql0 .= " *";
        }
        $sql0 .= " FROM ".$tbpref."{$main_table} ";
        foreach ($joins as $value) {
            if(isset($value['join'])){
                $sql0 .= " {$value['join']} JOIN ".$tbpref.$value['table_name'].' ON '.$value['conditions'];
            }else{
                $sql0 .= " INNER JOIN ".$tbpref.$value['table_name'].' ON '.$value['conditions'];
            }
        }
        $sql0 .= " WHERE 1=1 ";
        if(is_array($conditions)) {
            foreach($conditions as $key=>$value){
                if(is_array($value)) { 
                    if(isset($value[2]))
                        $operator = $value[2];
                    else
                        $operator = '=';

                    if(isset($value[3]))
                        $condition_operator = $value[3];
                    else
                        $condition_operator = 'AND';

                    if($value[1] == 'date')             
                        $sql0 .=" ".$condition_operator." ".$key." ".$operator." ". db_escape(date2sql($value[0]));
                    elseif($value[1] == 'float')
                        $sql0 .=" ".$condition_operator." ".$key." ".$operator." ". $value[0];
                    else
                        $sql0 .=" ".$condition_operator." ".$key." ".$operator." ". db_escape($value[0]);
                }else
                    $sql0 .= " AND {$key} = ".db_escape($value);
            }
        }elseif($conditions !=null && $conditions){
            $sql0 .=" AND ".$conditions;
        }

        if($group_by != null) {
                $sql0 .=" GROUP BY ";
                foreach($group_by as $value){
                    $sql0 .= " ${value}";
                }
        }

        if($order_by != null) {
            $sql0 .=" ORDER BY ";
            foreach($order_by as $key=>$value){
                $sql0 .= " {$key} ${value}";
            }
        }
        if($single)
            $sql0 .= ' LIMIT 1'; 
        elseif($limit !=null)
            $sql0 .= ' LIMIT '.$limit; 

        if($sql)
            return $sql0;
        $result = db_query($sql0, "Could not get data!");
        $data = array();
        if(db_num_rows($result) > 0 ) {
            while($row = db_fetch($result)) {
                $data[] = $row;
            }
            if($single){               
                return $data[0];
            }
            else
                return $data;
        } else 
            return false;
    }
}

if(!function_exists('FA_GetAll')) {
    function FA_GetAll($table_name, $conditions = null, $order_by = null, $group_by = null, $default_company=null, $show_query=false, $return_sql=false,$limit=null){
       
        $sql0 = "SELECT * FROM ".TB_PREF.$table_name." WHERE 1=1";
        if(is_array($conditions)) {
            foreach($conditions as $key=>$value){
                if($key == '')
                    $sql0 .= " AND ".$value." ";
                    
                elseif(is_array($value)) { 
                    if(isset($value[2]))
                        $operator = $value[2];
                    else
                        $operator = '=';

                    if($value[1] == 'date')             
                        $sql0 .= " AND ".$key." ".$operator." ". db_escape(date2sql($value[0]));
                    elseif($value[1] == 'float')
                        $sql0 .= " AND ".$key." ".$operator." ". $value;
                    else
                        $sql0 .= " AND ".$key." ".$operator." ". db_escape($value[0]);
                }else
                 $sql0 .= " AND {$key} = ".db_escape($value);
            }
        }elseif($conditions !=null && $conditions){
            $sql0 .=" AND ".$conditions;
        }
       
        if($group_by != null) {
            $sql0 .=" GROUP BY ";
            foreach($group_by as $value){
                $sql0 .= " ${value}";
            }
        }
        if($order_by != null) {
            $sql0 .=" ORDER BY ";
            foreach($order_by as $key=>$value){
                $sql0 .= " {$key} ${value}";
            }
        }

        if($limit !=null){
            $sql0 .=' LIMIT '.$limit;
        }
        if($return_sql)
            return $sql0;
        $result = db_query($sql0, "Could not get data from {$table_name}", $show_query);
        $data = array();
        while($row = db_fetch_assoc($result)) {
            $data[] = $row;
        }
        return $data;
    }
}

if(!function_exists('FA_GetRow')) {
    function FA_GetRow($table_name, $conditions = null, $order_by = null,  $group_by= null,  $default_company=null,$show_sql=false){
      
            $sql0 = "SELECT * FROM ".TB_PREF.$table_name." WHERE 1=1";
        if(is_array($conditions)) {
            if($conditions != null) {
                foreach($conditions as $key=>$value){
                    if(is_array($value)) { 
                        $sql0 .= " AND ".$key." ".$value[1]." ". db_escape($value[0]);
                    } else
                        $sql0 .= " AND {$key} = '${value}'";
                }
            }
        }elseif($conditions !=null && $conditions){
            $sql0 .=" AND ".$conditions;
        }

        if($group_by != null) {
                $sql0 .=" GROUP BY ";
                foreach($group_by as $value){
                    $sql0 .= " ${value}";
                }
        }

        if($order_by != null) {
            $sql0 .=" ORDER BY ";
            foreach($order_by as $key=>$value){
                $sql0 .= " {$key} ${value}";
            }
        }
        
        $sql0 .= ' LIMIT 1'; 
        $result = db_query($sql0, "Could not get data from {$sql0}",$show_sql);
        $data = db_fetch($result);
        
        return $data;
    }
}

if(!function_exists('FA_GetDataFilter')) { 
    function FA_GetDataFilter($table_name, $columns= array(), $conditions=null, $order_by = null, $group_by= null, $default_company=null,$sql=false){
        $sql0 = "SELECT ";
        if(count($columns)>0){
            foreach ($columns as $value) {
                $sql0 .= $value.",";
            }
        }else{
            $sql0 .= " * ";
        }
        $sql0 = substr($sql0, 0, -1);
       
        $sql0 .= " FROM ".TB_PREF.$table_name." WHERE 1=1";
         if(is_array($conditions)){
            foreach($conditions as $key=>$value){
                if(is_array($value)) { 
                    if(isset($value[2]))
                        $operator = $value[2];
                    else
                        $operator = '=';

                    if(isset($value[3]))
                        $condition_operator = $value[3];
                    else
                        $condition_operator = 'AND';

                    if($value[1] == 'date')             
                        $sql0 .=" ".$condition_operator." ".$key." ".$operator." ". db_escape(date2sql($value[0]));
                    elseif($value[1] == 'float')
                        $sql0 .=" ".$condition_operator." ".$key." ".$operator." ". $value[0];
                    else
                        $sql0 .=" ".$condition_operator." ".$key." ".$operator." ". db_escape($value[0]);
                } else 
                    $sql0 .= " AND {$key} =".db_escape($value);
            }
        }elseif($conditions !=null && $conditions){
            $sql0 .=" AND ".$conditions;
        }

        if($group_by != null) {
                $sql0 .=" GROUP BY ";
                foreach($group_by as $value){
                    $sql0 .= " ${value}";
                }
        }
        if($order_by != null) {
            $sql0 .=" ORDER BY ";
            foreach($order_by as $key=>$value){
                $sql0 .= " {$key} ${value}";
            }
        }
        if($sql){
            return $sql0;
        }
        $result = db_query($sql0, "Could not get data from {$table_name}");
        $data = array();
        while($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        return $data;
    }
}

if(!function_exists('FA_GetSingleValue')) {
    function FA_GetSingleValue($tablename, $column_single, $conditions=null, $order_by = null, $group_by= null, $default_company=null, $show_sql=false){
        $sql0 = "SELECT ".$column_single." FROM ".TB_PREF.$tablename." WHERE 1=1";
        if(is_array($conditions) && !empty($conditions)){
            foreach($conditions as $key=>$value){
                if(is_array($value)) { 
                    if(isset($value[2]))
                        $operator = $value[2];
                    else
                        $operator = '=';

                    if($value[1] == 'date')             
                        $sql0 .= " AND ".$key." ".$operator." ". db_escape(date2sql($value[0]));
                    elseif($value[1] == 'float')
                        $sql0 .= " AND ".$key." ".$operator." ". $value;
                    else
                        $sql0 .= " AND ".$key." ".$operator." ". db_escape($value[0]);
                }else
                    $sql0 .= " AND {$key} =".db_escape($value);
            }
        }elseif($conditions !=null && $conditions){
            $sql0 .=" AND ".$conditions;
        }
        
        if($group_by != null) {
                $sql0 .=" GROUP BY ";
                foreach($group_by as $value){
                    $sql0 .= " ${value}";
                }
            }

        if($order_by != null) {
            $sql0 .=" ORDER BY ";
            foreach($order_by as $key=>$value){
                $sql0 .= " {$key} ${value}";
            }
        }
        if($show_sql)
           return $sql0;

        $result = db_query($sql0, "could not get data form ".$tablename);
        $row = db_fetch_row($result);
        
            $data =(isset($row[0]) ? @unserialize(base64_decode($row[0])) : false );
        if ($data !== false) {
            return unserialize(base64_decode($row[0]));
        }else
            return isset($row[0]) ? $row[0] : null;
    }
}

?>
