<?php
/*
JOHNN GUTIERREZ, 
FECHA DE CREACION   2020-12-26
ULTIMA MODIFICASION 2021-03-22
ULTIMA MODIFICASION 2022-09-01
*/
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

class Reposit_Functions
{

    protected function Div_result_Decimal($pNumber)
    {
        $whole = floor($pNumber); // 1
        $fraction = $pNumber - $whole; // .25
        return $fraction;
    }

    protected function check_field_type($pConn, $schemaName, $TableName, $FieldName)
    {
        try {
            $Sql_Line = "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = '" . $schemaName . "' AND TABLE_NAME = '" . $TableName . "' AND COLUMN_NAME = '" . $FieldName . "'";
            $data_flds = $pConn->query($Sql_Line)->fetchArray();
            $value = $data_flds['DATA_TYPE'];
            $data_flds = null;
            return $value;
        } catch (PDOException $e) {
            print $e->getMessage();
        }
    }

    public function jsonmysql_insert_result_str_v2($pjson_str, $tabl_name, $connection1, $database, $database_dest, $Excl_Field, $On_Dlupl, $Execute, $max_lines_block, $chech_decimals)
    {
        $bresult = false;
        if (($Excl_Field == '0') or ($Excl_Field == '') or ($Excl_Field == 'NULL') or ($Excl_Field == 'null')) {
            $Excl_Field = '-NONE-';
        }

        if (($On_Dlupl == '0') or ($On_Dlupl == '') or ($On_Dlupl == 'NULL') or ($On_Dlupl == 'null')) {
            $On_Dlupl = '-NONE-';
        }

        $Excl_Key = '';
        if (strtoupper($tabl_name) == strtoupper('operacion')) {
            $Excl_Key = 'id_op';
        }

        if (($Execute == '') or ($Execute == 'NULL') or ($Execute == 'null')) {
            $Execute = 0;
        }

        if (($chech_decimals == '') or ($chech_decimals == 'NULL') or ($chech_decimals == 'null')) {
            $chech_decimals = 0;
        }
        //$max_lines_block = ($max_lines_block - 1);
        $ib = 0;
        $Sql_Insert_Res = '';
        //$json_Obj = json_decode($pjson_str, TRUE);
        $json_Obj = $pjson_str;
        //$tabla = $json_Obj[$tabl_name];
        $tabla = $json_Obj;

        $reg_p = count($tabla);
        $FldOk = 0;
        $cadena3 = '';
        while ($ib < $reg_p) {
            $opfinal = $tabla[$ib];
            $cadena = '';
            $cadena2 = '';
            $i = 0;
            $valuekey = '';
            $fieldkey = '';
            foreach ($opfinal as $field => $value) {
                #--------------VERIFICA Y AUTOREPARA TIPOS NUMERICOS QUE VIENEN CON COMA------------------
                $cJonFieldType = $this->check_field_type($connection1, $database, $tabl_name, $field);
                switch (trim($cJonFieldType)) {
                    case 'varchar': {
                            if (($value == 'null') or ($value == 'NULL'))
                                $value = '';
                            break;
                        }
                    case 'datetime': {
                            if (($value == '') or ($value == '0000-00-00 00:00:00'))
                                $value = '2000-01-01 01:00:00';
                            break;
                        }
                    case 'date': {
                            if (($value == '') or ($value == '0000-00-00'))
                                $value = '2000-01-01';
                            break;
                        }
                    case 'int': {
                            if (($value == '') or ($value == 'null') or ($value == 'NULL'))
                                $value = '0';
                            break;
                        }
                    case 'decimal': {
                            if (($value == '') or ($value == 'null') or ($value == 'NULL'))
                                $value = '0.00';
                            if ($chech_decimals == 1) {
                                $value = str_replace(",", ".", $value);
                            }
                            break;
                        }
                    case 'double': {
                            if (($value == '') or ($value == 'null') or ($value == 'NULL'))
                                $value = '0.00';
                            if ($chech_decimals == 1) {
                                $value = str_replace(",", ".", $value);
                            }
                            break;
                        }
                    case 'tinyint': {
                            if (($value == '') or ($value == 'null') or ($value == 'NULL'))
                                $value = '0';
                            break;
                        }
                }
                #------------------------------------------------------------------------------------------

                if ($field != $Excl_Field) {
                    $fieldkey = $field;
                    $valuekey = $value;
                    if ($i > 0) {
                        $field = ',' . $field;
                        $fieldkey = ',' . $fieldkey;

                        if (($value != 0) and ($value != '') and $value == null) {
                            $value = ',null';
                            $valuekey = 'null';
                        } else {
                            $value = ',"' . $value . '"';
                            $valuekey = '"' . $valuekey . '"';
                        }
                    } else {
                        $value = '"' . $value . '"';
                    }

                    if ($FldOk == 0) {
                        if ($On_Dlupl != '-NONE-') {
                            if ($fieldkey != $Excl_Key) {
                                $cadena3 = $cadena3 . $fieldkey . '=VALUES(' . str_replace(',', '', $fieldkey) . ') ';
                            }
                        }
                    }

                    $cadena = $cadena . $field;
                    $cadena2 = $cadena2 . $value;
                    $i = $i + 1;
                }
            }
            $FldOk = 1;
            if ($ib == 0) {
                $sql = "INSERT INTO " . $database_dest . "." . $tabl_name . " (" . $cadena . ") VALUES " . CHR(13);
            } else {
                $sql = "";
            }

            $sql = $sql . " (" . $cadena2 . ") ";
            $Frac = $this->Div_result_Decimal($ib / $max_lines_block);
            //echo "COUNTER:[" . $ib . "]  MAXIMUS:[" . $max_lines_block . "] FRAC:[" . $Frac . "]" . CHR(13);
            if (($ib >= $max_lines_block) && ($Frac == 0)) {
                if ($On_Dlupl != '-NONE-') {
                    if (trim($cadena3) != '') {
                        $sql = $sql . CHR(13) . " ON DUPLICATE KEY UPDATE " . $cadena3 . ";" . CHR(13);
                    }
                } else {
                    $sql = $sql . ";" . CHR(13);
                }
                $sql = $sql  . "INSERT INTO " . $database_dest . "." . $tabl_name . " (" . $cadena . ") VALUES ";
            } else {
                $sql = $sql . ",";
            }

            $Sql_Insert_Res = $Sql_Insert_Res . $sql . CHR(13);
            $Sql_Insert_Res = str_replace("0000-00-00", "2009-01-01", $Sql_Insert_Res);
            $Sql_Insert_Res = str_replace("0000-00-00 00:00:00", "2009-01-01 01:01:01", $Sql_Insert_Res);
            $Sql_Insert_Res = str_replace("UPDATE ,", "UPDATE ", $Sql_Insert_Res);

            $ib++;
        }

        if ($On_Dlupl != '-NONE-') {
            $Frac = $this->Div_result_Decimal($ib / $max_lines_block);
            if ($Frac != 0) {
                if (trim($cadena3) != '') {

                    $Sql_Insert_Res = substr($Sql_Insert_Res, 0, strlen($Sql_Insert_Res) - 2) . CHR(13);
                    $Sql_Insert_Res = $Sql_Insert_Res . " ON DUPLICATE KEY UPDATE " . $cadena3 . ";";
                }
            }
        } else {
            $Sql_Insert_Res = substr(trim($Sql_Insert_Res), 0, strlen($Sql_Insert_Res) - 2);
            if (trim($Sql_Insert_Res) != '') {
                $Sql_Insert_Res = trim($Sql_Insert_Res) . ";";
            }
        }
        return $Sql_Insert_Res;
    }

    // FECHA CREACION: JOHNN GUTIERREZ 2017-10-06
    // ULTIMA MODIFICACION: JOHNN GUTIERREZ 2017-10-07
    public function jsonmysql($poConn3, $cpDatab3, $JsonStr3, $TblName, $pcSaveLog3)
    {
        if ($pcSaveLog3 == 1) {
            echo '*-------------------------->jsonmysql--------------------------*' . chr(13);
            echo '--->Database :' . $cpDatab3 . chr(13);
            echo '--->Jason :' . $JsonStr3 . chr(13);
            echo '--->Table :' . $TblName . chr(13);
            echo '*--------------------------------------------------------------*' . chr(13);
        }

        $data_arr = json_decode(utf8_encode($JsonStr3), TRUE);
        $xTable = $data_arr[$TblName];
        $regs_cnt = $data_arr['regs_po'];

        if ($pcSaveLog3 == 1) {
            echo 'REGISTROS: ' . $regs_cnt . chr(13);
        }

        // echo 'son '.$regs."de la tabla".$TblName."<br>";
        $ib = 0;

        while ($ib < $regs_cnt) {
            /*
         * el valor presentado sería
         * $i antes del incremento
         * (post-incremento)
         */

            // echo 'vuelta nro: '.$ib;

            $opfinal = $xTable[$ib];

            $str_fields = '';
            $str_values = '';
            $str_update = '';
            $i = 0;
            $valuekey = '';
            $fieldkey = '';
            foreach ($opfinal as $field => $value) {

                $fieldkey = $field;
                $valuekey = $value;
                // if($i<9999) {
                if ($i > 0) {
                    $field = ',' . $field;
                    $fieldkey = ',' . $fieldkey;

                    if ($value == '') {
                        $value = $value . ',null';
                        $valuekey = 'null';
                    } else {
                        $value = ',"' . $value . '"';
                        $valuekey = '"' . $valuekey . '"';
                    }

                    // $field=','.$field.$i;
                    // $value=',"'.$value.$i.'"';
                } else {
                    $value = '"' . $value . '"';
                }

                // $str_update = $str_update . $fieldkey . '=' . $valuekey;
                // if ($ib == 0) {
                $str_update = $str_update . $fieldkey . '=VALUES(' . str_replace(',', '', $fieldkey) . ') ';
                // }
                $str_fields = $str_fields . $field;
                $str_values = $str_values . $value;
                $i = $i + 1;

                // }
            }

            // echo $str_update;

            $sql = "INSERT INTO " . $cpDatab3 . "." . $TblName . " (" . $str_fields . ") VALUES (" . $str_values . ") ON DUPLICATE KEY UPDATE " . $str_update . "";

            // echo $sql;
            $sql = str_replace("0000-00-00 00:00:00", "2009-01-01 01:01:01", $sql);
            $iAffected_rows = 0;
            $result = $poConn3->query($sql);
            $iAffected_rows = $poConn3->affectedRows();

            if ($pcSaveLog3 == 1) {
                echo 'SQL : ' . $sql . chr(13);
                echo 'RES: ' . ($result ? 'true' : 'false') . chr(13);
            }

            $ib++;

            // echo "inserta: ".$sql;
        }

        if ($pcSaveLog3 == 1) {
            echo '*FIN------------------------jsonmysql<-------------------------*' . chr(13);
        }
        return $result;
    }

    public function __construct()
    {
        //sets up connection here 
    }
}

class Utiles
{

    protected $connection;
    protected $query;
    protected $show_errors = TRUE;
    protected $query_closed = TRUE;
    public $query_count = 0;
    public $timestamp;

    public function __construct($dbname = '', $dbhost = '', $dbuser = '', $dbpass = '', $charset = '')
    {
        include 'conn_param.php';

        if ($dbhost == '')
            $dbhost = $Srv_Info['hostname'];
        if ($dbuser == '')
            $dbuser = $Srv_Info['username'];
        if ($dbpass == '')
            $dbpass = $Srv_Info['password'];
        if ($dbname == '')
            $dbname = $Srv_Info['dbname'];
        if ($charset == '')
            $charset = $Srv_Info['charset'];

        $this->connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        if ($this->connection->connect_error) {
            $this->error('Error al tratar de conectarse a MySQL - ' . $this->connection->connect_error);
        }
        $this->connection->set_charset($charset);

        // to get time-stamp for 'created' field
        $this->timestamp = date('Y-m-d H:i:s');
    }

    public function query($query)
    {
        if (!$this->query_closed) {
            $this->query->close();
        }
        if ($this->query = $this->connection->prepare($query)) {
            if (func_num_args() > 1) {
                $x = func_get_args();
                $args = array_slice($x, 1);
                $types = '';
                $args_ref = array();
                foreach ($args as $k => &$arg) {
                    if (is_array($args[$k])) {
                        foreach ($args[$k] as $j => &$a) {
                            $types .= $this->_gettype($args[$k][$j]);
                            $args_ref[] = &$a;
                        }
                    } else {
                        $types .= $this->_gettype($args[$k]);
                        $args_ref[] = &$arg;
                    }
                }
                array_unshift($args_ref, $types);
                call_user_func_array(array($this->query, 'bind_param'), $args_ref);
            }
            $this->query->execute();
            if ($this->query->errno) {
                $this->error('No es posible procesar MySQL query (Verifique sus parámetros) - ' . $this->query->error . ' ' . $query);
            }
            $this->query_closed = FALSE;
            $this->query_count++;
        } else {
            $this->error('No es posible preparar MySQL statement (Verifique sus sintaxis) - ' . $this->connection->error . ' ' . $query);
        }
        return $this;
    }

    public function fetchAll($callback = null)
    {
        $params = array();
        $row = array();
        $meta = $this->query->result_metadata();
        while ($field = $meta->fetch_field()) {
            $params[] = &$row[$field->name];
        }
        call_user_func_array(array($this->query, 'bind_result'), $params);
        $result = array();
        while ($this->query->fetch()) {
            $r = array();
            foreach ($row as $key => $val) {
                $r[$key] = $val;
            }
            if ($callback != null && is_callable($callback)) {
                $value = call_user_func($callback, $r);
                if ($value == 'break') break;
            } else {
                $result[] = $r;
            }
        }
        $this->query->close();
        $this->query_closed = TRUE;
        return $result;
    }

    public function fetchArray()
    {
        $params = array();
        $row = array();
        $meta = $this->query->result_metadata();
        while ($field = $meta->fetch_field()) {
            $params[] = &$row[$field->name];
        }
        call_user_func_array(array($this->query, 'bind_result'), $params);
        $result = array();
        while ($this->query->fetch()) {
            foreach ($row as $key => $val) {
                $result[$key] = $val;
            }
        }
        $this->query->close();
        $this->query_closed = TRUE;
        return $result;
    }

    public function close()
    {
        return $this->connection->close();
    }

    public function numRows()
    {
        $this->query->store_result();
        return $this->query->num_rows;
    }

    public function affectedRows()
    {
        return $this->query->affected_rows;
    }

    public function lastInsertID()
    {
        return $this->connection->insert_id;
    }

    public function error($error)
    {
        if ($this->show_errors) {
            exit($error);
        }
    }

    protected function setError($error)
    {
        array_push($this->error, $error);
    }

    protected function CheckConnection()
    {
        if (!$this->connection) {
            $e              = 'DB connection failed';
            $this->setError($e);
            echo "Your exception handling" . $e;
            return false;
        }
        return true;
    }

    public function Value($val)
    {
        return trim($val);
    }

    public function noHTMLnoQuotes($string)
    {
        return htmlentities($this->Value($string), ENT_NOQUOTES);
    }

    public function noHTMLquotes($string)
    {
        return htmlentities($this->Value($string), ENT_QUOTES);
    }

    public function firstUpperCase($string)
    {
        return ucfirst(strtolower($this->Value($string)));
    }

    public function allLowerCase($string)
    {
        return strtolower($this->Value($string));
    }

    public function urlEncode($string)
    {
        return urlencode($this->Value($string));
    }

    public function urlDecode($string)
    {
        return urldecode($this->Value($string));
    }

    public function slash($string)
    {
        return addslashes($string);
    }

    public function noSlash($string)
    {
        return stripslashes($string);
    }

    public function sql_clean($val)
    {
        if (is_numeric($val)) {
            return $val;
        }
        return "'" . mysqli_real_escape_string($this->connection, htmlspecialchars($this->Value($val))) . "'";
    }

    private function _gettype($var)
    {
        if (is_string($var)) return 's';
        if (is_float($var)) return 'd';
        if (is_int($var)) return 'i';
        return 'b';
    }

    public function tableExists($table)
    {
        $db_name2 = $this->get_database();
        $tablesInDb = $this->query('SHOW TABLES FROM "' . TRIM($db_name2)  . '" LIKE "' . $table . '"');
        if ($tablesInDb) {
            if ($this->numRows() == 1) {
                return true;
            } else {
                return false;
            }
        }
    }

    public function FieldExists($tableName, $FieldName)
    {
        $db_name2 = $this->get_database();
        $tablesInDb = $this->query('SELECT TABLE_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = "' . TRIM($db_name2) . '" AND TABLE_NAME = "' . trim($tableName) . '" AND COLUMN_NAME = "' . trim($FieldName) . '"');
        if ($tablesInDb) {
            if ($this->numRows() > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    public function get_database()
    {
        if ($result = mysqli_query($this->connection, "SELECT DATABASE()")) {
            $row = mysqli_fetch_row($result);
            return $row[0];
            mysqli_free_result($result);
        }
    }

    public function delete($table, $where = null)
    {
        if ($this->tableExists($table)) {
            if ($where == null) {
                $delete = 'DELETE ' . $table;
            } else {
                $delete = 'DELETE FROM ' . $table . ' WHERE ' . $where;
            }
            $del = $this->query($delete);

            if ($del) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function insert($table, $values, $rows = null)
    {
        if ($this->tableExists($table)) {
            $insert = 'INSERT INTO ' . $table;
            if ($rows != null) {
                $insert .= ' (' . $rows . ')';
            }

            for (
                $i = 0;
                $i < count($values);
                $i++
            ) {
                if (is_string($values[$i]))
                    $values[$i] = '"' . $values[$i] . '"';
            }
            $values = implode(',', $values);
            $insert .= ' VALUES (' . $values . ')';
            $ins = $this->query($insert);
            if ($ins) {
                return true;
            } else {
                return false;
            }
        }
    }

    public function update($table, $rows, $where)
    {
        if ($this->tableExists($table)) {
            // Parse the where values
            // even values (including 0) contain the where rows
            // odd values contain the clauses for the row
            for (
                $i = 0;
                $i < count($where);
                $i++
            ) {
                if ($i % 2 != 0) {
                    if (is_string($where[$i])) {
                        if (($i + 1) != null)
                            $where[$i] = '"' . $where[$i] . '" AND ';
                        else
                            $where[$i] = '"' . $where[$i] . '"';
                    }
                }
            }
            $where = implode('=', $where);


            $update = 'UPDATE ' . $table . ' SET ';
            $keys = array_keys($rows);
            for (
                $i = 0;
                $i < count($rows);
                $i++
            ) {
                if (is_string($rows[$keys[$i]])) {
                    $update .= $keys[$i] . '="' . $rows[$keys[$i]] . '"';
                } else {
                    $update .= $keys[$i] . '=' . $rows[$keys[$i]];
                }

                // Parse to add commas
                if ($i != count($rows) - 1) {
                    $update .= ',';
                }
            }
            $update .= ' WHERE ' . $where;
            $query = $this->query($update);
            if ($query) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /*
    // Perform an INSERT query
    //------------------EJEMPLO DE LA IMPLEMENTACION----------------------
    //$sql = "INSERT INTO things (name, color) VALUES (:name, :color)";
    //$params = array("name" => "Hat", "color" => "Purple");
    //--------------------------------------------------------------------
    public function sql_execute($sql, $data = array())
    {
        try {
            // Prepare the SQL statement

            $stmt = mysqli_prepare($this->connection, $sql);
            $types = str_repeat('s', count($data)); //types
            mysqli_stmt_bind_param($stmt, $types ,$stmt, ...$data);
            $result = mysqli_stmt_execute($stmt);
            /* 
            $stmt = $this->connection->prepare($sql);
            // Execute the statement
            if ($stmt->execute($data)) {
            
            if ( $result){ 
            // Return the number of rows affected
                echo 'true'; 
                return true; //$stmt->affected_rows;
            } else {
                echo 'false'; 
                return false;
            }
        } catch (Exception $e) {
            echo $e->error; 
            return false;
        }
    }
 
    //------------------EJEMPLO DE LA IMPLEMENTACION----------------------
    //$cmd_ln = 'INSERT INTO `' . $pDdm_Name . '`.`http_json` (`json_str`) VALUES (?);';
    //execute_cmd_par($conn, $pDdm_Name, $cmd_ln, $pJsonStrn);   
    //--------------------------------------------------------------------
  /*  function execute_cmd_par($pSql_Cmd,$pSql_par)
    {
    $db_name2 = $this->get_database();
    //mysqli_select_db($this->connection, $db_name2);
    try {
        $stmt = mysqli_prepare($this->connection, $pSql_Cmd);
        //mysqli_stmt_bind_param($stmt, 's', $pSql_par);
        $result = mysqli_stmt_execute($stmt);
        return $result;
    } catch (Error $e) {
        $trace = $e->getTrace();
        echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . ' called from ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'];
        return -1;
    }
    }
*/
    public function select($table, $rows = '*', $where = null, $order = null)
    {
        $q = 'SELECT ' . $rows . ' FROM ' . $table;
        if ($where != null)
            $q .= ' WHERE ' . $where;
        if ($order != null)
            $q .= ' ORDER BY ' . $order;
        if ($this->tableExists($table)) {
            $query = $this->query($q);
            if ($query) {
                $this->numResults = $query->numRows();
                for (
                    $i = 0;
                    $i < $this->numResults;
                    $i++
                ) {
                    $r = $this->fetchArray($query);
                    $key = array_keys($r);
                    for (
                        $x = 0;
                        $x < count($key);
                        $x++
                    ) {
                        // Sanitizes keys so only alphavalues are allowed
                        if (!is_int($key[$x])) {
                            if ($this->numRows() > 1)
                                $this->result[$i][$key[$x]] = $r[$key[$x]];
                            else if ($this->numRows() < 1)
                                $this->result = null;
                            else
                                $this->result[$key[$x]] = $r[$key[$x]];
                        }
                    }
                }
                return true;
            } else {
                return false;
            }
        } else
            return false;
    }


    public static function Doit_Sql_cxc_v2($poConn, $cDb_Nam, $cDb_NamD, $cValidOp, $cSuc_id, $cCte_id, $cDropTb, $cCreaTb, $cDelReg, $cDupReg, $SaveLog, $Repl_Bl, $Include_Ctes)
    {
        if (($cCte_id == '') or ($cCte_id == 'NULL') or ($cCte_id == 'null') or ($cCte_id == '0')) {
            $cCte_id = '00000000000000000000';
        }

        if (($cDropTb == '') or ($cDropTb == 'NULL') or ($cDropTb == 'null')) {
            $cDropTb = '0';
        }

        if (($cCreaTb == '') or ($cCreaTb == 'NULL') or ($cCreaTb == 'null')) {
            $cCreaTb = '0';
        }

        if (($cDelReg == '') or ($cDelReg == 'NULL') or ($cDelReg == 'null')) {
            $cDelReg = '0';
        }

        if (($cDupReg == '') or ($cDupReg == 'NULL') or ($cDupReg == 'null')) {
            $cDupReg = '';
        }

        if (($SaveLog == '') or ($SaveLog == 'NULL') or ($SaveLog == 'null')) {
            $SaveLog = '0';
        }

        if (($Repl_Bl == '') or ($Repl_Bl == 'NULL') or ($Repl_Bl == 'null')) {
            $Repl_Bl = '0';
        }

        if (($Include_Ctes == '') or ($Include_Ctes == 'NULL') or ($Include_Ctes == 'null')) {
            $Include_Ctes = '0';
        }

        $str_sql = "USE `$cDb_Nam`;";
        $oRep = new Reposit_Functions();

        /*******************************OPERACION_CXC******************************************/

        $oQry_Cxc = null;
        if ($cDropTb == '1') {
            $str_sql = $str_sql . "DROP TABLE IF EXISTS `$cDb_NamD`.`operacion_cxc`;" . chr(10);
        }

        if ($cCreaTb == '1') {
            $cSql = "SHOW CREATE TABLE `$cDb_Nam`.`operacion_cxc`;";
            $oQry_Crea_Cxc = $poConn->query($cSql)->fetchArray();
            $records = $poConn->numRows();

            if ($records = 0) {
                $sValue1 = '';
            } else {
                $sValue1 = $oQry_Crea_Cxc['Create Table'];
                $sValue1 = str_replace("`operacion_cxc`", "`$cDb_NamD`.`operacion_cxc`", $sValue1);
                $sValue1 = $sValue1 . ';' . chr(10);
            }
            unset($oQry_Crea_Cxc);
        } else {
            $sValue1 = '';
        }
        $str_sql = $str_sql . $sValue1 . chr(10);

        if ($cDelReg == '1') {
            $str_sql = $str_sql . "DELETE FROM `$cDb_NamD`.`operacion_cxc` WHERE (c_id='$cCte_id');" . chr(10);
        }
        $cSql = "SELECT * FROM `$cDb_Nam`.`operacion_cxc` WHERE c_id='$cCte_id';";
        $TablaCxc = $poConn->query($cSql)->fetchall();
        $records = $poConn->numRows();
        //$cDropTb, $cCreaTb, $cDelReg, $, $SaveLog, $Repl_Bl
        if ($records > 0) {
            $sValue2 = $oRep->jsonmysql_insert_result_str_v2($TablaCxc, 'operacion_cxc', $poConn, $cDb_Nam, $cDb_NamD, 'id_reg', $cDupReg, 1, 1000, 0);
            //        $sValue2 = str_replace('.operacion_cxc','.tmp_operacion_cxc', $sValue2);
            $str_sql = $str_sql . $sValue2 . chr(10);
        }
        unset($TablaCxc);

        /*******************************OPERACION_CXC_APL******************************************/
        if ($cDropTb == '1') {
            $str_sql = $str_sql . "DROP TABLE IF EXISTS `$cDb_NamD`.`operacion_cxc_apl`;" . chr(10);
        }

        if ($cCreaTb == '1') {
            $cSql = "SHOW CREATE TABLE `$cDb_Nam`.`operacion_cxc_apl`;";
            $oQry_Crea_Apl = $poConn->query($cSql)->fetchArray();
            $records = $poConn->numRows();

            if ($records = 0) {
                $sValue1 = '';
            } else {
                $sValue1 = $oQry_Crea_Apl['Create Table'];
                $sValue1 = str_replace("`operacion_cxc_apl`", "`$cDb_NamD`.`operacion_cxc_apl`", $sValue1);
                $sValue1 = $sValue1 . ';' . chr(10);
            }
            unset($oQry_Crea_Apl);
        } else {
            $sValue1 = '';
        }
        $str_sql = $str_sql . $sValue1 . chr(10);

        if ($cDelReg == '1') {
            $str_sql = $str_sql . "DELETE FROM `$cDb_NamD`.`operacion_cxc_apl` WHERE c_id='$cCte_id';" . chr(10);
        }

        $cSql = "SELECT * FROM `$cDb_Nam`.`operacion_cxc_apl` WHERE c_id='$cCte_id';";
        $TablaApls = $poConn->query($cSql)->fetchall();
        $records = $poConn->numRows();
        if ($records > 0) {
            $sValue2 = $oRep->jsonmysql_insert_result_str_v2($TablaApls, 'operacion_cxc_apl', $poConn, $cDb_Nam, $cDb_NamD, 'autoinc', $cDupReg, 1, 1000, 0);
            //$sValue2 = str_replace('.operacion_cxc_apl','.tmp_operacion_cxc_apl', $sValue2);
            $str_sql = $str_sql . $sValue2 . chr(10);
        }
        unset($TablaApls);

        /*******************************CLIENTES*********************************************/
        if ($Include_Ctes == '1') {
            if ($cDropTb == '1') {
                $str_sql = $str_sql . "DROP TABLE IF EXISTS `$cDb_NamD`.`clientes`;" . chr(10);
            }

            if ($cCreaTb == '1') {
                $cSql = "SHOW CREATE TABLE `$cDb_Nam`.`clientes`;";
                $oQry_Crea_Ctes = $poConn->query($cSql)->fetchArray();
                $records = $poConn->numRows();

                if ($records = 0) {
                    $sValue1 = '';
                } else {
                    $sValue1 = $oQry_Crea_Ctes['Create Table'];
                    $sValue1 = str_replace('`clientes`', '`' . $cDb_NamD . '`.`clientes`', $sValue1);
                    $sValue1 = $sValue1 . ';' . chr(10);
                }
                unset($oQry_Crea_Ctes);
            } else {
                $sValue1 = '';
            }
            $str_sql = $str_sql . $sValue1 . chr(10);

            if ($cDelReg == '1') {
                // $str_sql = $str_sql . "DELETE FROM `$cDb_NamD`.`clientes` WHERE c_id='$cOp__id';" . chr(10);
            }

            $cSql = "SELECT * FROM `$cDb_Nam`.`clientes` WHERE c_id='$cCte_id';";
            $TablaCtes = $poConn->query($cSql)->fetchall();
            $records = $poConn->numRows();
            if ($records > 0) {
                $sValue2 = $oRep->jsonmysql_insert_result_str_v2($TablaCtes, 'clientes', $poConn, $cDb_Nam, $cDb_NamD, 'id_autoinc', $cDupReg, 1, 1000, 0);
                //$sValue2 = str_replace('.clientes','.tmp_clientes', $sValue2);
                $str_sql = $str_sql . $sValue2 . chr(10);
            }
            unset($TablaCtes);
        }
        /**
         * *********************************************************************************/

        if ($SaveLog == 1) {
            echo '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' . chr(13);
            echo 'SQL : ' . $str_sql . chr(13);
            echo '++++++++++++++++++++++++++++++++++++++++++++++insert_json_op_gen.php++++++++++++++++++++++++++++++++++++++++++' . chr(13);
            echo chr(13);
        }

        return $str_sql;
    }
    /*
    public function execute_procedure( $pDb_Nam, $Proc_name, $arrayPar)
    {
        $stmt =$this->connection->prepare('CALL ' . $pDb_Nam . '.'. $Proc_name);
        if ($stmt) {
            $iTParam = count($arrayPar);
            for ($x = 0; $x <= $iTParam; $x++) {
                $stmt->bind_param($x, $arrayPar[$x], PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 20);
            }
            $stmt->execute();
            $Result = $stmt->effected_rows;
            $stmt->close;
            return $Result;
        }
    }
*/
    public function call_doc_pend_upd($pDb_Nam, $pOp_Id)
    {
        $stmt = $this->connection->prepare('CALL `' . $pDb_Nam . '`.Doc_Pend_Upd(?,?)');
        $Debug = 1;
        $stmt->bind_param('si', $pOp_Id, $Debug);
        $stmt->execute();
        $Result = $stmt->errno;
        //var_dump($Result);

        $stmt->close;
        return $Result;
    }

    public function close_conn()
    {
        @mysqli_close($this->connection);
    }
}
