 <?php
    //error_reporting(E_ALL);
    error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
    include_once("utiles.php");
    date_default_timezone_set('America/Panama');
    $iAffected_rows = 0;

    function logs3($text, $Include_Time = true)
    {
        if (1 == 1) {
            //if ($SW_LOGFILE == 1) {

            $hoynowf = getdate();

            $hora = str_pad($hoynowf["minutes"], 2, "0", STR_PAD_LEFT);
            $timeStampf = $hoynowf["year"] . "-" . $hoynowf["mon"] . "-" . $hoynowf["mday"] . " " . $hoynowf["hours"] . ":" . $hora . ":" . $hoynowf["seconds"];

            if (is_readable("logphp.txt")) {
                // echo "Tienes permiso de lectura!";
            } else {
                // echo "NO Tienes permiso de lectura!";
            }

            // chmod ("logphp.txt", 0777);

            // Entrada

            $fp = fopen("log_php2.txt", "a");
            fputs($fp, ($Include_Time == true ? $timeStampf . " : " : '') . $text . "\r\n");
            fclose($fp);

            // echo $salida;
        }
    }

    // FECHA CREACION: JOHNN GUTIERREZ 2017-10-09
    // ULTIMA MODIFICACION: JOHNN GUTIERREZ 2017-10-09
    function Gen_Saldo_Actual_Aptdo($poConn, $cpDatab, $cpSuc_id, $cpOp_Id, $cOp_cxc, $pcSaveLog)
    {
        if ($pcSaveLog == 1) {
            logs2('*==============================>Gen_Saldo_Actual_Aptdo>=============================*');
            logs2('--->Database :' . $cpDatab);
            logs2('--->Sucursal :' . $cpSuc_id);
            logs2('--->Tbl_Opid :' . $cpOp_Id);
            logs2('--->Cxc_Opid :' . $cOp_cxc);
            logs2('*-----------------------------------------------------------------------------------*');
        }
        $Montos_Aptdo = Gen_Monto_Origen_Aptdo($poConn, $cpDatab, $cpSuc_id, $cpOp_Id, $pcSaveLog);

        $Abonos_Aptdo = Gen_Monto_Abonos_Aptdo($poConn, $cpDatab, $cpSuc_id, $cpOp_Id, $pcSaveLog);

        $Valor_Act = $Montos_Aptdo - $Abonos_Aptdo;

        if ($pcSaveLog == 1) {
            logs2('MONTO APT: ' . $Montos_Aptdo);
            logs2('ABONOS   : ' . $Abonos_Aptdo);
            logs2('SALDO ACT: ' . $Valor_Act);
            logs2('*FIN===========================<Gen_Saldo_Actual_Aptdo<=============================*');
            logs2('', false);
            logs2('', false);
        };
        return $Valor_Act;
    }

    // FECHA CREACION: JOHNN GUTIERREZ 2017-10-06
    // ULTIMA MODIFICACION: JOHNN GUTIERREZ 2017-10-09
    function Gen_Monto_Origen_Aptdo($poConn1, $cpDatab1, $cpSuc_id1, $cpOp_Id1, $pcSaveLog1)
    {
        $Valor_Tot = '0.00';

        if ($pcSaveLog1 == 1) {
            logs2('*-------------------------->Gen_Monto_Origen_Aptdo--------------------------*');
            logs2('--->Database :' . $cpDatab1);
            logs2('--->Sucursal :' . $cpSuc_id1);
            logs2('--->Tbl_Opid :' . $cpOp_Id1);
            logs2('*---------------------------------------------------------------------------*');
        };

        $sql = 'SELECT
        ROUND(IFNULL(op.op_total ,0),2) AS op_total
        FROM ' . $cpDatab1 . '.operacion op
        WHERE op.op_tipo = "3"
        AND op.op_id ="' . $cpOp_Id1 . '"
        GROUP BY op.op_id
        ORDER BY op.op_num_corre DESC';
        //AND suc_id="' . $cpSuc_id1 . '"

        $data = getRow($poConn1, $sql, $records, false);

        if ($records = 0) {
            $Valor_Tot = '0.00';
        } else {
            $Valor_Tot = ((($data['op_total'] == '') or ($data['op_total'] == null)) ? '0.00' : $data['op_total']);
        }

        if ($pcSaveLog1 == 1) {
            logs2('SQL : ' . $sql);
            logs2('RESP: ' . $Valor_Tot);
            logs2('*FIN----------------------->Gen_Monto_Origen_Aptdo--------------------------*');
            logs2('', false);
            logs2('', false);
        };
        return $Valor_Tot;
    }

    // FECHA CREACION: JOHNN GUTIERREZ 2017-10-06
    // ULTIMA MODIFICACION: JOHNN GUTIERREZ 2017-10-09
    function Gen_Monto_Abonos_Aptdo($poConn2, $cpDatab2, $cpSuc_id2, $cpOp_Id2, $pcSaveLog2)
    {
        $Valor_Abn = '0.00';

        if ($pcSaveLog2 == 1) {
            logs2('*-------------------------->Gen_Monto_Abonos_Aptdo>-------------------------*');
            logs2('--->Database :' . $cpDatab2);
            logs2('--->Sucursal :' . $cpSuc_id2);
            logs2('--->Cxc_Opid :' . $cpOp_Id2);
            logs2('*---------------------------------------------------------------------------*');
        }

        $cFieldDB = 'ROUND(IFNULL(op_debito ,0),2) ';
        $cFieldCR = 'ROUND(IFNULL(op_credito,0),2) ';

        $sql = 'SELECT
        SUM(' . $cFieldCR . ')-SUM(' . $cFieldDB . ') AS abonos
        FROM ' . $cpDatab2 . '.operacion_cxc
        WHERE id_tipo in(25,21,22)
        AND op_rel ="' . $cpOp_Id2 . '"
        AND IFNULL(op_aptdo,0)=1 '; 
        //AND suc_id="' . $cpSuc_id2 . '"';

        $data = getRow($poConn2, $sql, $records, false);

        if ($records == 0) {
            $Valor_Abn = '0.00';
        } else {
            $Valor_Abn = ((($data['abonos'] == '') or ($data['abonos'] == null)) ? '0.00' : $data['abonos']);
         }

        if ($pcSaveLog2 == 1) {
            logs2('SQL : ' . $sql);
            logs2('RESP: ' . $Valor_Abn);
            logs2('*FIN-----------------------<Gen_Monto_Abonos_Aptdo<-------------------------*');
            logs2('', false);
            logs2('', false);
        }
        return $Valor_Abn;
    }

    function Actualiza_saldos_Aptdo($poConn3, $cpDatab3, $cpSuc_id3, $cpOp__id3, $status, $S_Ant, $M_Abn, $S_Act, $pSaveLog3)
    {
        $timeStamp = date("Y-m-d H:i:s");

        if ($pSaveLog3 == 1) {
            logs2('*-------------------------->Actualiza_saldos_Aptdo--------------------------*');
            logs2('--->Database :' . $cpDatab3);
            logs2('--->Sucursal :' . $cpSuc_id3);
            logs2('--->Tbl_Opid :' . $cpOp__id3);
            logs2('--->Saldo Ant:' . $S_Ant);
            logs2('--->Tot. Abn :' . $M_Abn);
            logs2('--->Saldo Act:' . $S_Act);
            logs2('*---------------------------------------------------------------*');
        }

        $SQL_Update = 'UPDATE ' . $cpDatab3 . '.operacion SET
        ' . ($status == '' ? '' : 'op_aptdo_status     = "' . $status . '",') . '
        op_saldo_ant_aptdo  ="' . $S_Ant . '",
        op_pago_aptdo       ="' . $M_Abn . '",
        op_saldo_act_aptdo  ="' . $S_Act . '",
        op_aptdo_pagad      ="' . $timeStamp . '",
        usermodify          ="1",
        useroption          ="2"
        WHERE op_id  ="' . $cpOp__id3 . '" ';
        //AND   suc_id ="' . $cpSuc_id3 . '"';
        $iAffected_rows = 0;
        $result = update_Sql($poConn3, $SQL_Update, $iAffected_rows);

        if ($pSaveLog3 == 1) {
            logs2('SQL :' . $SQL_Update);
            logs2('RES : ' . ($result ? 'true' : 'false'));
            logs2('*FIN----------------------->Actualiza_saldos_Aptdo--------------------------*');
            logs2('', false);
            logs2('', false);
        }
        return $result;
    }

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

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

        if ($pcSaveLog3 == 1) {
            logs2('REGISTROS: ' . $regs_cnt);
        }

        // 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 = update_Sql($poConn3, $sql, $iAffected_rows);

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

            $ib++;

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

        if ($pcSaveLog3 == 1) {
            logs2('*FIN------------------------jsonmysql<-------------------------*');
            logs2('', false);
            logs2('', false);
        }
        return $result;
    }

    function empty2null($value)
    {
        return ($value === '' ? null : $value);
    }

    function Actualiza_Exist_Online($poConn, $Db_Nam, $suc_id, $Tipo, $pPo_op_id, $Sign = 1, $bAllItems = true, $pMPr_id = '', $bProduct_Op2 = false, $pSaveLog)
    {
        if ($pSaveLog == 1) {
            logs2('-------------------------------Actualiza_Exist_Online-----------------------------');
            logs2('--->Database :' . $Db_Nam);
            logs2('--->Sucursal :' . $suc_id);
            logs2('--->Tbl_Opid :' . $pPo_op_id);
            logs2('--->Tipo_Op  :' . $Tipo);
            logs2('--->Signo    :' . $Sign);
            logs2('--->Pr_id    :' . $pMPr_id);
            logs2('*---------------------------------------------------------------*');
        };

        $cSqlLine = '';
        $cSetLine = '';

        if ($bProduct_Op2 == false) {
            $cProduct_Op = 'producto_op';
        } else {
            $cProduct_Op = 'producto_op2';
        };

        if ($Tipo == '8') {
            return (TRUE);
            exit();
        };

        switch ($Tipo) {
                /* {-----------------------------Compras-----------------------------------------} */
            case 1: /*{Compra}*/
                $cSetLine = ' a.p_compras    =  (a.p_compras  +  abs(b.po_cant)) ';
                $Sign = 1;
            case 19: /*{Dev. Compra}*/
                $cSetLine = ' a.p_dcompras =  (a.p_dcompras +  abs(b.po_cant)) ';
                $Sign = -1;
            case 11: /*{Nota Entrega Compra}*/
                $cSetLine = ' a.p_ncompras =  (a.p_ncompras +  abs(b.po_cant)) ';
                $Sign = 1;
            case 30: /*{Cargos mercancia}*/
                $cSetLine = ' a.p_cargos     =  (a.p_cargos  +  abs(b.po_cant)) ';
                $Sign = 1;
            case 31: /*{Decargos mercancia}*/
                $cSetLine = ' a.p_descargos  =  (a.p_descargos  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 32: /*{Cargos mercancia por desempaques(Autom�ticos)}*/
                $cSetLine = ' a.p_cargo_auto     =  (a.p_cargo_auto  +  abs(b.po_cant)) ';
                $Sign = 1;
            case 33: /*{Decargos mercancia por desempaques(Autom�ticos)}*/
                $cSetLine = ' a.p_descargo_auto  =  (a.p_descargo_auto  +  abs(b.po_cant)) ';
                $Sign = -1;
                /* {-----------------------------Ventas-----------------------------------------} */
            case 2: /*{Venta}*/
                $cSetLine = ' a.p_ventas   =  (a.p_ventas  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 13: /*{Venta de Cortes�a}*/
                $cSetLine = ' a.p_ventas_cort   =  (a.p_ventas_cort  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 14: /*{Venta al Costo}*/
                $cSetLine = ' a.p_ventas_cost   =  (a.p_ventas_cost  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 3: /*{Apartado Mercancia}*/
                $cSetLine = ' a.p_apartado    =  (a.p_apartado  + abs(b.po_cant)) ';
                $Sign = -1;
            case 4: /*{Dev. Nota entrega Cliente}*/
                $cSetLine = ' a.p_rventas  =  (a.p_rventas  +  abs(b.po_cant)) ';
                $Sign = 1;
            case 16: /*{Dev. Ventas}*/
                $cSetLine = ' a.p_dventas  =  (a.p_dventas  + abs(b.po_cant)) ';
                $Sign = 1;
            case 7: /*{Nota de Entrega Cliente}*/
                $cSetLine = ' a.p_nventas  =  (a.p_nventas  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 9: /*{pedidos Clientes}*/
                $cSetLine = ' a.p_pventas  =  (a.p_pventas  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 12: /*{Ajustes Inventarios}*/
                // $Sign := -1;
                $cSetLine = ' a.p_ajustes     =  (a.p_ajustes  +  (b.po_cant)) ';
            case 36: /*{Transferencia de Mercancia [Saliente]}*/
                $cSetLine = ' a.p_trasl_sal   =  (a.p_trasl_sal  +  abs(b.po_cant)) ';
                $Sign = -1;
            case 37: /*{Transferencia de Mercancia [Entrante]}*/
                $cSetLine = ' a.p_trasl_ent   =  (a.p_trasl_ent  + abs(b.po_cant)) ';
                $Sign = 1;
            case 40: /*{Cargos de Inventario Por Producci�n}*/
                $cSetLine = ' a.p_cargo_prod   =  (a.p_cargo_prod  +  abs(b.po_cant)) ';
                $Sign = 1;
            case 41: /*Descargos de Inventario Por Producci�n*/
                $cSetLine = ' a.p_descargo_prod=  (a.p_descargo_prod  + abs(b.po_cant)) ';
                $Sign = -1;
        };

        $cSqlLine = '
        UPDATE prod_existencia a,
            (SELECT
                o.po_id,
                o.po_op_id,
                o.po_id_prod,
                SUM(o.po_cant* o.po_signo) AS po_cant,
                o.po_dep_id,
                o.suc_id
            FROM ' . $Db_Nam . '.' . $cProduct_Op . ' o
         	INNER JOIN ' . $Db_Nam . '.productos_det pd ON (o.po_id_prod = pd.pr_id and pd.suc_id="1")
            INNER JOIN ' . $Db_Nam . '.depositos     dp ON (o.po_dep_id = dp.dep_id) AND (dp.suc_id = o.suc_id)
            WHERE o.suc_id="' . $suc_id . '"
            AND   pd.pr_man_exist = 1
            AND   o.po_op_id = "' . $pPo_op_id . '"
            GROUP BY o.po_dep_id,o.po_id_prod
            ORDER BY o.po_dep_id,o.po_id_prod) b ';

        /* // modif juan * a la cantidad se le agrego valor absoluto */
        if ($Tipo == '12') {
            $cSqlLine = $cSqlLine . 'SET   a.p_existencia = (a.p_existencia + b.po_cant), ';
        } else {
            $cSqlLine = $cSqlLine . 'SET   a.p_existencia = (a.p_existencia + (' . $Sign . ' * abs(b.po_cant))), ';
            // fin
            $cSqlLine = $cSqlLine . $cSetLine . ' ';

            $cSqlLine = $cSqlLine . 'WHERE a.pr_id = b.po_id_prod ';
            $cSqlLine = $cSqlLine . 'AND   a.p_existencia_dep_id = b.po_dep_id ';

            if ($bAllItems == false) {
                $cSqlLine = $cSqlLine . 'AND   b.po_id_prod ="' . $pMPr_id . '" ';
            };
            $iAffected_rows = 0;
            $resp = update_Sql($poConn, $cSqlLine, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('SQL: ' . $cSqlLine);
                logs2('RES: ' . ($resp ? 'true' : 'false'));
                logs2('', false);
                logs2('', false);
            };
            return ($resp);
        };
    };

    function Actualiza_Exist_Apdo($poConn, $Db_Nam, $suc_id, $pPo_op_id, $pSaveLog)
    {
        if ($pSaveLog == 1) {
            logs2('', false);
            logs2('-------------------------------Actualiza_Exist_Apdo-----------------------------');
            logs2('----------------------------------------------------------------------------------');
            logs2('', false);
            logs2('', false);
        };
        $Sql = '
        UPDATE prod_existencia a,
            (SELECT
                o.po_id,
                o.po_op_id,
                o.po_id_prod,
                SUM(o.po_cant_pend* o.po_signo) AS po_cant_pend,
                o.po_dep_id,
                o.suc_id
            FROM ' . $Db_Nam . '.producto_op o
         	INNER JOIN ' . $Db_Nam . '.productos_det pd ON (o.po_id_prod = pd.pr_id) AND (pd.suc_id="1")
            INNER JOIN ' . $Db_Nam . '.depositos     dp ON (o.po_dep_id = dp.dep_id) AND (dp.suc_id = o.suc_id)
            WHERE o.suc_id="' . $suc_id . '"
            AND   productos_det.pr_man_exist = 1
            AND   o.po_op_id = "' . $pPo_op_id . '"
            GROUP BY o.po_dep_id,o.po_id_prod
            ORDER BY o.po_dep_id,o.po_id_prod) b
        SET
            a.p_existencia = (a.p_existencia + abs(b.po_cant_pend)),
            a.p_apartado   = (a.p_apartado   - abs(b.po_cant_pend))
        WHERE a.pr_id = b.po_id_prod
        AND   a.p_existencia_dep_id = b.po_dep_id ';

        $iAffected_rows = 0;
        $resp = update_Sql($poConn, $Sql, $iAffected_rows);

        if ($pSaveLog == 1) {
            logs2('', false);
            logs2('SQL: ' . $Sql);
            logs2('RES: ' . ($resp ? 'true' : 'false'));
            logs2('', false);
        };
        return ($resp);
    };

    function Anula_OP_AND_PO($poConn, $Db_Nam, $suc_id, $cOp_Cte, $cOp_Tip, $cOp_Id, $pSaveLog)
    {
        try {

            $cSql = 'CREATE TABLE IF NOT EXISTS operacion_aud LIKE operacion';
            $iAffected_rows = 0;
            $Upd1 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL: ' . $cSql);
                logs2('RES: ' . ($Upd1 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = 'SELECT Get_AllFields_ExeptV3("operacion_aud","noexiste") AS FieldsLst';
            $result = getRow($poConn, $cSql, $records, false);
            $cFieldsLst = $result['FieldsLst'];

            $cSql = '
        INSERT INTO operacion_aud (' . $cFieldsLst . ')
            SELECT ' . $cFieldsLst . ' FROM operacion
            WHERE op_id         ="' . $cOp_Id . '"
            AND   op_tipo       ="' . $cOp_Tip . '"
            AND   op_id_cliente ="' . $cOp_Cte . '"
            AND   suc_id        ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd2 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd2 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = 'CREATE TABLE IF NOT EXISTS producto_op_aud LIKE producto_op ';
            $iAffected_rows = 0;
            $Upd3 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd3 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = 'SELECT Get_AllFields_ExeptV3("producto_op_aud","noexiste") AS FieldsLst';
            $result = getRow($poConn, $cSql, $records, false);
            $cFieldsLst = $result['FieldsLst'];

            $cSql = '
        INSERT INTO producto_op_aud (' . $cFieldsLst . ')
            SELECT ' . $cFieldsLst . ' FROM producto_op
            WHERE po_op_id ="' . $cOp_Id . '"
            AND   suc_id   ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd4 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd4 ? 'true' : 'false'));
                logs2('', false);
            }

            /* {Localiza la operacion y la anula.} */
            $cSql_Sets = '
        SET op_subtotal =0, op_itbms  =0, op_total   =0, op_manejo  =0, op_flete=0, op_seguro=0, op_desc=0,
            op_subtotalneto=0, op_utilidad=0, op_utilidadporc=0, op_costo=0,
            op_pagado  =0, op_vuelto  =0,	op_diferencia=0,
            op_contado =0, op_credito =0, op_efectivo=0,
            op_cheque  =0, op_tcredito=0, op_tdebito =0,
            op_forma_6 =0, op_forma_7 =0, op_forma_8 =0, op_forma_9 =0,
            op_forma_10=0, op_forma_11=0, op_forma_12=0, op_forma_13=0,
            op_forma_14=0, op_forma_15=0, op_forma_16=0, op_forma_17=0,
            op_forma_18=0, op_forma_19=0, op_forma_20=0,
            emp_imp0base=0,emp_imp1base=0,emp_imp2base=0,emp_imp3base=0,emp_imp4base=0,
            emp_imp1=0,emp_imp2=0,emp_imp3=0,emp_imp4=0,
            op_desctm=0,op_desctp=0,
            saldo_ant=0, monto_pago=0,saldo_act=0,
            id_status=3,op_observ="DOCUMENTO ANULADO ADMINISTRATIVAMENTE.",UserModify=1,UserOption=2
        WHERE op_id         ="' . $cOp_Id . '"
        AND   op_tipo       ="' . $cOp_Tip . '"
        AND   op_id_cliente ="' . $cOp_Cte . '"
        AND   suc_id        ="' . $suc_id . '"';

            $cSql = 'UPDATE operacion ' . $cSql_Sets;
            $iAffected_rows = 0;
            $Upd5 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd5 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = 'UPDATE operacion2 ' . $cSql_Sets;
            $iAffected_rows = 0;
            $Upd6 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd6 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        UPDATE producto_op SET pr_condiciones = po_cant 
        WHERE po_op_id ="' . $cOp_Id . '"
        AND   suc_id   ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd7 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd7 ? 'true' : 'false'));
                logs2('', false);
            }

            /* {Busca la los productos de la operacion y la anula.} */

            $cSql_Sets = '
        SET po_costo=0, po_precio=0, po_itbms=0, po_cant=0, po_cant_pend=0, po_precioneto=0, po_desc1=0, 
            po_desc2=0, po_utilidad=0, po_utilidad_porc=0, po_montoimp=0, po_preciotmp=0,
            po_comisionv=0, po_comisionv_porc=0, po_comisionc=0, po_comisionc_por=0, po_montoimp_adic=0,
            po_costo_fob=0, po_costo_fob_porc=0,
            UserModify=1, UserOption=2 
        WHERE po_op_id ="' . $cOp_Id . '"
        AND   suc_id   ="' . $suc_id . '"';

            $cSql = 'UPDATE producto_op ' . $cSql_Sets;
            $iAffected_rows = 0;
            $Upd8 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd8 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = 'UPDATE producto_op2 ' + $cSql_Sets;
            $iAffected_rows = 0;
            $Upd9 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd9 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM entradas_salidas_desg 
        WHERE op_id  ="' . $cOp_Id . '"
        AND   suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd10 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd10 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM entradas_salidas_det_pago 
        WHERE op_id  ="' . $cOp_Id . '"
        AND   suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd11 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd11 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM operacion_det_pago 
        WHERE op_id  ="' . $cOp_Id . '"
        AND   suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd12 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd12 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM operacion_det_pago2 
        WHERE op_id  ="' . $cOp_Id . '"
        AND   suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd13 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd13 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM operacion_det_pago_dif 
        WHERE op_id  ="' . $cOp_Id . '"';
            // AND suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd14 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd14 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM operacion_det_pago_mm 
        WHERE op_id  ="' . $cOp_Id . '"';
            // AND suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd15 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd15 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        DELETE FROM operacion_det_pago_mm2 
        WHERE op_id  ="' . $cOp_Id . '"';
            // AND suc_id ="' . $suc_id . '"';
            $iAffected_rows = 0;
            $Upd16 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd16 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        UPDATE puntos_clientes a 
        JOIN puntos_detalle b ON a.c_id = b.c_id 
            SET a.puntos = (a.puntos - b.puntos) 
        WHERE b.op_id = "' . $cOp_Id . '"
        AND   b.acum  = "1" ';
            $iAffected_rows = 0;
            $Upd17 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd17 ? 'true' : 'false'));
                logs2('', false);
            }

            $cSql = '
        UPDATE puntos_detalle 
            SET puntos=0, usermodify=1 
        WHERE op_id ="' . $cOp_Id . '"
        AND   acum  =1 ';
            $iAffected_rows = 0;
            $Upd18 = update_Sql($poConn, $cSql, $iAffected_rows);

            if ($pSaveLog == 1) {
                logs2('', false);
                logs2('SQL : ' . $cSql);
                logs2('RES: ' . ($Upd18 ? 'true' : 'false'));
                logs2('', false);
            }
            return true;
        } catch (Exception $e) {
            echo 'Excepci�n capturada: ', $e->getMessage(), "\n";
            return false;
        }
    }

    function cleanString($text)
    {
        $utf8 = array(
            '/[�����]/u'   =>   'a',
            '/[�����]/u'    =>   'A',
            '/[����]/u'     =>   'I',
            '/[����]/u'     =>   'i',
            '/[����]/u'     =>   'e',
            '/[����]/u'     =>   'E',
            '/[������]/u'   =>   'o',
            '/[�����]/u'    =>   'O',
            '/[����]/u'     =>   'u',
            '/[����]/u'     =>   'U',
            '/�/'           =>   'c',
            '/�/'           =>   'C',
            '/�/'           =>   'n',
            '/�/'           =>   'N',
            '/�/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
            '/[�����]/u'    =>   ' ', // Literally a single quote
            '/[�����]/u'    =>   ' ', // Double quote
            '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
        );
        return preg_replace(array_keys($utf8), array_values($utf8), $text);
    }

    function jsonmysql2($tabla, $reg_p, $nombre, $connection1, $database, $pSaveLog)
    {

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

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

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

            $opfinal = $tabla[$ib];

            $cadena = '';
            $cadena2 = '';
            $cadena3 = '';
            $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 . '"';
                }

                // if ($ib == 0) {
                $cadena3 = $cadena3 . $fieldkey . '=VALUES(' . str_replace(',', '', $fieldkey) . ') ';
                // }
                $cadena = $cadena . $field;
                $cadena2 = $cadena2 . $value;
                $i = $i + 1;

                // }
            }

            // echo $cadena3;

            $sql = "insert into " . $database . "." . $nombre . " (" . $cadena . ") values (" . $cadena2 . ") ON DUPLICATE KEY UPDATE " . $cadena3 . "";
            if ($nombre == 'clientes') {
                // echo $sql;
            }
            $sql = str_replace("0000-00-00 00:00:00", "2009-01-01 01:01:01", $sql);
            $iAffected_rows = 0;
            $result = update_Sql($connection1, $sql, $iAffected_rows);

            if ($pSaveLog == '1') {
                logs2('Nombre : ' . $nombre);
                logs2('Sql    : ' . $sql);
                logs2('RES    : ' . ($result ? 'true' : 'false'));
            }

            $ib++;
        }

        return $result;
    }

    ?>
