<?php

function login_user($user, $pass) {
    global $sql;
    FLAG_HO == false ? $sql->select("COD,NOM,DOM,LOC,PVC,PASSWEB,MCC") : $sql->select("COD,NOM,DOM,LOC,PCI,PASSWEB,MCC");
    $sql->where(" COD = $user and (PASSWEB='$pass' or (PASSWEB='' and '123456'='$pass'))");
    $rtn = $sql->get_tabla("clientes");
    
    if ($rtn) {
        if ($rtn[0]['PASSWEB'] == '' && $pass == '123456') { //si el cliente q se logea con el pass 123456 y en la bd tiene x defecto vacio se actualiza
            $sql->query("UPDATE clientes SET PASSWEB='123456' WHERE COD=".$user);
        }
        $rtn[0]['NOM'] = htmlspecialchars(utf8_encode($rtn[0]['NOM']));
        $rtn[0]['DOM'] = utf8_encode($rtn[0]['DOM']);
        $rtn[0]['LOC'] = utf8_encode($rtn[0]['LOC']);
        FLAG_HO == false ? $rtn[0]['PVC'] = utf8_encode($rtn[0]['PVC']) : $rtn[0]['PCI'] = utf8_encode($rtn[0]['PCI']);
    } else {
        $rtn = array();
    }

    return $rtn;
}

function repass($nueva, $key, $enc_type, $enc_key_secret) {
    global $sql;
    $a_contactos = $sql->get_tabla("A_CONTACTOS");

    if ($a_contactos) {
        foreach ($a_contactos as $contacto) {
            $tmp = $contacto['COD'] . "--" . $contacto['EMAIL'];
            $tmp = hash_hmac($enc_type, $tmp, $enc_key_secret);
            if ($key == $tmp) {
                $cod_find = $contacto['COD'];
                break;
            }
        }
    }

    //file_put_contents('eeee.log', $cod_find);

    if ($cod_find) {
        //update
        return $sql->update("clientes", array("PASSWEB" => $nueva), "COD = " . $cod_find);
    } else {
        return false;
    }
}

function cambiar_clave($user, $oldpass, $newpass) {
    global $sql;

    $sql->where("COD = " . $user . " AND PASSWEB = '" . $oldpass . "'");
    $old = $sql->get_tabla("clientes");

    if ($old) {
        //update
        return $sql->update("clientes", array("PASSWEB" => $newpass), "COD = " . $user);
    } else {
        return false;
    }
}

function recordar_clave($email) {
    global $sql;

    $sql->where(" EMAIL = '" . $email . "'");
    $cli = $sql->get_tabla("A_CONTACTOS");

    if ($cli) {
        $sql->select('passweb');
        $sql->where("COD = " . $cli[0]['COD']);
        $clic = $sql->get_tabla("clientes");

        $rtn = array(
            "cod" => $cli[0]['COD'],
            "email" => $cli[0]['EMAIL'],
            "passweb" => $clic[0]['passweb']
        );
        return $rtn;
    } else {
        return false;
    }
}

function resumen_cuenta($usuario, $desde, $hasta, $cc, $remito, $contado, $anulada, $orden, $empresa=0, $remitoPrecioActual) {
    global $sql;
    date_default_timezone_set('America/Argentina/Buenos_Aires');

    //log_this('AAAAAA.log',":::::::::::::RESUMEN DE CUENTA:::::::::::::::");
    //log_this('AAAAAA.log',"DESDE: " . print_r(date("Y/m/d", $desde),TRUE) . " HASTA: " . print_r(date("Y/m/d", $hasta),TRUE));
    $sql_cod = " select nom, grp from clientes where cod=" . $usuario;
    $cli_dat = $sql->query($sql_cod);
    Auditoria::guardar(array(
        'USU' => '9999',
        'FRM' => 'Resumen de cuenta web',
        'TEX' => 'El cliente '.$usuario.' '.$cli_dat[0]['nom'].' solicita resumen de cuenta desde '.date('d/m/Y', $desde).' hasta '.date('d/m/Y', $hasta)
    ), $sql);
    if (FLAG_HO == FALSE) {
        //log_this('AAAAAA.log',"---------------------------------------FLAG_HO = FALSE");
        if ($orden == 0) {
            $sql->order_by("a.fep desc, a.suc, A.nco", $ord = "");
        }
        if ($orden == 1) {
            $sql->order_by("a.fep asc, a.suc, A.nco", $ord = "");
        }        
        if($remito && $contado && $anulada){
            //log_this('AAAAAA.log',"REMITO & CONTADO & ANULADA");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','RE') AND a.fpa in (0,1,2,3,4,5)"); 
        }else if($remito && $contado){
            //log_this('AAAAAA.log',"REMITO & CONTADO");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','RE') AND a.fpa in (0,1,2,3,4,5) and A.anu <> 'A'");
        }
        else if($remito && $anulada){
            //log_this('AAAAAA.log',"REMITO & ANULADA");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','RE') AND a.fpa in (2,3,4,5)");
        }
        else if($contado && $anulada){
            //log_this('AAAAAA.log',"CONTADO & ANULADA");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN') AND a.fpa in (0,1,2,3,4,5)");
        }
        else if ($anulada) {
            //log_this('AAAAAA.log',"ANULADA");
            $sql->where(" A.FPA != 1 AND A.TCO != 'RE'");
        }
        else if ($contado) {
            //log_this('AAAAAA.log',"CONTADO");
            $sql->where("a.anu != 'A' AND A.FPA IN (0,1,2,3,4,5) AND A.TCO != 'RE'");
        }
        else if ($remito) {
            //log_this('AAAAAA.log',"REMITO");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','RE') AND a.FPA IN(2,3,4,5) and A.anu <> 'A'");
        }
        if($remito || $contado || $anulada){
            //log_this('AAAAAA.log',"REMITO || CONTADO || ANULADA");
            if($remito == true){
                //log_this('AAAAAA.log',"REMITO EN TRUE");
                $sql->select("D.DET1,D.DET3,AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
                $sql->JOIN("DET_CONDUCT_COMP D","A.NCO = D.NCO and A.SUC = D.SUC and A.TCO = D.TCO and A.CLI = D.CLI", "LEFT OUTER");
                $sql->group_by("D.DET1,D.DET3,AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
            } else {
                //log_this('AAAAAA.log',"REMITO EN FALSE");
                $sql->select("AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
                $sql->group_by("AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
            }
            $sql->join("AMAEFACT B", " A.TIP=B.TIP AND A.TCO=B.TCO AND A.SUC=B.SUC AND  A.NCO=B.NCO AND A.CLI = B.CLI", "FULL OUTER");
            $sql->join("APAREMP AP","AP.EMP = A.EMP");
            if($cli_dat[0]['grp'] == 1){
                $sql->where("(A.cli = " . $usuario . " or A.cta = " . $usuario . ")");   
            } else {
                $sql->where("A.cli = " . $usuario);
            }
            $sql->where(" CONVERT(CHAR(10),A.fep,111) >= '" . date("Y/m/d", $desde) . "'" .
                    " AND CONVERT(CHAR(10),A.fep,111) <= '" . date("Y/m/d", $hasta) . "'");
            //$sql->where("a.rec = 0");
                if (isset($empresa) && $empresa != -1) {//todas las empresas -1
                    $sql->where("AP.EMP = $empresa");
                }
            $prev = $sql->get_tabla("acobypag A");
        }else{
            //log_this('AAAAAA.log',"NI REMITO NI CONTADO NI ANULADA");            
            $sql->select("AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
            $sql->join("AMAEFACT B", " A.TIP=B.TIP AND A.TCO=B.TCO AND A.SUC=B.SUC AND  A.NCO=B.NCO AND A.CLI = B.CLI", "FULL OUTER");
            $sql->join("APAREMP AP","AP.EMP = A.EMP");
            if($cli_dat[0]['grp'] == 1){
                $sql->where("(A.cli = " . $usuario . " or A.cta = " . $usuario . ")");   
            } else {
                $sql->where("A.cli = " . $usuario);
            }
            $sql->where(" CONVERT(CHAR(10),A.fep,111) >= '" . date("Y/m/d", $desde) . "'" .
                    " AND CONVERT(CHAR(10),A.fep,111) <= '" . date("Y/m/d", $hasta) . "'");
            $sql->where(" a.TCO != 'RE' AND a.FPA != 1 and A.anu <> 'A'");                    
            //$sql->where("a.rec = 0");
            $sql->group_by("AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
                if (isset($empresa) && $empresa != -1) {//todas las empresas -1
                    $sql->where("AP.EMP = $empresa");
                }
            $prev = $sql->get_tabla("acobypag A");
        }
    } else {
        //log_this('AAAAAA.log',"---------------------------------------FLAG_HO = TRUE");
        if(!$remito && !$contado && !$anulada){
            //log_this('AAAAAA.log',"REMITO & CONTADO & ANULADA");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','SA', 'CE') AND a.fpa in (2,3,4,5) and A.anu <> 'A'"); 
        }else if(!$remito && !$contado){
            //log_this('AAAAAA.log',"REMITO & CONTADO");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN') AND a.fpa in (2,3,4,5)");
        }
        else if(!$remito && !$anulada){
            //log_this('AAAAAA.log',"REMITO & ANULADA");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN') AND a.fpa in (0,1,2,3,4,5) and A.anu <> 'A'");
        }
        else if(!$contado && !$anulada){
            //log_this('AAAAAA.log',"CONTADO & ANULADA");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','RE') AND a.fpa in (2,3,4,5) and A.anu <> 'A'");
        }
        else if (!$anulada) {
            //log_this('AAAAAA.log',"ANULADA");
            $sql->where("A.anu != 'A'");
        }
        else if (!$contado) {
            //log_this('AAAAAA.log',"CONTADO");
            $sql->where("A.FPA IN (2,3,4,5)");
        }
        else if (!$remito) {
            //log_this('AAAAAA.log',"REMITO");
            $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN') AND a.FPA IN(0,1,2,3,4,5)");
        }

        if($remito){
            //log_this('AAAAAA.log',"REMITO");
            $sql->select("D.DET1, D.DET3, A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cod,A.anu,A.rep,A.SALDO_CALC, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
            $sql->JOIN("DET_CONDUCT_COMP D","A.NCO = D.NCO and A.SUC = D.SUC and A.TCO = D.TCO and A.COD = D.CLI", "LEFT");
        }else{
            //log_this('AAAAAA.log',"SIN REMITO");
            $sql->select(" A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cod,A.anu,A.rep,A.SALDO_CALC, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
        }
        $sql->join("AMAEFACT B", " A.TIP=B.TIP AND A.TCO=B.TCO AND A.SUC=B.SUC AND A.NCO=B.NCO", "FULL OUTER");
        $sql->where("A.hos<>'S' AND A.cod = " . $usuario);
        $sql->where(" CONVERT(CHAR(10),A.fep,111) >= '" . date("Y/m/d", $desde) . "'" .
           " AND CONVERT(CHAR(10),A.fep,111) <= '" . date("Y/m/d", $hasta) . "'");
        //$sql->order_by("A.fep,A.fpa,A.tco");

        if ($orden == 0) {
            //Se fuerza el asc para que al final, antes del return, se pueda dar vuelta el array  [inc554672]
            $sql->order_by("A.fep asc, A.suc, A.nco", $ord = "");
        }
        if ($orden == 1) {
            $sql->order_by("A.fep asc, A.suc, A.nco", $ord = "");
        }
        $prev = $sql->get_tabla("acobypag A");
        //log_this('prev.log', print_r($prev,true) . "\n");
    }
    if(FLAG_HO == FALSE){
        if($prev){
            foreach ($prev as $tData) {
                $sucursales[] = $tData['suc'];
            }
        }
    }else{
        $sucursales = 0;
    }

    $nSalRPEL = "0";
    $nSalRpe = 0;
    $nnSal = 0;
    $saldos = TraerSaldoAnteriorRC(date("Y/m/d", $desde), date("Y/m/d", $hasta), $usuario,$empresa, $sucursales, $remitoPrecioActual);

    $fech = date("Y-m-d", $desde);
    $dias = 1;
    $fech = strtotime("$fech -$dias day");
    $saldos["desde"] = date('d', $fech) . " " . get_mes(date('n', $fech)) . " " . date('Y', $fech);
    $saldos["tipo"] = 'resumen';

    $saldos["cliente"]["cta"] = $usuario;
    $saldos["cliente"]["cli"] = str_replace("&","Y",utf8_encode($cli_dat[0]["nom"]));

    $nSalRPEL = $nSalRpe;

    $ret = array();
    $c = 0;
    $nDB = 0;
    $nCR = 0;
    $ndeb = 0;
    $ncre = 0;
    //log_this('AAAAAA.log',":::::::::PREV::::::::::");
    //log_this('prev.log',print_r($prev,TRUE));
    if ($prev) {
        //log_this('AAAAAA.log',"***********EMPIEZAN LOS CALCULOS PARA TOTALES**************");
        $nSalRPEL = myfloat($saldos["rpe"]);

        foreach ($prev as $rs) {
            $nswIR = true;
//            return $remito;
            if ($rs['tco'] == "RE" && $remito == 1) {
//                return 'entraIF';
                $nswIR = true;
            } else {
//                return 'entraElse';
                $nswIR = true;
            }

            if ($nswIR) {
//                $nDB = 0;
//                $nCR = 0;
                if (FLAG_HO == FALSE && $empresa == -1){
                    if($rs['suc'] != 0 && $rs['tco'] == "RC"){
                        $sql->select('SUM(A.IMP) as SUMA , A.TIL');
                        $sql->join('ARECIBOS B','A.EMP=B.EMP AND A.CYV=B.CYV AND A.TIP=B.TIP AND A.TCO=B.TCO AND A.SUC=B.SUC AND A.NCO=B.NCO','INNER');
                        $sql->where("A.emp=0 and A.TCO IN ('RC','RM') AND A.SUC=". $rs['suc'] ." AND A.NCO=". $rs['nco'] ." AND B.CLI=". $rs['cli'] ."  AND A.TCO='".$rs['tco']."' AND A.LOP = 'L' AND NOT A.COM LIKE '%AC%'");
                        $sql->group_by("A.TIL");
                        $result = $sql->get_tabla("ADETREC A");
                        //log_this('AAAAAA.log',"RESULT: " . print_r($result,TRUE));
                        $total_positivo = 0;
                        $total_negativo = 0;
                        if($result){
                            foreach($result as $res){
                                if($res['TIL'] == 'FT' || $res['TIL'] == 'ND' || $res['TIL'] == 'SA'){
                                    $suma = $res['SUMA'] ? $res['SUMA'] : 0;
                                    $total_positivo += $suma;
                                } else {
                                    $resta = $res['SUMA'] ? $res['SUMA'] : 0;
                                    $total_negativo += $resta;
                                }
                            }
                            $resultado = $total_positivo - $total_negativo;
                            //log_this('AAAAAA.log',"RESULTADO: " . print_r($resultado,TRUE) . " = " . print_r($total_positivo,TRUE) . " - " . print_r($total_negativo,TRUE));
                            if($resultado != $rs['ipa']){
                                //log_this('AAAAAA.log',"RESULTADO ES " . print_r($rs['ipa'],TRUE) . " != " . print_r($resultado,TRUE));
                                //log_this('AAAAAA.log',"FECHA " . print_r($rs['fev'],TRUE));
                            }                        
                            $rs['ipa'] = $resultado;
                        }
                    } else if ($rs['suc'] == 0 && $rs['ipa'] != 0 && $rs['tco'] == "RC"){
                        //log_this('AAAAAA.log',"RESULTADO ES " . print_r($rs['ipa'],TRUE));
                        //log_this('AAAAAA.log',"FECHA " . print_r($rs['fev'],TRUE));
                        $es_duplicado = $sql->query("SELECT * FROM ACOBYPAG where cli = ". $rs['cli'] ." and nco = ".substr($rs['nco'],2)." and tip = '". $rs['tip'] ."' and suc = ".substr($rs['nco'],0,2)." and tco = '". $rs['tco'] ."'");
                        if($es_duplicado){
                            $rs['ipa'] = 0;
                        }
                        
                    }
                }
                $ret[$c]['fep'] = $rs['fep'];
                $ret[$c]['ncNCO'] = $rs['ncNCO'];
                $ret[$c]['obs'] = "";
                $ret[$c]['DEB'] = "";
                $ret[$c]['CRED'] = "";
                $ret[$c]['SAL'] = "";

                $ret[$c]['tco_o'] = $rs['tco'];
                $ret[$c]['tip_o'] = $rs['tip'];
                $ret[$c]['suc_o'] = $rs['suc'];
                $ret[$c]['nco_o'] = $rs['nco'];
                $ret[$c]['cod_o'] = FLAG_HO == false ? $rs['cli'] : $rs['cod'];
                if ($remito) {
                    $ret[$c]['DET1'] = $rs['DET1'];
                    $ret[$c]['DET3'] = $rs['DET3'];
                }
                FLAG_HO == false ? $ret[$c]['NOM'] = $rs['NOM'] : '';
                FLAG_HO == false ? $ret[$c]['EMP'] = $rs['EMP'] : ''; //REVIZAR PARA BO 

                if ($rs['fpa'] == 2 && $rs['tco'] != "RC") {
                    $ret[$c]['fpa'] = "CC";
                } elseif ($rs['fpa'] == 1 && $rs['tco'] == "RC") {
                    $ret[$c]['fpa'] = "CO";
                } elseif ($rs['tco'] == "RC") {
                    $ret[$c]['fpa'] = "CC";
                } else {
                    $ret[$c]['fpa'] = "CO";
                }

                $ret[$c]['tco'] = $rs['tco'];
                If ($rs['tco'] == "ND")
                    $ret[$c]['tco'] = "ND";

                If ($remito) {
                    //log_this('AAAAAA.log',"::::CASE REMITO");
                    If ($rs['tco'] == "RE") {
                        $nswR = true;
                        $valor = ($rs['anu'] == "A") ? 0 : number_format($rs['ipa'], 2, ',', '');
                        If ($rs['anu'] == "A") {
                            $ret[$c]['obs'] = "Remito Anulado";
                        }
                    } else {
                        $nswR = false;
                    }
                } else {
                    //log_this('AAAAAA.log',"::::CASE NOT REMITO");
                    If ($rs['tco'] == "RE") {    
                        $valor = ($rs['anu'] == "A") ? 0 : number_format($rs['ipa'], 2, ',', '');
                        $nswR = true;
                    } else {
                        //log_this('AAAAAA.log',"::::CASE NOT REMITO ELSE");
                        $nswR = false;
                    }
                }

                If ($rs['tco'] == "RE" && $rs['rec'] > 0) {

                    $ret[$c]["DEB"] = ($rs['anu'] == "A") ? '' : number_format($rs['ipa'], 2, ',', '');
                    If ($rs['anu'] == "A"):

                        $ret[$c]['obs'] = "Comp. Anulado";
                    else:
                        $dateFer = $rs['fer'] != NULL ? date_format($rs['fer'], 'd/m/yy') : "";
                        $ret[$c]['obs'] = "FT: " . substr(str_pad($rs['rec'], 8, "0", STR_PAD_LEFT), -5) . $dateFer;
                    endif;
                }



                if (in_array($rs['tco'], array('FT', 'ND', 'RE', 'SA', 'DI', 'CI', 'AN', 'PD', 'CE'))) {
                    //log_this('AAAAAA.log', " nco " . print_r($ret[$c]['ncNCO'], true) . "::::CASE 1");
                    $ret[$c]['DEB'] = ($rs['anu'] == "A") ? '' : number_format($rs['ipa'], 2, ',', '');
                    //log_this('AAAAAA.log',"RET DEBITO: " . print_r($ret[$c]['DEB'],TRUE));
                }

                //inc627800_V2
                //log_this("logquery.log",print_r($rs,true));
                if($remitoPrecioActual==1){
                    if (in_array($rs['tco'], array('RE'))) {
                        $debPrecioAct = $sql->query("select SUM(A.CAN*B.PreVen)as total from AMOVFACT A
                        INNER JOIN ARTICULOS B ON A.ART = B.CodArt AND A.RUB = B.CodRub
                        AND A.TIO = B.DetArt
                        where NCO = ".$rs['nco']." and SUC = ".$rs['suc']." and tco = 're'");
                        $ret[$c]['DEB'] = ($rs['anu'] == "A") ? '' : number_format($debPrecioAct[0]['total'], 2, ',', '');
                    }
                }

                if (( in_array($rs['tco'], array('FT', 'DI', 'ND', 'CI', 'AN', 'PD', 'CE')) && $rs['fpa'] == 2) || $rs['tco'] == "SA") {
                    // log_this('AAAAAA.log'," nco " . print_r($ret[$c]['ncNCO'], true) .  "::::CASE 2");
                    $valor = ($rs['anu'] == "A") ? 0 : $rs['ipa'];
                    if ($c > 0 && $ret[$c]['ncNCO'] != $ret[$c - 1]['ncNCO']){
                        $nDB = $nDB + floatval($valor);
                    } else if($c == 0){
                        $nDB = $nDB + floatval($valor);
                    }
                }

                if (in_array($rs['tco'], array('AC', 'NI', 'NC', 'RC', 'NI')) && $rs['fpa'] == 2) {
                    // log_this('AAAAAA.log',"::::CASE 3");
                    $valor = ($rs['anu'] == "A") ? 0 : number_format($rs['ipa'], 2, ',', '');
                    $ret[$c]['CRED'] = $valor;
                }

                if ($rs['tco'] == "RC" && $rs['fpa'] == 1) {
                    // log_this('AAAAAA.log'," nco " . print_r($ret[$c]['ncNCO'], true) .  "::::CASE 4");
                    $valor = ($rs['anu'] == "A") ? 0 : number_format($rs['ipa'], 2, ',', '');
                    $ret[$c]['CRED'] = $valor;
                }

                if (( ($rs['tco'] == "NC" || $rs['tco'] == "NI") && $rs['fpa'] == 1)) {
                    // log_this('AAAAAA.log'," nco " . print_r($ret[$c]['ncNCO'], true) .  "::::CASE 5");
                    $valor = ($rs['anu'] == "A") ? 0 : number_format($rs['ipa'], 2, ',', '');
                    $ret[$c]['CRED'] = $valor;
                }


                if (in_array($rs['tco'], array('AC', 'NI', 'NC', 'RC', 'NI')) && ( $rs['fpa'] == 2 || $rs['tco'] == "RC" )) {
                    If ($rs['fpa'] <> 1) {
                    // log_this('AAAAAA.log'," nco " . print_r($ret[$c]['ncNCO'], true) .  "::::CASE 6");
                        $valor = ($rs['anu'] == "A") ? 0 : $rs['ipa'];
                        $nCR = $nCR + $valor;
                    }
                }
                // Saldo //sumaTotalComprobantes  es el saldo_calc para cuenta madre
                $ndeb = myfloat($saldos['deb']) + abs(myfloat($nDB) + $saldos['sumaTotalComprobantes']);
                $ncre = myfloat($saldos['cre']) + abs(myfloat($nCR) + $saldos['sumaSaldoCalCredito']);

                $saldos['deb'] = myfloat($saldos['deb']);
                $saldos['cre'] = myfloat($saldos['cre']);
                $nDB = myfloat($nDB);
                $nCR = myfloat($nCR);

                if (($ndeb - $ncre ) >= 0) {
                    $nnSal = $ndeb - $ncre;
                }else{
                    // Saldo
                    $nnSal = myfloat($saldos['deb']) - myfloat($saldos['cre']) + $nDB - $nCR;
                }

//                $nswR = true; @@@@@@@@@@@@ Esto es el valor que se muestra por Remito de saldo
                If (!$nswR) {
                      // Formatear $nnSal a 2 decimales -- INC612281
                    $nnSal_formateado = number_format($nnSal, 2, '.', '');
                    $ret[$c]['SAL'] = $nnSal_formateado;
                }

                $nnSal = number_format($nnSal, 2, '.', '');

                If (in_array($rs['tco'], array('FT', 'NC', 'ND', 'DI', 'NI', 'CI', 'AN', 'PD')) || ($rs['tco'] == "SA" && $rs['rec'] > 0 )) {
                    //.col = 8
                    If ($rs['tco'] > 0) {
                        If ($rs['tco'] <> "NC") {
                            $ret[$c]['obs'] = "RC/NC:" . substr(str_pad($rs['rec'], 8, "0", STR_PAD_LEFT), -5) . date_format($rs['fer'], 'd/m/yy');
                        } Else {
                            $ret[$c]['obs'] = "CA:" . substr(str_pad($rs['rec'], 8, "0", STR_PAD_LEFT), -5) . date_format($rs['fer'], 'd/m/yy');
                        }
                    } ElseIf ($rs['far']) {
                        $ret[$c]['obs'] = "(Cancela Remitos)";
                    } ElseIf ($rs['tco'] == "FT" && $rs['rep'] > 0) {
                        $ret[$c]['obs'] = "Contado Pendiente";
                    } ElseIf ($rs['anu'] == "A") {
                        $ret[$c]['obs'] = "Comp. Anulado";
                    }
                }

                $ret[$c]['ven'] = "";

                if ($rs['fev']) {


                    if (($rs['fev'] >= $rs['fep']) && $rs['anu'] <> 'A') {

                        if (in_array($rs['tco'], array("FT", "NC", "PD", "SA", "AN", "CI", "NI", "ND", "DI"))) {
                            $ret[$c]['ven'] = date_format($rs['fev'], 'd/m/Y');
                        }
                    }
                }

                if ($rs['fpa'] <> 2 && $rs['tco'] <> "RC") {
                    $ret[$c]['obs'] = "(Contado)";
                }
                if ($rs['anu']=="A"){
                    $ret[$c]['obs']= "(Anulado)";
                }

            } else {
                $ret[$c] = "";
            }
                if($ret[$c]['tco_o'] != 'RE'){
                    if ($c > 0 && $ret[$c]['ncNCO'] == $ret[$c - 1]['ncNCO']){
                        if($ret[$c]['SAL'] > 0){
                            $nnSal =  $ret[$c]['SAL'];
                            $nnSal = $ret[$c]['SAL'] - $ret[$c]['DEB'];
                            $nnSal = number_format($nnSal, 2, ',', '');
                        }
                    }
                }
            //log_this('AAAAAA.log',"---------------------------------------------------");    
            $c++;
            //ACA ENTRA LA MODIFICACION DEL DUPLICADO
            // Aplicamos la consulta adaptada para HO o BO --inc631186_fix 
            if(FLAG_HO == false){
                if($rs['suc'] == 0 && $rs['tco'] == "RC"){
                    //log_this('AAAAAA.log',"IGUAL A CERO PERO CON PRECIO MAYOR A CERO " . print_r($c,TRUE));
                    $es_duplicado = $sql->query("SELECT * FROM ACOBYPAG where cli = ". $rs['cli'] ." and nco = ".substr($rs['nco'],2)." and tip = '". $rs['tip'] ."' and suc = ".substr($rs['nco'],0,2)." and tco = '". $rs['tco'] ."'");
                    //_logthis($sql->last_query());
                    if($es_duplicado){
                        unset($ret[$c - 1]);
                        $c--;
                    }
                }
            }else if(FLAG_HO == true){
                if($rs['suc'] == 0 && $rs['tco'] == "RC"){
                    $es_duplicado = $sql->query("SELECT * FROM ACOBYPAG where cod = ". $rs['cod'] ." and nco = ".substr($rs['nco'],2)." and tip = '". $rs['tip'] ."' and suc = ".substr($rs['nco'],0,2)." and tco = '". $rs['tco'] ."'");
                    //_logthis($sql->last_query());
                    if($es_duplicado){
                        unset($ret[$c - 1]);
                        $c--;
                    }
                }
            }      
        }
    } else {
        $nnSal = myfloat($saldos['deb']) - myfloat($saldos['cre']) + $nDB - $nCR;
        $nSalRPEL = myfloat($saldos['rpe']);
    }

    //log_this('AAAAAA.log',":::::::::::::::::CALCULOS::::::::::::::::::");
    //Incidencia inc560644, se suma valores de columna SALDO_CALC por parte de la funcion TraerSaldoAnteriorRC()
    $tot_deb = myfloat($saldos['deb']) + abs(myfloat($nDB));
    $tot_deb = number_format($tot_deb, 2, ',', '');
    //log_this('AAAAAA.log',"--TOT_DEB: " . print_r($tot_deb,TRUE) . " = " . print_r(myfloat($saldos['deb']),TRUE) . " + " . print_r(abs(myfloat($nDB)),TRUE));

    $tot_cre = myfloat($saldos['cre']) + abs(myfloat($nCR) + $saldos['sumaSaldoCalCredito']);
    $tot_cre = number_format($tot_cre, 2, ',', '');
    //log_this('AAAAAA.log',"--TOT_CRE: " . print_r($tot_cre,TRUE) . " = " . print_r(myfloat($saldos['cre']),TRUE) . " + " . print_r(abs(myfloat($nCR)),TRUE));
    //log_this('ZZZZZZZZZZZZZZZZZZ.log', 'FINAL $nnSal '. $nnSal. "\n" );

    $tot_sal = $nnSal;
    //Se lo controla asi para que el resultado de obs, sea correcto en su valor decimal
    if($nSalRPEL == 0){
        $valor = $nnSal;
    }else{
        $valor  = $nnSal + $nSalRPEL;
        $valor = number_format(myfloat($valor), 2, ',', '');
    }
    $tot_deuda = "(Deuda: " . $valor . ")";
    ////log_this('AAAAAA.log',"--TOT_DEUDA: " . print_r($tot_deuda,TRUE) . " = " . print_r($nnSal,TRUE) . " + " . print_r($nSalRPEL,TRUE));
    $nSalRPEL = number_format($nSalRPEL, 2, ',', '');
    ////log_this('AAAAAA.log',"nSalRPEL (RTOS PEND TOT): " . print_r($nSalRPEL,TRUE));
    $fech = date("Y-m-d", $hasta);
    $dias = 1;
    $fech = strtotime("$fech");
    $tot_hasta = date('d', $fech) . " " . get_mes(date('n', $fech)) . " " . date('Y', $fech);

    $ndeb = number_format($ndeb, 2, ',', '');
    $ncre = number_format($ncre, 2, ',', '');
    
    $totales = array(
        "hasta" => $tot_hasta,
        "deb" => $ndeb,
        "cre" => $ncre,
        "sal" => $tot_sal,
        "rtos" => $nSalRPEL,
        "obs" => $tot_deuda
    );
    $saldos["deb"] = number_format(myfloat($saldos["deb"]), 2, ',', '');
    $saldos["cre"] = number_format(myfloat($saldos["cre"]), 2, ',', '');
    $saldos["sal"] = number_format(myfloat($saldos["sal"]), 2, ',', '');
    $saldos["rpe"] = number_format(myfloat($saldos["precioAnteriorRpe"]), 2, ',', '');
    //Ret es cada calculo por remito, grada fila
    //log_this('ret.log', " ret ". print_r($ret,TRUE) . "\n"); 
    if($orden == 0){
        //Se rota el array a proposito, para que respete el orden de mas nuevo a mas antiguo, pero mantenga los calculos correctos [inc554672]
        $ret = array_reverse($ret);
    }
    //log_this('SALDOSSSSSSS.log', 'saldos ' . print_r($saldos,true) . ' ret ' . print_r($ret,true)  . 'TOTALES'. print_r($totales,true). "\n");
    foreach ($ret as &$row) {
        // Verifica si $row['DET1'] existe y no está vacío
        if (isset($row['DET1']) && !empty($row['DET1'])) {
            $stringValidar = $row['DET1'];
            $string_validado = str_replace("&", " ", $stringValidar);
            $row['DET1'] = $string_validado;
        }
    }

    return array("saldos" => $saldos, "ret" => $ret, "totales" => $totales);
}

function get_datos_cliente($desde, $hasta, $usuario) {
    global $sql;
    date_default_timezone_set('America/Argentina/Buenos_Aires');

    $sql->select("ifnull(SUM(ipa),0) AS imp ");
    FLAG_HO == false ? $sql->where("CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' AND fpa=2  ") : //EMP
    $sql->where(" hos<>'S' and CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' AND fpa=2  ");
    FLAG_HO == false ? $sql->where(" cli = " . $usuario) : $sql->where(" cod = " . $usuario);
    $sql->where(" tco IN('FT','ND','DI','SA','CI','AN','PD')");
    $data['aa'] = $sql->get_tabla("acobypag");

    $sql->select("ifnull(SUM(ipa),0) AS imp ");
    FLAG_HO == false ? $sql->where("CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' AND fpa=2  ") : //EMP
    $sql->where(" hos<>'S' and CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' AND fpa=2  ");
    $sql->where(" tco IN('NC','NI') ");
    FLAG_HO == false ? $sql->where(" cli = " . $usuario) : $sql->where(" cod = " . $usuario);
    $data['bb'] = $sql->get_tabla("acobypag");

    $sql->select("SUM(ipa) AS imp ");
    FLAG_HO == false ?  $sql->where("CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' ") : //EMP
    $sql->where(" hos<>'S' and CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' ");
    $sql->where(" ((tco IN('AC','RC') AND FPA=2) OR (TCO='RC' AND FPA <> 1)) ");
    $data['cc'] = $sql->get_tabla("acobypag");

    $sql->select("SUM(ipa) AS imp ");
    FLAG_HO == false ? $sql->where(" cli = " . $usuario) : $sql->where(" cod = " . $usuario);
    FLAG_HO == false ? $sql->where("CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' AND fpa=2  ") : //EMP
    $sql->where(" hos<>'S' and CONVERT(CHAR(10),fep,111)<" . date("Y/m/d", $desde) . " AND anu<>'A' AND fpa=2  ");
    $sql->where(" tco='RE' AND ((rec = 0 AND fer IS NULL) OR (rec <> 0 AND CONVERT(CHAR(10),fer,111) > " . date("Y/m/d", $desde));
    $data['dd'] = $sql->get_tabla("acobypag");
    return $data;
}

function get_deudas($usuario, $desde) {
    $sql = new sqldata();
    date_default_timezone_set('America/Argentina/Buenos_Aires');

    $sql->select("fep,tip,tco,suc,nco,ipa,sal,fpa,rec,fer,pla,lug,fev,rep");
    FLAG_HO == FALSE ? $sql->where("anu<>'A' AND cli=" . $usuario) : //EMP
    $sql->where("hos<>'S' and anu<>'A' AND cli=" . $usuario);
    $sql->where(" AND fpa=2 ");
    $sql->where(" (rec=0 OR tco='AC' or (tco = 're' and rec > 0 and CONVERT(CHAR(10),fer,111) > " . date("Y/m/d", $desde));
    $sql->get_tabla("acobypag");
}

function TraerSaldoAnteriorRC($FechaDelPeriodo, $FechaHasta, $CodigoDeCliente,$EMP, $sucursales, $remitoPrecioActual = 0) {
    // log_this('parametroSaldoAnterior.log', 'fechaDelPeriodo '. print_r($FechaDelPeriodo,true). ' fechaHasta '. print_r($FechaHasta,true) . ' codigoDeCliente '. print_r($CodigoDeCliente,true) . ' emp '. print_r($EMP,true). ' sucursales '. print_r($sucursales,true). "\n" );
    global $sql;
    if(FLAG_HO == FALSE){
        foreach ($sucursales as $sucursal) {
            // log_this('valorSucursales.log', print_r($sucursal,TRUE));
        }
    }else{
        $sucursales = 0;
    }

    //log_this('AAAAAA.log',":::::::::::::::TRAER SALDO ANTERIOR::::::::::::::::");
    $EMP != "" ? $EMP : $EMP = "";
    //Como es BO, no hay que consultar por empresa -- INC608461
    if ($EMP == -1 || FLAG_HO == TRUE){
        //log_this('AAAAAA.log',":::: ENTRA EN EMPRESAS -1 " . "\n");
        $whereEMP = "";
    }else{
        //log_this('AAAAAA.log',":::: ENTRA EN EMPRESAS ELSE " . "\n");
        $whereEMP = " AND EMP= " . $EMP . " ";
    }
    //log_this('AAAAAA.log',":::: EMP FINAL ". $whereEMP . "\n");

    $teVend = ""; 
    $cFecFin = "'" . $FechaDelPeriodo . "'";
    $cFecHas = "'" . $FechaHasta . "'";
    FLAG_HO == false ? $Sql = "SELECT SUM(ipa) AS imp " .
            "FROM acobypag " .
            "WHERE CONVERT(CHAR(10),fep,111)<" . $cFecFin . " " . //EMP
            "AND (cli=" . $CodigoDeCliente . " or cta=".$CodigoDeCliente.") " .
            "AND anu<>'A' AND fpa=2 " .
            "AND tco IN('FT','ND','DI','SA','CI','AN','PD') $whereEMP":
    $Sql = "SELECT SUM(ROUND(ipa,2))-SUM(ROUND(SALDO_CALC,2)) AS imp " .
            "FROM acobypag " .
            "WHERE hos<>'S' and CONVERT(CHAR(10),fep,111)<" . $cFecFin . " " .
            "AND cod=" . $CodigoDeCliente . " " .
            "AND anu<>'A' AND fpa=2 " .
            "AND tco IN('FT','LI','ND','DI','SA','CI','AN','PD','CE','DE','LP','LG','PD','LA','LH')" . $whereEMP;
    $q1 = $sql->query($Sql);
    $nSalDeb = 0;
    if ($q1)
        $nSalDeb = decs($q1[0]["imp"], 2);
    //log_this('AAAAAA.log',"Q1 (pasa a ser nSalDeb): " . print_r($q1,TRUE));
    FLAG_HO == false ? $Sql = " SELECT SUM(ipa) AS imp " .
            " FROM acobypag " .
            " WHERE CONVERT(CHAR(10),fep,111)<" . $cFecFin . " " . //EMP
            " AND cli=" . $CodigoDeCliente . " " .
            " AND anu<>'A' AND fpa=2 " .
            " AND tco IN ('NC','NI') $whereEMP " :
        $Sql = " SELECT SUM(ROUND(ipa,2))-SUM(ROUND(SALDO_CALC,2)) AS imp " .
            " FROM acobypag " .
            " WHERE hos<>'S' and  CONVERT(CHAR(10),fep,111)<" . $cFecFin . " " .
            " AND cod=" . $CodigoDeCliente . " " .
            " AND anu<>'A' AND fpa=2 " .
            " AND ((TCO IN('AC','RC','RM','NC','NI','NE') AND FPA=2) OR (TCO IN('RC','RM') AND FPA <> 1))" . $whereEMP;
    $q2 = $sql->query($Sql);
    $nSalCre = 0;
    if ($q2)
        $nSalCre = decs($q2[0]["imp"], 2);
    //log_this('AAAAAA.log',"Q2 (pasa a ser nSalCre): " . print_r($q2,TRUE));
    FLAG_HO == false ?     $Sql = " SELECT SUM(ipa) AS imp " .
            " FROM acobypag " .
            " WHERE CONVERT(CHAR(10),fep,111)<" . $cFecFin . " " . //EMP
            " AND cli=" . $CodigoDeCliente . " " .
            " AND anu<>'A' " .
            " AND ((tco IN('AC','RC') AND FPA=2) OR (TCO='RC' AND FPA <> 1)) $whereEMP ": 
    $Sql = " SELECT SUM(ipa) AS imp " .
            " FROM acobypag " .
            " WHERE hos<>'S' and CONVERT(CHAR(10),fep,111)<" . $cFecFin . " " .
            " AND cod=" . $CodigoDeCliente . " " .
            " AND anu<>'A' " .
            " AND ((tco IN('AC','RC') AND FPA=2) OR (TCO='RC' AND FPA <> 1))" . $whereEMP;

    $q3 = $sql->query($Sql);
    if ($q3) {
        //$nSalCre = decs($nSalCre, 2) + decs($q3[0]["imp"], 2);
        $nSalCre = decs($nSalCre, 2);
        //log_this('AAAAAA.log',"Q3 (con la suma del Q2 anterior pasa a ser el nuevo nSalCre): " . print_r($q3,TRUE));
    }

    //VERIFICO SI SE TRAE REMITOS A PRECIO ACTUAL --inc627800_V2
    $nSalRpe = 0;

    if($remitoPrecioActual == 1){
        //log_this("myquerylog.log","query 4: ".$sql->last_query());
        FLAG_HO == FALSE ? $Sql = " SELECT * " .
        " FROM acobypag " .
        " WHERE " . //EMP
        " cli=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND rec = 0  $whereEMP ":
        $Sql = " SELECT * " .
        " FROM acobypag " .
        " WHERE hos<>'S' " .
        " AND cod=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND ((rec = 0 AND fer IS NULL) OR (rec <> 0 AND CONVERT(CHAR(10),fer,111) > " . $cFecHas . ")) " . $whereEMP;
    
        $q4 = $sql->query($Sql);
        $resultTot = 0;
        foreach($q4 as $row){
            $acumulador = $sql->query("select SUM(A.CAN*B.PreVen)as total from AMOVFACT A
            INNER JOIN ARTICULOS B ON A.ART = B.CodArt AND A.RUB = B.CodRub AND A.TIO = B.DetArt
            where NCO = ".$row['NCO']." and SUC = ".$row['SUC']." and tco = 're'");
            $resultTot+=$acumulador[0]['total'];
        }
    
        if ($q4){
            $nSalRpe = decs($resultTot, 2);
        }
    }
    else{
        FLAG_HO == FALSE ? $Sql = " SELECT SUM(ipa) AS imp " .
        " FROM acobypag " .
        " WHERE " . //EMP
        " cli=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND rec = 0  $whereEMP ":
        $Sql = " SELECT SUM(ipa) AS imp " .
        " FROM acobypag " .
        " WHERE hos<>'S' " .
        " AND cod=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND ((rec = 0 AND fer IS NULL) OR (rec <> 0 AND CONVERT(CHAR(10),fer,111) > " . $cFecHas . ")) " . $whereEMP;

        $q4 = $sql->query($Sql);
        //log_this('ConsultaSalRep.log', $sql->last_query());
        if ($q4){
            $nSalRpe = decs($q4[0]["imp"], 2);
        }
    }

    //CALCULO REMITOS PENDIENTES CON PRECIO ANTERIOR --inc627800_V2
    $precioAnteriorRpe = 0;

    if($remitoPrecioActual == 1){
        //log_this("myquerylog.log","query 4: ".$sql->last_query());
        FLAG_HO == FALSE ? $Sql = " SELECT * " .
        " FROM acobypag " .
        " WHERE " . //EMP
        " cli=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND rec = 0  $whereEMP ":
        $Sql = " SELECT * " .
        " FROM acobypag " .
        " WHERE hos<>'S' " .
        " AND cod=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND ((rec = 0 AND fer IS NULL and CONVERT(CHAR(10),fep,111) < " . $cFecFin . ")) " . $whereEMP;
    
        $q4 = $sql->query($Sql);
        $resultTot = 0;
        foreach($q4 as $row){
            $acumulador = $sql->query("select SUM(A.CAN*B.PreVen)as total from AMOVFACT A
            INNER JOIN ARTICULOS B ON A.ART = B.CodArt AND A.RUB = B.CodRub AND A.TIO = B.DetArt
            where NCO = ".$row['NCO']." and SUC = ".$row['SUC']." and tco = 're'");
            $resultTot+=$acumulador[0]['total'];
        }
    
        if ($q4){
            $precioAnteriorRpe = decs($resultTot, 2);
        }
    }
    else{
        FLAG_HO == FALSE ? $Sql = " SELECT SUM(ipa) AS imp " .
        " FROM acobypag " .
        " WHERE " . //EMP
        " cli=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND rec = 0  $whereEMP ":
        $Sql = " SELECT SUM(ipa) AS imp " .
        " FROM acobypag " .
        " WHERE hos<>'S' " .
        " AND cod=" . $CodigoDeCliente . " " .
        " AND anu<>'A' AND fpa=2 " .
        " AND tco='RE' " .
        " AND ((rec = 0 AND fer IS NULL and CONVERT(CHAR(10),fep,111) < " . $cFecFin . ")) " . $whereEMP;

        $q4 = $sql->query($Sql);
        //log_this('ConsultaSalRep.log', $sql->last_query());
        if ($q4){
            $precioAnteriorRpe = decs($q4[0]["imp"], 2);
        }
    }

    FLAG_HO == FALSE ? 
    $Sql =   "SELECT SUM (SALDO_CALC) AS SALDO_CALC FROM ACOBYPAG WHERE CLI = ". $CodigoDeCliente ." AND ANU <> 'A' AND FPA=2 AND 
    CONVERT(CHAR(10),FEP,111)< " . $cFecFin . " AND ((TCO IN('AC','RC','RM') AND FPA=2) OR (TCO IN('RC','RM') AND FPA<>1))"
    :
    $Sql =  "SELECT SUM (SALDO_CALC) AS SALDO_CALC FROM ACOBYPAG WHERE COD =" . $CodigoDeCliente . " AND ANU !='A' AND FPA = 2  AND TCO = 'FT'";

    $q5 = $sql->query($Sql); 
    if($q5){
        $suma_Saldo_Cal_Credito =+ decs($q5[0]["SALDO_CALC"], 2);
        $suma_Saldo_Cal_Credito = decs($suma_Saldo_Cal_Credito, 2);
        $nSalCre = decs($nSalCre, 2);
    }
    //INC560644, se aplican los calculos con la columna SALDO_CALC para los saldos totales
    FLAG_HO == FALSE ? 
    $Sql = "SELECT SUM (SALDO_CALC) AS SUM_TOTAL_COMPROBANTES FROM ACOBYPAG WHERE CLI = ". $CodigoDeCliente ." AND CONVERT(CHAR(10), fep, 111) BETWEEN " . $cFecFin . " AND " . $cFecHas. " AND ANU != 'A' AND FPA = 2  AND ((TCO IN('AC','RC','RM') AND FPA=2) OR (TCO IN('RC','RM') AND FPA<>1))"
    :
    $Sql =  "SELECT SUM (SALDO_CALC) AS SUM_TOTAL_COMPROBANTES FROM ACOBYPAG WHERE COD =" . $CodigoDeCliente . " AND CONVERT(CHAR(10), fep, 111) BETWEEN " . $cFecFin . " AND " . $cFecHas. " AND ANU != 'A' AND FPA = 2  AND ((TCO IN('AC','RC','RM') AND FPA=2) OR (TCO IN('RC','RM') AND FPA<>1))";
    
    $q6 = $sql->query($Sql);
    if($q5 && $q6){
        $sumaTotalComprobantes =+ decs($q6[0]["SUM_TOTAL_COMPROBANTES"], 2);
        $sumaTotalComprobantes = decs($sumaTotalComprobantes, 2);
    }

    //log_this('AAAAAA.log',"Q4 (pasa a ser nSalRpe): " . print_r($q4,TRUE));
    $nSaldif = $nSalDeb - $nSalCre;
    //log_this('AAAAAA.log',"nSaldif: " . print_r($nSaldif,TRUE) . " = " . print_r($nSalDeb,TRUE) . " - " . print_r($nSalCre,TRUE));
   $nSalDeb = number_format($nSalDeb, 2);
   $nSalCre = number_format($nSalCre, 2);
   $nSalRpe = number_format($nSalRpe, 2);
   $precioAnteriorRpe = number_format($precioAnteriorRpe, 2);

    $rtn = array(
        'deb' => $nSalDeb,
        'cre' => $nSalCre,
        'sal' => $nSaldif,
        'rpe' => $nSalRpe,
        'precioAnteriorRpe' => $precioAnteriorRpe,
        'sumaTotalComprobantes' => $sumaTotalComprobantes,
        'sumaSaldoCalCredito' => $suma_Saldo_Cal_Credito
    );
    // log_this('AAAAAA.log',"RTN: " . print_r($rtn,TRUE) . "\n");
    return $rtn;
}

function get_detalle($cod, $tco, $tip, $suc, $nco, $emp) {
    global $sql;
    date_default_timezone_set('America/Argentina/Buenos_Aires');
    FLAG_HO == false ? $Sql = "SELECT * FROM TICOMP WHERE COD = '" . $tco . "'" : $Sql = "SELECT * FROM TICOMP WHERE ID = '" . $tco . "'";
    $q1 = $sql->query($Sql);
    if ($q1) {
        FLAG_HO == false ? $laTip = $q1[0]['NOM'] : $laTip = $q1[0]['NOMBRE'];
    }

    //inicializar
    $laNGR = "";
    $arr_pie = array();
    $arr_det = array();
    
    $laNUF = str_pad($suc, 5, "0", STR_PAD_LEFT) . "-" . str_pad($nco, 8, "0", STR_PAD_LEFT);

    $swtipo = "";
    if ($tco <> "RC" && $tco <> "AC" && $tco <> "CH") {
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        FLAG_HO == false ? $Sql = "SELECT * FROM AMAEFACT WHERE CLI = " . $cod . " AND TCO = '" . $tco . "' AND TIP = '" . $tip . "' AND SUC = " . $suc . " AND NCO = " . $nco :
            $Sql = "SELECT * FROM AMAEFACT WHERE COD = " . $cod . " AND TCO = '" . $tco . "' AND TIP = '" . $tip . "' AND SUC = " . $suc . " AND NCO = " . $nco;
        $swtipo = "F";
    } elseif ($tco == "RC" || $tco == "AC") {
        FLAG_HO == false ? $Sql = "SELECT * FROM ARECIBOS WHERE CLI = " . $cod . " AND TCO = 'RC' AND TIP = '" . $tip . "' AND SUC = " . $suc . " AND NCO = " . $nco : $Sql = "SELECT * FROM ARECIBOS WHERE CLI = " . $cod . " AND TCO = 'RC' AND TIP = '" . $tip . "' AND PVE = " . $suc . " AND NCO = " . $nco;
        $swtipo = "R";
    } elseif ($tco == "CH") {
        $Sql = "SELECT * FROM TVALOR WHERE BCO = " . $suc . " AND  NUM = " . $nco;
        $swtipo = "C";
    }


    $qCom = $sql->query($Sql);

    if ($qCom) {
        //$laFec = $qCom[0]['FEC']->date('dd/mm/YY');
        $laFec = $qCom[0]['FEC']->format('d/m/Y');
        $laTip_o = $qCom[0]['TIP'];
        $laTco_o = $qCom[0]['TCO'];
        $lato = $qCom[0]['ATO'];
        $laanu = $qCom[0]['ANU'];
    } else {
        return -1;
    }

    //Forma de Pago
    if ($swtipo == "R") {
        $laMAS = "";
    } else {
        FLAG_HO == false ? $Sql = "SELECT * FROM FDPAGO WHERE COD = " . $qCom[0]['FPA'] : $Sql = "SELECT * FROM FDPAGO WHERE ID = " . $qCom[0]['FPA'];
        $qFpa = $sql->query($Sql);
        FLAG_HO == false ?$laMAS = "PAGO: " . trim($qFpa[0]['NOM']) : $laMAS = "PAGO: " . trim($qFpa[0]['NOMBRE']);
    }

    //Datos Cliente
    //$Sql = "SELECT C.*, I.NOMBRE FROM CLIENTES as C join IVA as I on C.IVA = I.COD WHERE C.COD = " . $cod;
    /*
    SELECT C.*, I.NOMBRE FROM CLIENTES as C join IVA as I on C.IVA = I.ID WHERE C.COD = 170
    */
    if(FLAG_HO == false){
        $Sql = "SELECT C.*, I.NOMBRE FROM CLIENTES as C join IVA as I on C.IVA = I.COD WHERE C.COD = " . $cod;
    }elseif(FLAG_HO == true){
        $Sql = "SELECT C.*, I.NOMBRE FROM CLIENTES as C join IVA as I on C.IVA = I.ID WHERE C.COD = " . $cod;
    }
    
    $qCli = $sql->query($Sql);
    $laDIR = 0;

    if ($qCli) {
        if ($swtipo == "R") {
            $laNOM = "(" . str_pad($cod, 5, "0", STR_PAD_LEFT) . ") " . utf8_encode($qCli[0]['NOM']);
            /*Anteriormente se encontraba asi pero generaba un error. Se cambia a la misma forma del else.
            $tmp = "(" . str_pad($cod, 5, "0", STR_PAD_LEFT) . ") " . utf8_encode($qCli[0]['NOM']);
            $tmp1 = str_pad($tmp, 272, "&nbsp;", STR_PAD_RIGHT);
            $tmp2 = $tmp1 . "Asiento: " . $lato;
            $laNOM = $tmp2;
             */
        } else {
            $laNOM = "(" . str_pad($cod, 5, "0", STR_PAD_LEFT) . ") " . utf8_encode($qCli[0]['NOM']);
        }
        if(FLAG_HO == false){
            $laDIR = utf8_encode(trim($qCli[0]['DOM']) . ", " . trim($qCli[0]['LOC']) . ", " . trim($qCli[0]['PVC']));
        }else{
            $laDIR = utf8_encode(trim($qCli[0]['DOM']) . ", " . trim($qCli[0]['LOC']) . ", " . trim($qCli[0]['PCI']));
        }
                
        $laDOM = utf8_encode(trim($qCli[0]['DOM']));
        $laLOC = utf8_encode(trim($qCli[0]['LOC']));
        if(FLAG_HO == false){
            $laPROV = utf8_encode(trim($qCli[0]['PVC']));
        }else{
            $laPROV = utf8_encode(trim($qCli[0]['PCI']));
        }

        $laIVA = utf8_encode($qCli[0]['NOMBRE']);

        if(FLAG_HO == false){
            $laCUI = $qCli[0]['CUI'];
        }else{
            $laCUI = $qCli[0]['CUIT'];
        }

    } else {
        $laNOM = "Publico General";
        $laDIR = "-";
        $laDOM = "-";
    }

    //Datos Detalle Factura
    //laMAS = laMAS & "    Items: " & Format(N + 1, "00")
    //file_put_contents('swtipo.log', print_r($swtipo,1));

    if ($swtipo == 'F') {
        $Sql = "SELECT * FROM AMOVFACT WHERE TIP = '" . $tip . "' AND TCO = '" . $tco . "' AND SUC = " . $suc . " AND NCO = " . $nco . " ORDER BY ORD";
        $qDet = $sql->query($Sql);

//        $arr_det = array();
        if ($qDet) {
            
            $cont = 0;
            foreach ($qDet as $det) {
                FLAG_HO == false ? $arr_det[$cont]["cod"] = $det['SEC'] . "-" . str_pad($det['ART'], 5, "0", STR_PAD_LEFT) : $arr_det[$cont]["cod"] = $det['COD'] . "-" . str_pad($det['ART'], 5, "0", STR_PAD_LEFT);
                $arr_det[$cont]["det"] = $det['TIO'];
                if ($tip == 'A') {
                    if (floatval($det['NET']) == '0')
                        $arr_det[$cont]["uni"] = "";
                    else
                        $arr_det[$cont]["uni"] = number_format($det['NET'], 2, ',', '');
                }else{
                    if (floatval($det['PUN']) == '0')
                        $arr_det[$cont]["uni"] = "";
                    else
                        $arr_det[$cont]["uni"] = number_format($det['PUN'], 2, ',', '');
                }

                if ($tip == 'A') {
                    $arr_det[$cont]["imp"] = number_format($det['NET'] * $det['CAN'], 2, ',', '');
                }else{
                    $arr_det[$cont]["imp"] = number_format($det['PUN'] * $det['CAN'], 2, ',', '');
                }
                    
                $arr_det[$cont]["pun"] = number_format($det['PUN'], 2, ',', '');
                
                if (floatval($arr_det[$cont]["imp"]) == '0')
                    $arr_det[$cont]["imp"] = "";

                if (floatval($det['CAN']) == '0')
                    $arr_det[$cont]["can"] = "";
                else
                    $arr_det[$cont]["can"] = number_format($det['CAN'], 1, ',', '');

                $arr_det[$cont]["tasa"] = $det['TAS_IVA'];
                $arr_det[$cont]["impint"] = $det['IMI'] + $det['IMI2'] + $det['IMI3'];
                if(FLAG_HO == false){
                    $arr_det[$cont]["iva"] = $det['IRI'];
                }elseif(FLAG_HO == true){
                    $arr_det[$cont]["iva"] = $det['IVA'];
                }
                $cont++;
            }
        }
    }else {
        //BOLETA
        FLAG_HO == false ? $Sql = "SELECT * FROM ADETREC WHERE TIP = '" . $tip . "' AND SUC = " . $qCom[0]['SUC'] . " AND TCO = 'RC' AND NCO = " . $nco . " ORDER BY LOP,COM " : $Sql = "SELECT * FROM ADETREC WHERE TIP = '" . $tip . "' AND PVE = " . $qCom[0]['PVE'] . " AND TCO = 'RC' AND NCO = " . $nco . " ORDER BY LOP,COM ";
        $qDet = $sql->query($Sql);
        
//        $arr_det = array();
        if ($qDet) {
            $cont = 0;
            $nTotLiq = 0;
            $nTotPag = 0;
            foreach ($qDet as $det) {
                $arr_det[$cont]["can"] = $det['FEC']->format('d/m/Y');
                if (substr($det['COM'], 0, 2) == 're') {
                    $arr_det[$cont]["det"] = substr($det['COM'], 0, -15);
                } else {
                    $arr_det[$cont]["det"] = $det['COM'];
                }

                if ($det['LOP'] == 'L') {
                    $arr_det[$cont]["laimp"] = number_format($det['IMP'], 2, ',', '');
                    $arr_det[$cont]["cod"] = "   ";
//                    $arr_det[$cont]["cod"] = "&nbsp";

                    if (strtoupper(substr($det['COM'], 0, 2)) == "CA" || strtoupper(substr($det['COM'], 0, 2)) == "NC") {
                        $nTotLiq = $nTotLiq - $det['IMP'];
                    } else {
                        $nTotLiq = $nTotLiq + $det['IMP'];
                    }
                } else {
                    $arr_det[$cont]["cod"] = number_format($det['IMP'], 2, ',', '');
//                    $arr_det[$cont]["laimp"] = "&nbsp";
                    $arr_det[$cont]["laimp"] = "   ";
                    $nTotPag = $nTotPag + $det['IMP'];
                }
                $cont++;
            }

            $nTotLiq = number_format($nTotLiq, 2, ',', '');
            $nTotPag = number_format($nTotPag, 2, ',', '');
        }
    }
    //MAESTRO
    if ($swtipo == "F") {
        If ($qCom[0]['NET'] + $qCom[0]['NEE'] != 0) {
            $laNGR = number_format($qCom[0]['NET'] + $qCom[0]['NEE'], 2, ',', '');
        } else {
            $laNGR = "0,00";
        }
        If ($qCom[0]['IRI'] != 0) {
            $laIRI = number_format($qCom[0]['IRI'], 2, ',', '');
        } else {
            $laIRI = "0,00";
        }
        If ($qCom[0]['IRS'] != 0) {
            $laIRS = number_format($qCom[0]['IRIS'], 2, ',', '');
        } else {
            $laIRS = "0,00";
        }
        If ($qCom[0]['IMI'] != 0) {
            $laIITC = number_format($qCom[0]['IMI'], 2, ',', '');
        } else {
            $laIITC = "0,00";
        }
        If ($qCom[0]['IMI2'] != 0) {
            $laIIDC = number_format($qCom[0]['IMI2'], 2, ',', '');
        } else {
            $laIIDC = "0,00";
        }
        If ($qCom[0]['IMI3'] != 0) {
            $laITV = number_format($qCom[0]['IMI3'], 2, ',', '');
        } else {
            $laITV = "0,00";
        }
        If ($qCom[0]['APR'] != 0) {
            $laDESC = number_format($qCom[0]['APR'], 2, ',', '');
        } else {
            $laDESC = "0.00";
        }

        $laCANC = "";
        if ($qCom[0]['FAR'] && $qCom[0]['ANU'] != "A") {
            if ($qCom[0]['TCO'] != "NC") {
                $laCANC = "Esta Factura Cancela Remitos";
            } else {
                $laCANC = "Esta NC, cancela Factura de Cuenta Corriente";
            }
        } else {
            $laCANC = "";
        }

        If ($qCom[0]['PER_IVA'] != 0) {
            $laPIV = number_format($qCom[0]['PER_IVA'], 2, ',', '');
        } else {
            $laPIV = "0,00";
        }
        If ($qCom[0]['PER'] != 0) {
            $laPIV = number_format($qCom[0]['PER'], 2, ',', '');
        } else {
            $laPIV = "0,00";
        }
        If ($qCom[0]['TOT'] != 0) {
            $laTOT = number_format($qCom[0]['TOT'], 2, ',', '');
        } else {
            $laTOT = "0,00";
        }
        If ($qCom[0]['DTO'] != 0) {
            $laDESC = number_format($qCom[0]['DTO'], 2, ',', '');
        }
        //  else {
        //     $laDESC = "0.00";
        // }

        $lacae = $qCom[0]['CAE'];
        $feccae = strtotime($qCom[0]['FECCAE']);
        $feccae = date("d/m/Y", $feccae);
        $lafeccae = $feccae;
        
        $arr_pie = array(
            "langr" => $laNGR,
            "lairi" => $laIRI,
            "lairs" => $laIRS,
            "laiitc" => $laIITC,
            "laiidc" => $laIIDC,
            "laitv" => $laITV,
            "ladesc" => $laDESC,
            "lapiv" => $laPIV,
            "latot" => $laTOT,
            "lacanc" => $laCANC,
            "lacae" => $lacae,
            "lafeccae" => $lafeccae
        );
    } else {
        //MAESTRO BOLETA (SUMAR TOTALES)

        $arr_pie = array(
            "liqtotal" => isset($nTotLiq) ? $nTotLiq : $nTotLiq = '',
            "pagtotal" => isset($nTotPag) ? $nTotPag : $nTotPag = ''
        );
    }

    $laNOM = utf8_encode($laNOM);
    
    $arr_cond = "SELECT DET1, DET3, DET2 FROM DET_CONDUCT_COMP WHERE TCO = '$tco' AND TIP = '$tip' AND SUC = $suc AND NCO = $nco AND (DET1!='' OR DET3!='') ";
    $arr_cond = $sql->query($arr_cond);
    // _logthis($sql->last_query());
    if ($arr_cond) {
        $arr_cond = $arr_cond[0];
        preg_match('/V:(.*)P:(.*)R:(.*)U:(.*)VA:(.*)/', $arr_cond['DET3'], $vehiculo);
        $patente = array();
        $patente = explode('M:', $arr_cond['DET2']);
        //log_this("AAA.log",print_r($patente,TRUE));
        $patenteRegistrada = '';
        if (isset($vehiculo['2'])) {
            $patenteRegistrada = $vehiculo['2'];
        }
        else if (isset($patente[0])) {
            if($patente[0] == 'PATENTE:')
            {
                $patenteRegistrada = '';
            }else{
                $patenteRegistrada = $patente[0];
            }
            
        }
        //Con la funcionalidad de htmlspecialchars, evitamos que se impriman caracteres como '&'. INC608461
        $arr_cond = array(
            'CONDUCTOR' => str_replace("**", "", htmlspecialchars($arr_cond['DET1'])),
            'V_MARCA' => isset($vehiculo[1]) ? $vehiculo[1] : '',
            'V_PATENTE' => ($patenteRegistrada) ? $patenteRegistrada : '',
            'V_KM' => isset($vehiculo[3]) ? $vehiculo[3] : ''
        );
    }

    if(FLAG_HO == FALSE){
        $arr_empresa = $sql->query("SELECT A.EMP, A.NOM, A.DOM, A.TEL, A.CUI, A.NIB, A.NES, A.STI, A.IAC, B.NOMBRE FROM APAREMP as A join IVA as B on A.IVA = B.COD where A.EMP = $emp");
    } else {
        $arr_empresa = $sql->query("SELECT A.NOM, A.DIR as DOM, A.TEL, A.CUI, A.NIB, A.NES, A.STI, A.IAC, B.NOMBRE FROM APAREMP as A join IVA as B on A.IVA = B.ID");
    }
    $rtn = array(
        "tipo" => $swtipo,
        "fecha" => $laFec,
        "tip" => $laTip,
        "suc" => $suc,
        "numf" => $laNUF,
        "laanu" => $laanu,
        "tip_o" => $laTip_o,
        "tco_o" => $laTco_o,
        "ato_o" => $lato,
        "lanom" => $laNOM,
        "ladir" => $laDIR,
        "ladom" => $laDOM,
        "laloc" => $laLOC,
        "laprov" => $laPROV,
        "lamas" => $laMAS,
        "laiva" => $laIVA,
        "lacui" => $laCUI,
        "arr_detalle" => $arr_det,
        "arr_conductor" => $arr_cond,
        "arr_pie" => $arr_pie,
        "arr_empresa" => $arr_empresa,
    );
    // log_this('ZZZZZZZZZ.log', print_r($rtn, true). "\n");
    return $rtn;
}

function analisis_deuda($usuario, $desde, $hasta, $cc, $remito, $contado, $anulada, $orden, $empresa, $remitoPrecioActual) {
    global $sql;
    date_default_timezone_set('America/Argentina/Buenos_Aires');
    $sql_cod = " select nom, grp from clientes where cod=" . $usuario;
    $cli_dat = $sql->query($sql_cod);
    //log_this('AAAAAA.log',":::::::::::::ANALISIS DEUDA:::::::::::::");
    //log_this('AAAAAA.log',"HASTA: " . print_r(date("Y/m/d", $hasta),TRUE));
    if($remito && $contado && $anulada){
        //log_this('AAAAAA.log',"REMITO & CONTADO & ANULADA");
        $sql->where("a.TCO IN('AC','RC','FT','NC','NI','DI','ND','TI','CI','AN','RE') "); 
    }
    if (!$anulada) {
        //log_this('AAAAAA.log',"NO ANULADA");
        $sql->where("a.anu<>'A' ");
    }

    if (!$contado) {
        //log_this('AAAAAA.log',"NO CONTADO");
        FLAG_HO == false ? $sql->where("NOT (a.fpa IN(1))") : $sql->where("NOT (a.TCO IN('RC','FT','NC','NI','DI','ND','TI','CI','AN') AND a.FPA IN(1,3,4,5))");
    }

    if(FLAG_HO == false){
        if (!$remito) {
            //log_this('AAAAAA.log',"NO REMITO");
            $sql->where("NOT (a.TCO='RE' AND a.rec<>0)");
            $sql->select("AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
            $sql->group_by("AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
        } 

        if ($remito){
            $sql->select("D.DET1,D.DET3,AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
            $sql->group_by("D.DET1,D.DET3,AP.NOM,AP.EMP,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cli,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
        }
    } else {
        if (!$remito) {
            //log_this('AAAAAA.log',"NO REMITO");
            $sql->where("NOT (a.TCO='RE' AND a.rec<>0)");
            $sql->select("A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cod,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
            $sql->group_by("A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cod,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
        } 

        if ($remito){
            $sql->select("D.DET1,D.DET3,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cod,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO) as ncNCO ");
            $sql->group_by("D.DET1,D.DET3,A.fev,A.fep,A.tip,A.tco,A.suc,A.nco,A.ipa,A.sal,A.fpa,A.rec,A.fer,A.pla,A.lug,A.far,A.cod,A.anu,A.rep, cast( A.TIP as varchar(2)) + ' ' + REPLICATE('0',4-LEN(A.suc)) + Convert(varchar,A.suc) + '-' + REPLICATE('0',8-LEN(A.NCO)) + Convert(varchar,A.NCO)");
        }
    }
    
    if(FLAG_HO == false){
        //log_this('AAAAAA.log',"FLAG_HO = FALSE");
        $sql->JOIN("DET_CONDUCT_COMP D","A.NCO = D.NCO and A.TCO = D.TCO and A.CLI = D.CLI and A.SUC = D.SUC", "LEFT OUTER");
        $sql->join("APAREMP AP","AP.EMP = A.EMP");
        $sql->where("anu<>'A' and fpa=2");
        if($cli_dat[0]['grp'] == 1){
            $sql->where("(A.cli = " . $usuario . " or A.cta = " . $usuario . ")");   
        } else {
            $sql->where("A.cli = " . $usuario);
        }
        if (isset($empresa) && $empresa != -1) {
            $sql->where("a.tco<>'RC' and AP.EMP = $empresa");
        }
    }else{
        //log_this('AAAAAA.log',"FLAG_HO = TRUE");
        
        $sql->JOIN("DET_CONDUCT_COMP D","A.NCO = D.NCO and A.TCO = D.TCO and A.SUC = D.SUC and A.COD = D.CLI", "LEFT OUTER");
        $sql->where("A.hos<>'S' and anu<>'A' and a.fpa=2 AND A.cod = " . $usuario);
    }
    $sql->where(" ( A.rec=0 OR A.tco='AC' or ( A.tco='re' AND A.rec > 0 and CONVERT(CHAR(10),A.fer,111) >= '" . date("Y/m/d", $hasta) . "' ) )");
    $sql->where("A.tco<>'RC'");
    if ($orden == 0) {
        $sql->order_by("A.fep", $ord = "desc");
        }
    if ($orden == 1) {
        $sql->order_by("A.fep", $ord = "asc");
    }
    $prev = $sql->get_tabla("acobypag A");
    
    $nSalRPEL = "0";
    $nSalRpe = 0;
    $nnSal = 0;
    if($prev){
        foreach ($prev as $tData) {
            $sucursales[] = $tData['suc'];
        }
    }
    $nSalRPEL = $nSalRpe;

    $saldos = TraerSaldoAnteriorRC(date("Y/m/d", $desde), date("Y/m/d", $hasta), $usuario,$empresa,$sucursales, $remitoPrecioActual);
    if($saldos){
        $nSalRPEL = myfloat($saldos["rpe"]);
    }

    $ret = array();
    $c = 0;
    $nDB = 0;
    $nCR = 0;
    if ($prev) {

        $saldos = array(
            'tipo' => 'analisis',
            'deb' => '0',
            'cre' => '0',
            'sal' => '0',
            'rpe' => '0'
        );

        $fech = date("Y-m-d", $desde);
        $dias = 1;
        $fech = strtotime("$fech -$dias day");
        $saldos["desde"] = date('d', $fech) . " " . get_mes(date('n', $fech)) . " " . date('Y', $fech);

        $sql_cod = " select nom from clientes where cod=" . $usuario;
        $cli_dat = $sql->query($sql_cod);

        $saldos["cliente"]["cta"] = $usuario;
        $saldos["cliente"]["cli"] = str_replace("&","Y",utf8_encode($cli_dat[0]["nom"]));

        foreach ($prev as $rs) {
            $nswR = true;
            $nswIR = true;
            if ($rs['tco'] == "RE" && $rs['rec'] == 0 && !$remito) {
                $nswIR = false;
            }

            if ($nswIR) {

                $ret[$c]['fep'] = $rs['fep'];
                $ret[$c]['ncNCO'] = $rs['ncNCO'];
                $ret[$c]['obs'] = "";
                $ret[$c]['DEB'] = "";
                $ret[$c]['CRED'] = "";
                $ret[$c]['SAL'] = "";

                $ret[$c]['tco_o'] = $rs['tco'];
                $ret[$c]['tip_o'] = $rs['tip'];
                $ret[$c]['suc_o'] = $rs['suc'];
                $ret[$c]['nco_o'] = $rs['nco'];
                $ret[$c]['cod_o'] = FLAG_HO == false ? $rs['cli'] : $rs['cod'];
                FLAG_HO == false ? $ret[$c]['NOM'] = $rs['NOM'] : '';
                FLAG_HO == false ? $ret[$c]['EMP'] = $rs['EMP'] : '';
                if ($rs['fpa'] == 2 && $rs['tco'] != "RC") {
                    $ret[$c]['fpa'] = "CC";
                } elseif ($rs['tco'] == "RC") {
                    $ret[$c]['fpa'] = "";
                } else {
                    $ret[$c]['fpa'] = "CO";
                }
                $ret[$c]['tco'] = $rs['tco'];

                If ($remito) {
                    $ret[$c]['DET1'] = $rs['DET1'];
                    $ret[$c]['DET3'] = $rs['DET3'];
                    If ($rs['tco'] != "AC" && $rs['rec'] == 0) {
                        $nswR = true;
                    } else {
                        $nswR = false;
                    }
                }

                if (in_array($rs['tco'], array('FT', 'ND', 'RE', 'DI', 'CI', 'SA', 'AN', 'PD','CE'))) {
                    $ret[$c]['DEB'] = number_format($rs['ipa'], 2, ',', '');
                }

                //inc627800_V2
                //log_this("logmeuquery.log",print_r($rs,true));
                if($remitoPrecioActual==1){
                    if (in_array($rs['tco'], array('RE'))) {
                        $debPrecioAct = $sql->query("select SUM(A.CAN*B.PreVen)as total from AMOVFACT A
                        INNER JOIN ARTICULOS B ON A.ART = B.CodArt AND A.RUB = B.CodRub
                        AND A.TIO = B.DetArt
                        where NCO = ".$rs['nco']." and SUC = ".$rs['suc']." and tco = 're'");
                        $ret[$c]['DEB'] = ($rs['anu'] == "A") ? '' : number_format($debPrecioAct[0]['total'], 2, ',', '');
                    }
                }

                //@@@@@@ DEFINE LOS COMPROBANTES QUE SE TIENEN EN CUENTA PARA SALDO TOTAL DEBITO
                if ((in_array($rs['tco'], array('FT', 'CI', 'SA')) && $rs['fpa'] == 2) || in_array($rs['tco'], array('ND', 'DI', 'AN', 'PD','CE'))) {
                    if($remito && $ret[$c]['ncNCO']){
                        if ($c > 0 && $ret[$c]['ncNCO'] != $ret[$c - 1]['ncNCO']){
                            $nDB = $nDB + $rs['ipa'];
                        } else if($c == 0){
                            $nDB = $nDB + $rs['ipa'];
                        }
                    } else {
                        $nDB = $nDB + $rs['ipa'];
                    }
                    
                }

                if (in_array($rs['tco'], array('AC', 'NI', 'NC', 'RC', 'NI'))) {
                    if ($rs['tco'] == "AC") {
                        $nCR = $nCR + $rs['sal'];
                        $ret[$c]['CRED'] = number_format($rs['sal'], 2, ',', '');
                    } else {
                        $nCR = $nCR + $rs['ipa'];
                        $ret[$c]['CRED'] = number_format($rs['ipa'], 2, ',', '');
                    }
                }

                $nnSal = floatval($saldos['deb']) - floatval($saldos['cre']) + floatval($nDB) - floatval($nCR);
                If ($nswR == true) {
                    $ret[$c]['SAL'] = number_format($nnSal, 2, ',', '');
                }

                If (in_array($rs['tco'], array('FT', 'CI', 'ND', 'DI', 'NC', 'NI', 'AN', 'PD')) && ( $rs['rec'] > 0 )) {
                    $ret[$c]['obs'] = substr(str_pad($rs['rec'], 8, "0", STR_PAD_LEFT), 0, 8) . date_format($rs['fer'], 'd/m/yy');
                } else {
                    If ($rs['tco'] == "FT" && $rs['rep'] > 0) {
                        $ret[$c]['obs'] = "Contado Pendiente";
                    }
                }
                $ret[$c]['ven'] = "";
                if ($rs['fev']) {
                    if ($rs['fev'] >= $rs['fep']) {
                        if (in_array($rs['tco'], array("FT", "NC", "CI", "PD", "ND", "NI", "AN", "SA", "DI"))) {
                            $ret[$c]['ven'] = date_format($rs['fev'], 'd/m/Y');
                        }
                    }
                }
            } else {
                $ret[$c] = "";
            }
            $c++;
            if (($rs['tco'] == "AC" && floatval($rs['sal']) == 0)) {
                unset($ret[$c - 1]);
                $c--;
            }
        }

        $tot_deb = floatval($saldos['deb']) + abs(floatval($nDB));
        $tot_deb = number_format($tot_deb, 2, ',', '');

        $tot_cre = floatval($saldos['cre']) + abs(floatval($nCR));
        $tot_cre = number_format($tot_cre, 2, ',', '');
        $tot_sal = number_format($nnSal, 2, ',', '');
        $valor = number_format($nnSal + $nSalRPEL, 2, ',', '');
        $tot_deuda = "(Deuda: " . $valor . ")";
        $nSalRPEL = number_format($nSalRPEL, 2, ',', '');

        $fech = date("Y-m-d", $hasta);
        $dias = 1;
        $fech = strtotime("$fech");
        $tot_hasta = date('d', $fech) . " " . get_mes(date('n', $fech)) . " " . date('Y', $fech);

        $totales = array(
            "hasta" => $tot_hasta,
            "deb" => $tot_deb,
            "cre" => $tot_cre,
            "sal" => $tot_sal,
            "rtos" => $nSalRPEL,
            "obs" => $tot_deuda
        );
    //log_this('AAAAAA.log',"TOTALES: " . print_r($totales,TRUE) . "\n");   
    //log_this('ZZZ.log',"TOTALES: " . print_r($totales,TRUE) . "\n");  
    //log_this('ANALISIS_DEUDA.log', 'saldos ' . print_r($saldos,true) . ' ret ' . print_r($ret,true)  . 'TOTALES'. print_r($totales,true). "\n"); 
    foreach ($ret as &$row) {
        // Verifica si $row['DET1'] existe y no está vacío
        if (isset($row['DET1']) && !empty($row['DET1'])) {
            $stringValidar = $row['DET1'];
            $string_validado = str_replace("&", " ", $stringValidar);
            $row['DET1'] = $string_validado;
        }
    }
    return array("saldos" => $saldos, "ret" => $ret, "totales" => $totales);
    }else{/*Se agrega este else, ya que si en la base no encuentra nada, devuelva todo en 0.*/
        $ret = array();
        $saldos = array(
            'tipo' => 'analisis',
            'deb' => '0',
            'cre' => '0',
            'sal' => '0',
            'rpe' => '0'
        );
        $totales = array(
            "hasta" => "",
            "deb" => 0,
            "cre" => 0,
            "sal" => 0,
            "rtos" => 0,
            "obs" => ""
        );
        $sql_cod = " select nom from clientes where cod=" . $usuario;
        $cli_dat = $sql->query($sql_cod);
        $saldos["cliente"]["cta"] = $usuario;
        $saldos["cliente"]["cli"] = str_replace("&","Y",utf8_encode($cli_dat[0]["nom"]));
        //log_this('ANALISIS_DEUDA.log', 'saldos ' . print_r($saldos,true) . ' ret ' . print_r($ret,true)  . 'TOTALES'. print_r($totales,true). "\n"); 
        foreach ($ret as &$row) {
            // Verifica si $row['DET1'] existe y no está vacío
            if (isset($row['DET1']) && !empty($row['DET1'])) {
                $stringValidar = $row['DET1'];
                $string_validado = str_replace("&", " ", $stringValidar);
                $row['DET1'] = $string_validado;
            }
        }
        return array("saldos" => $saldos, "ret" => $ret, "totales" => $totales);
    }
}
function get_empresas(){
    global $sql;
    date_default_timezone_set('America/Argentina/Buenos_Aires');
    $sql->select("NOM,EMP");
    $empresa = $sql->get_tabla("APAREMP");
    if($empresa){
        return $empresa;
    }else{
        echo "-1";
    }
}

function get_remitos($SUC,$NCO, $TIP){
    global $sql;
    date_default_timezone_set('America/Argentina/Buenos_Aires');
    $i = 0;
    $remi = array();
    $remitos =$remitos = $sql->query("SELECT EMP, EMP_RE, TIP, TCO, SUC, NCO, TIP_F, TCO_F, SUC_F, NCO_F 
    FROM AFACTRE 
    WHERE SUC_F=$SUC AND NCO_F=$NCO AND TIP_F='$TIP' AND TCO_F='FT' 
    GROUP BY EMP, EMP_RE, TIP, TCO, SUC, NCO, TIP_F, TCO_F, SUC_F, NCO_F");
    // log_this("AAAAA.log",$NCO." - ".$SUC);
    foreach ($remitos as $rem) {
        $sql->where("SUC=".$rem['SUC']." and NCO=".$rem['NCO']." and tip='r'");
        $remi[$i] = $sql->get_tabla("AMAEFACT");
        // log_this("AAAAA.log",$remi[$i][0]['TOT']);
        $i++; 
    }
    
    return $remi;
}
?>