<?php

die();
// CONTAB
{
    function ctas_deta($pctas)
    {
        include ('../_cfg/config.php');
        $pctas = trim($pctas);
        if (strlen($pctas) < 5)
        {
            return false;
        }
        $sql_ctas = 'select * from ctas0 where ctas_codigo like "' . $pctas . '%" and ctas_status!="X" order by ctas_codigo';
        $res_ctas = msql_query($sql_ctas, $link_vcrx);
        if (msql_num_rows($res_ctas) == 1)
        {
            return true;
        }
        return false;
    }
     

    function gen_103($panio, $pmes)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        $razsoc = r_fiel('enti', $cfg_ruc);

        $f104html = '';

        $f104html .= '<html xmlns="http://www.w3.org/1999/xhtml">';
        $f104html .= '<head>';
        $f104html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $f104html .= '<title>' . 'F103-' . $cfg_empr . '-' . $panio . '-' . $pmes . '</title>';
        $f104html .= '<style type="text/css">';
        $f104html .= 'p.saltodepagina{page-break-before: always;}';
        $f104html .= '</style>';
        /* <p class="saltodepagina" /></p>	 */
        //   $saltopagina='<p class="saltodepagina" /></p>';
        //   $saltopagina='<hr>';
        $f104html .= '<div style="font-weight:bolder; font-size:200%;">FORMULARIO 103</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:150%;">RUC : ' . $cfg_ruc . '</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:150%;">RAZON SOCIAL :' . $razsoc . '</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:100%;">AÑO : ' . $panio . '</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:100%;">MES : ' . $pmes . '</div>';
        $f104html .= '<hr>';

        $f104html .= file_get_contents('../../_lib/f103.html');

        //   $cinfo=0;
        //   while(mb_stristr($f104html,'info_outline'))
        //   {
        //     $infoout=$f104html;
        //     $lblpos1=strrpos(substr($infoout,0,strpos($infoout,'info_outline')),'<label');
        //     $infoout=substr($infoout,$lblpos1);
        //     $infoout=substr($infoout,0,strpos($infoout,'</label>')+8);
        //     $f104html=str_replace($infoout,'',$f104html);
        //     $cinfo++;
        //     if($cinfo>5){break;}
        //   }
        

        //   $f104html=str_replace('>VENTAS</','><span style="font-weight:bolder; font-size:150%;">VENTAS</span></',$f104html);
        //   $f104html=str_replace('>COMPRAS</','>'.$saltopagina.'<span style="font-weight:bolder; font-size:150%;">COMPRAS</span></',$f104html);
        //   $f104html=str_replace('>RETENCIONES</','>'.$saltopagina.'<span style="font-weight:bolder; font-size:150%;">RETENCIONES</span></',$f104html);
        

        $xml = new DomDocument("1.0", "UTF-8");
        $xml->xmlStandalone = true;

        $f104 = $xml->appendChild($xml->createElement('detallesDeclaracion'));

        $casillero = '101';
        $concepto = 'MES';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $pmes));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        $casillero = '102';
        $concepto = 'AÑO';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $panio));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        $casillero = '201';
        $concepto = 'RUC';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $cfg_ruc));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        $casillero = '202';
        $concepto = 'RAZON SOCIAL';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $razsoc));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        //RETENCIONES
        
        {
            $sql_f104 = '';

            $sql_f104 .= 'select ';
            $sql_f104 .= 'cair,';
            $sql_f104 .= 'sum(brta) as sbrta,';
            $sql_f104 .= 'sum(rrta) as srrta,';
            $sql_f104 .= 'status ';
            $sql_f104 .= 'from retp12 ';
            $sql_f104 .= 'where status!="O" ';
            $sql_f104 .= 'and substring(cair,1,1) in("3","4") ';
            $sql_f104 .= 'and fanio="' . $panio . '" and fmes="' . $pmes . '" ';
            $sql_f104 .= 'group by cair ';
            $sql_f104 .= 'order by cair ';

            //       explain_sql($sql_f104);
            $res_f104 = msql_query($sql_f104, $link_vcrx);
            while ($aso_f104 = msql_fetch_assoc($res_f104))
            {
                $casillero = $aso_f104['cair'];
                $valor = $aso_f104['sbrta'];
                if ($valor != 0 and !empty($casillero))
                {
                    $concepto = sri_concepto($f104html, $casillero);
                    $f104html = gen_104html($f104html, $casillero, $valor);
                    $
                    {
                        $casillero
                    } = $f104->appendChild($xml->createElement('detalle', number_format($valor, 2, '.', '')));
                    $
                    {
                        $casillero
                    }->setAttribute("concepto", $concepto);
                    $
                    {
                        $casillero
                    }->setAttribute("casillero", $casillero);
                }

                $casillero = $casillero + 50;
                $valor = $aso_f104['srrta'];
                if ($valor != 0 and !empty($casillero))
                {
                    $concepto = sri_concepto($f104html, $casillero);
                    $f104html = gen_104html($f104html, $casillero, $valor);
                    $
                    {
                        $casillero
                    } = $f104->appendChild($xml->createElement('detalle', number_format($valor, 2, '.', '')));
                    $
                    {
                        $casillero
                    }->setAttribute("concepto", $concepto);
                    $
                    {
                        $casillero
                    }->setAttribute("casillero", $casillero);
                }
            }

        }

        $xml3 = $rutadoc . 'F103_' . $panio . $pmes . '_' . $cfg_empr . '.xml';
        $xml->formatOut = true;
        $xml->save($xml3);

        $xmlfile = file_get_contents($xml3);
        $xmlfile = xml_chr13($xmlfile);
        file_put_contents($xml3, $xmlfile);

        $html3 = $rutadoc . 'F103_' . $panio . $pmes . '_' . $cfg_empr . '.html';
        file_put_contents($html3, $f104html);

        return;
    }

    function gen_104($panio, $pmes)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        $razsoc = r_fiel('enti', $cfg_ruc);

        $f104html = '';

        $f104html .= '<html xmlns="http://www.w3.org/1999/xhtml">';
        $f104html .= '<head>';
        $f104html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $f104html .= '<title>' . 'F104-' . $cfg_empr . '-' . $panio . '-' . $pmes . '</title>';
        $f104html .= '<style type="text/css">';
        $f104html .= 'p.saltodepagina{page-break-before: always;}';
        $f104html .= '</style>';
        /* <p class="saltodepagina" /></p>	 */
        //   $saltopagina='<p class="saltodepagina" /></p>';
        //   $saltopagina='<hr>';
        $f104html .= '<div style="font-weight:bolder; font-size:200%;">FORMULARIO 104</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:150%;">RUC : ' . $cfg_ruc . '</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:150%;">RAZON SOCIAL :' . $razsoc . '</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:100%;">AÑO : ' . $panio . '</div>';
        $f104html .= '<div style="font-weight:bolder; font-size:100%;">MES : ' . $pmes . '</div>';
        $f104html .= '<hr>';

        $f104html .= file_get_contents('../../_lib/f104.html');

        $cinfo = 0;
        while (mb_stristr($f104html, 'info_outline'))
        {
            $infoout = $f104html;
            $lblpos1 = strrpos(substr($infoout, 0, strpos($infoout, 'info_outline')) , '<label');
            $infoout = substr($infoout, $lblpos1);
            $infoout = substr($infoout, 0, strpos($infoout, '</label>') + 8);
            $f104html = str_replace($infoout, '', $f104html);
            $cinfo++;
            if ($cinfo > 5)
            {
                break;
            }
        }

        $f104html = str_replace('>VENTAS</', '><span style="font-weight:bolder; font-size:150%;">VENTAS</span></', $f104html);
        $f104html = str_replace('>COMPRAS</', '>' . $saltopagina . '<span style="font-weight:bolder; font-size:150%;">COMPRAS</span></', $f104html);
        $f104html = str_replace('>RETENCIONES</', '>' . $saltopagina . '<span style="font-weight:bolder; font-size:150%;">RETENCIONES</span></', $f104html);

        $xml = new DomDocument("1.0", "UTF-8");
        $xml->xmlStandalone = true;

        $f104 = $xml->appendChild($xml->createElement('detallesDeclaracion'));

        $casillero = '101';
        $concepto = 'MES';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $pmes));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        $casillero = '102';
        $concepto = 'AÑO';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $panio));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        $casillero = '201';
        $concepto = 'RUC';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $cfg_ruc));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        $casillero = '202';
        $concepto = 'RAZON SOCIAL';
        $
        {
            $casillero
        } = $f104->appendChild($xml->createElement('detalle', $razsoc));
        $
        {
            $casillero
        }->setAttribute("concepto", $concepto);
        $
        {
            $casillero
        }->setAttribute("casillero", $casillero);

        //   echo $casillero;
        //     $sql_f104='';
        //     $sql_f104.='select fanio,fmes,"401" as casillero, sum(case when docu like "FC%" then tsubtiva else 0 end) as valor ';
        //     $sql_f104.='from vtas12 where status!="O" and fanio="'.$panio.'" and fmes="'.$pmes.'" ';
        //     $sql_f104.='union';
        //     $sql_f104.='select fanio,fmes,"411" as casillero, sum(case when docu like "FC%" or docu like "NC%" then tsubtiva else 0 end) as valor  ';
        //     $sql_f104.='from vtas12 where status!="O" and fanio="'.$panio.'" and fmes="'.$pmes.'" ';
        //     $sql_f104='';
        //     $sql_f104.='select fanio,fmes,';
        //     $sql_f104.='case when docu like "FC%" then "401" ';
        //     $sql_f104.='else case when docu like "FC%" then "401" ';
        //     $sql_f104.='sum(case when docu like "FC%" then tsubtiva else 0 end) as valor, ';
        //     $sql_f104.='status ';
        //     $sql_f104.='from vtas12 where status!="O" and fanio="'.$panio.'" and fmes="'.$pmes.'" ';
        //     $sql_f104.='union';
        //     $sql_f104.='select fanio,fmes,"411" as casillero, sum(case when docu like "FC%" or docu like "NC%" then tsubtiva else 0 end) as valor  ';
        //     $sql_f104.='from vtas12 where status!="O" and fanio="'.$panio.'" and fmes="'.$pmes.'" ';
        //VTAS
        
        {
            $sql_f104 = '';

            $sql_f104 .= 'select *,';
            $sql_f104 .= 'c401+c405 as c409, ';
            $sql_f104 .= 'c411+c415 as c419, ';
            $sql_f104 .= 'c421 as c429, ';
            $sql_f104 .= 'c421 as c482, ';
            $sql_f104 .= '0 as fin ';
            $sql_f104 .= 'from(';

            $sql_f104 .= 'select ';
            $sql_f104 .= 'sum(case when docu like "FC%" then tsubtiva else 0 end) as c401, ';
            $sql_f104 .= 'sum(case when docu like "FC%" or docu like "NC%" then tsubtiva else 0 end) as c411, ';
            $sql_f104 .= 'sum(case when docu like "FC%" or docu like "NC%" then tiva else 0 end) as c421, ';
            $sql_f104 .= 'sum(case when docu like "FC%" then tsubtiva0 else 0 end) as c405, ';
            $sql_f104 .= 'sum(case when docu like "FC%" or docu like "NC%"  then tsubtiva0 else 0 end) as c415, ';

            $sql_f104 .= 'status ';
            $sql_f104 .= 'from vtas12 ';
            $sql_f104 .= 'where status!="O" ';
            $sql_f104 .= 'and fanio="' . $panio . '" and fmes="' . $pmes . '" ';

            $sql_f104 .= ') as cas ';

            //       explain_sql($sql_f104);
            $res_f104 = msql_query($sql_f104, $link_vcrx);
            for ($ccol = 0;$ccol < msql_num_fields($res_f104);$ccol++)
            {
                $casillero1 = msql_field_name($res_f104, $ccol);
                $valor = msql_result($res_f104, 0, $casillero1);
                if ($valor != 0 and !empty($casillero1))
                {
                    $casillero = substr(msql_field_name($res_f104, $ccol) , 1);
                    $concepto = sri_concepto($f104html, $casillero);
                    $f104html = gen_104html($f104html, $casillero, $valor);
                    $
                    {
                        $casillero
                    } = $f104->appendChild($xml->createElement('detalle', number_format($valor, 2, '.', '')));
                    $
                    {
                        $casillero
                    }->setAttribute("concepto", $concepto);
                    $
                    {
                        $casillero
                    }->setAttribute("casillero", $casillero);
                }
            }
        }

        // COMP
        
        {

            $sql_f104 = '';

            $sql_f104 .= 'select *,';
            $sql_f104 .= 'c500+c506+c507+c508 as c509, ';
            $sql_f104 .= 'c510+c516+c517+c518 as c519, ';
            $sql_f104 .= 'c520 as c529, ';
            $sql_f104 .= '0 as fin ';
            $sql_f104 .= 'from(';

            $sql_f104 .= 'select ';
            $sql_f104 .= 'sum(case when docu in("FP10","FP03") and enti_rise=0 then tsubtiva else 0 end) as c500, ';
            $sql_f104 .= 'sum(case when (docu in("FP10","FP03") or docu like "NP%") and enti_rise=0 then tsubtiva else 0 end) as c510, ';
            $sql_f104 .= 'sum(case when (docu in("FP10","FP03") or docu like "NP%") and enti_rise=0 then tiva else 0 end) as c520, ';

            //importaciones
            $sql_f104 .= 'sum(case when docu="FP15" then tsubt else 0 end) as c506, ';
            $sql_f104 .= 'sum(case when docu="FP15" then tsubt else 0 end) as c516, ';

            //501.511.521 activo fijo
            $sql_f104 .= 'sum(case when docu like "FP%" and enti_rise=0 then tsubtiva0 else 0 end) as c507, ';
            $sql_f104 .= 'sum(case when (docu like "FP%" or docu like "NP%") and enti_rise=0  then tsubtiva0 else 0 end) as c517, ';

            $sql_f104 .= 'sum(case when docu like "FP%" and enti_rise=1 then tsubtiva0 else 0 end) as c508, ';
            $sql_f104 .= 'sum(case when (docu like "FP%" or docu like "NP%") and enti_rise=1  then tsubtiva0 else 0 end) as c518, ';

            $sql_f104 .= 'status ';
            $sql_f104 .= 'from comp12 ';
            $sql_f104 .= 'where status!="O" ';
            $sql_f104 .= 'and fanio="' . $panio . '" and fmes="' . $pmes . '" ';
            $sql_f104 .= 'and docu not like "FP9%" ';

            $sql_f104 .= ') as cas';
            //       explain_sql($sql_f104);
            $res_f104 = msql_query($sql_f104, $link_vcrx);

            for ($ccol = 0;$ccol < msql_num_fields($res_f104);$ccol++)
            {
                $casillero1 = msql_field_name($res_f104, $ccol);
                $valor = msql_result($res_f104, 0, $casillero1);
                if ($valor != 0 and !empty($casillero1))
                {
                    $casillero = substr(msql_field_name($res_f104, $ccol) , 1);
                    $concepto = sri_concepto($f104html, $casillero);
                    $f104html = gen_104html($f104html, $casillero, $valor);
                    $
                    {
                        $casillero
                    } = $f104->appendChild($xml->createElement('detalle', number_format($valor, 2, '.', '')));
                    $
                    {
                        $casillero
                    }->setAttribute("concepto", $concepto);
                    $
                    {
                        $casillero
                    }->setAttribute("casillero", $casillero);
                }
            }
        }

        // RETP
        
        {

            $sql_f104 = '';

            $sql_f104 .= 'select *,';
            $sql_f104 .= 'c721+c723+c725+c727+c729 as c799, ';
            //       $sql_f104.='c411+c415 as c419, ';
            $sql_f104 .= '0 as fin ';
            $sql_f104 .= 'from(';

            $sql_f104 .= 'select ';
            $sql_f104 .= 'sum(case when puni=10 then riva else 0 end) as c721, ';
            $sql_f104 .= 'sum(case when puni=20 then riva else 0 end) as c723, ';
            $sql_f104 .= 'sum(case when puni=30 then riva else 0 end) as c725, ';
            $sql_f104 .= 'sum(case when puni=50 then riva else 0 end) as c727, ';
            $sql_f104 .= 'sum(case when puni=70 then riva else 0 end) as c729, ';
            $sql_f104 .= 'sum(case when puni=100 then riva else 0 end) as c731, ';
            $sql_f104 .= 'status ';
            $sql_f104 .= 'from retp12 ';
            $sql_f104 .= 'where status!="O" ';
            $sql_f104 .= 'and fanio="' . $panio . '" and fmes="' . $pmes . '" ';
            $sql_f104 .= ') as cas';
            //     explain_sql($sql_f104);
            $res_f104 = msql_query($sql_f104, $link_vcrx);

            for ($ccol = 0;$ccol < msql_num_fields($res_f104);$ccol++)
            {
                $casillero1 = msql_field_name($res_f104, $ccol);
                $valor = msql_result($res_f104, 0, $casillero1);
                if ($valor != 0 and !empty($casillero1))
                {
                    $casillero = substr(msql_field_name($res_f104, $ccol) , 1);
                    $concepto = sri_concepto($f104html, $casillero);
                    $f104html = gen_104html($f104html, $casillero, $valor);
                    $
                    {
                        $casillero
                    } = $f104->appendChild($xml->createElement('detalle', number_format($valor, 2, '.', '')));
                    $
                    {
                        $casillero
                    }->setAttribute("concepto", $concepto);
                    $
                    {
                        $casillero
                    }->setAttribute("casillero", $casillero);
                }
            }
        }

        $xml3 = $rutadoc . 'F104_' . $panio . $pmes . '_' . $cfg_empr . '.xml';
        $xml->formatOut = true;
        $xml->save($xml3);

        $xmlfile = file_get_contents($xml3);
        $xmlfile = xml_chr13($xmlfile);
        file_put_contents($xml3, $xmlfile);

        $html3 = $rutadoc . 'F104_' . $panio . $pmes . '_' . $cfg_empr . '.html';
        file_put_contents($html3, $f104html);

        return;
    }

    function gen_104html($fhtml, $casillero, $valor)
    {
        $oldvalue = $fhtml;
        $oldvalue = substr($oldvalue, strpos($oldvalue, '>' . $casillero . '<'));
        $oldvalue = substr($oldvalue, strpos($oldvalue, '<div'));
        $oldvalue = substr($oldvalue, 0, strpos($oldvalue, '</div>'));

        $newvalue = str_replace('value="0.00"', 'value="' . number_format($valor, 2) . '"', $oldvalue);
        $fhtml = str_replace($oldvalue, $newvalue, $fhtml);
        return $fhtml;
    }

    function sri_concepto($formulario, $casillero)
    {
        $concepto = $formulario;
        $concepto = substr($concepto, strpos($concepto, '>' . $casillero . '<'));
        $concepto = substr($concepto, strpos($concepto, 'id="concepto'));
        $concepto = substr($concepto, 12, 10);
        $concepto = substr($concepto, 0, strrpos($concepto, '"'));
        return $concepto;
    }

    function gen_ats1($panio,$pmes,$psixm='')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');
         
         if($cfg_empr=='cqsa'){$psixm=1;}
         if($cfg_empr=='chmj'){$psixm=1;}
         
         $pmes1=$pmes;
         $pmes2=$pmes;
         if(!empty($psixm))
         {
              if($pmes>=1 and $pmes<=6) {$pmes1='01';$pmes2='06';}
              if($pmes>=7 and $pmes<=12){$pmes1='07';$pmes2='12';}
         }

        $sql_total = sql_total('comp');
        $sql_comp = 'select * from comp12 ';
        $sql_comp .= 'where status!="O" ';
        $sql_comp .= 'and fanio="' . $panio . '" and fmes>="' . $pmes1 . '"  and fmes<="' . $pmes2 . '" ';
        $sql_comp .= 'and docu_tico*1>0 and docu_tico is not null ';
        if(strtoupper($cfg_empr)=='HG01')
        {
        $sql_comp .= 'and docu not like "NP%" ';
        }
        $sql_comp = str_replace('select *', 'select *,' . $sql_total, $sql_comp);
        $sql_comp .= ' group by enti,fecha,numero,idnum1 ';
        $sql_comp .= ' order by enti,fecha,numero,idnum1 ';
         
        $res_comp = msql_query($sql_comp, $link_vcrx);

        $sql_total = sql_total('vtas');
        $sql_vtas = 'select * from vtas12 ';
        $sql_vtas .= 'where status!="O" ';
        $sql_vtas .= 'and fanio="' . $panio . '" and fmes>="' . $pmes1 . '"  and fmes<="' . $pmes2 . '" ';
        $sql_vtas .= 'and docu_tico!="41" ';
        $sql_vtas .= 'and tipoemi!="E" ';
        //   $sql_vtas.='and substring(claveacc,24,1)!="2" ';
        //   $sql_vtas.=' and enti like "0992124857%" ';
        //   $sql_vtas.=' and enti like "77%" ';
        $sql_vtas = str_replace('select *', 'select *,' . $sql_total, $sql_vtas);
        $sql_vtast = $sql_vtas;
        $sql_vtase = $sql_vtas;
        $sql_vtaso = $sql_vtas;

        $sql_vtaso = str_replace('!="O"', '="O"', $sql_vtaso);
//         $sql_vtaso = str_replace('!="O"', '="O" and ptoe<"001101"', $sql_vtaso);

        $sql_vtas .= ' group by substring(enti,1,10) ';
        $sql_vtas .= ' order by substring(enti,1,10) ';
        $sql_vtase .= ' group by substring(ptoe,1,3) ';
        $sql_vtaso .= ' group by idnum1 ';

        $res_vtas = msql_query($sql_vtas, $link_vcrx);
        $res_vtast = msql_query($sql_vtast, $link_vcrx);
        $res_vtase = msql_query($sql_vtase, $link_vcrx);
        $res_vtaso = msql_query($sql_vtaso, $link_vcrx);

        $stsubtiva0 = msql_result($res_vtast, 0, 'stsubtiva0');
        $stsubtiva = msql_result($res_vtast, 0, 'stsubtiva');

        $totalvtas = (int)$stsubtiva + (int)$stsubtiva0;

        $razsoc = r_fiel('enti', $cfg_ruc);
        $razsoc = str_replace('.', '', $razsoc);

        $xml = new DomDocument("1.0", "UTF-8");
        //   $xml->xmlStandalone = true;
        //   $xml->appendChild($xml->createElement('h1',date('H:i:s')));
        $anexo = $xml->appendChild($xml->createElement('iva'));
        $anexo->appendChild($xml->createElement('TipoIDInformante', 'R'));
        $anexo->appendChild($xml->createElement('IdInformante', $cfg_ruc));
        $anexo->appendChild($xml->createElement('razonSocial', $razsoc));
        $anexo->appendChild($xml->createElement('Anio', $panio));
        $anexo->appendChild($xml->createElement('Mes', fillzero($pmes2, 2)));

         if(!empty($psixm))
         {$anexo->appendChild($xml->createElement('regimenMicroempresa', 'SI'));}
              
//          if(empty($psixm))
         {$anexo->appendChild($xml->createElement('numEstabRuc', '001'));}
        $anexo->appendChild($xml->createElement('totalVentas', number_format($totalvtas, 2, '.', '')));
        $anexo->appendChild($xml->createElement('codigoOperativo', 'IVA'));

        $compras = $anexo->appendChild($xml->createElement('compras'));
        while ($aso_comp = msql_fetch_assoc($res_comp))
        {
            $idnum1 = $aso_comp['idnum1'];
            $docu = $aso_comp['docu'];
            $suco = $aso_comp['suco'];
            $tipocomp = $aso_comp['docu_tico'];
            $enti = $aso_comp['enti'];
            $enti_descri = $aso_comp['enti_descri'];
            $enti_tipoid = $aso_comp['enti_tipoid'];
            $estab = substr($aso_comp['ptoe'], 0, 3);
            $ptoe = substr($aso_comp['ptoe'], 3, 3);
            $numero = $aso_comp['numero'];
            $autorizacion = $aso_comp['autornum'];
            $fechaemision = date('d/m/Y', strtotime($aso_comp['fecha']));
            $fecharegistro = date('d/m/Y', strtotime($aso_comp['fecha']));
            //     $fecharegistro=date('d/m/Y', strtotime($aso_comp['fechacont']));
            //     if(empty($fecharegistro)){$fecharegistro=$fechaemision;}
            if (empty($autorizacion))
            {
                $autorizacion = $aso_comp['atrz'];
            }
            if ($suco == '-')
            {
                $suco = get_lsuco($enti);
            }
            if ($suco == '-') $suco = '01';

            $tpidprov = '00';
            $pagolocext = '00';
            $idprov = $enti;
            $tipoprov = '02';

            if ($enti_tipoid == 'R')
            {
                $tpidprov = '01';
                $pagolocext = '01';
            }
            if ($enti_tipoid == 'C')
            {
                $tpidprov = '02';
                $pagolocext = '01';
            }
            if ($enti_tipoid == 'P')
            {
                $tpidprov = '03';
                $pagolocext = '02';
                $idprov = $aso_comp['enti_pasaporte'];
            }
            if ($enti_tipoid == 'E')
            {
                $tpidprov = '03';
                $pagolocext = '01';
                $idprov = $aso_comp['enti_idexterior'];
            }
          
            $basenograiva = 0;
            $baseimponible = 0;
            $baseimpgrav = 0;
            $baseimpexe = 0;
            $montoice = 0;
            $montoiva = 0;
            $valretbien10 = 0;
            $valretserv20 = 0;
            $valorretbienes = 0;
            $valretserv50 = 0;
            $valorretservicios = 0;
            $valretserv100 = 0;
            $totbasesimpreemb = 0;

            $baseimponible = abs($aso_comp['stsubtiva0']);
            $baseimpgrav = abs($aso_comp['stsubtiva']);
            $montoice = abs($aso_comp['stice']);
            $montoiva = abs($aso_comp['stiva']);
            $total = abs($aso_comp['stotal']);

            $sql_retp = 'select *,';
            $sql_retp .= 'sum(case when puni=30 then total end) as total30,';
            $sql_retp .= 'sum(case when puni=70 then total end) as total70,';
            $sql_retp .= 'sum(case when puni=100 then total end) as total100,';
            $sql_retp .= 'status ';
            $sql_retp .= 'from retp12 ';
            $sql_retp .= 'where status!="O"';
            $sql_retp .= 'and concat(docum,ptoem,numer,enti)="' . $docu . $estab . $ptoe . $numero . $enti . '"';
            $res_retp = msql_query($sql_retp, $link_vcrx);

            //     echo $sql_retp;
            if (msql_num_rows($res_retp) > 0)
            {
                $valorretbienes = abs(msql_result($res_retp, 0, 'total30'));
                $valorretservicios = abs(msql_result($res_retp, 0, 'total70'));
                $valretserv100 = abs(msql_result($res_retp, 0, 'total100'));
            }

            //     $detalleCompras=$compras->appendChild($xml->createElement('Sistemas1',$sql_retp));
            

            $detalleCompras = $compras->appendChild($xml->createElement('detalleCompras'));
            $detalleCompras->appendChild($xml->createElement('codSustento', $suco));
            $detalleCompras->appendChild($xml->createElement('tpIdProv', $tpidprov));
            $detalleCompras->appendChild($xml->createElement('idProv', $idprov));

            //       if($tpidprov=='03')
            //       {
            //         $detalleCompras->appendChild($xml->createElement('tipoProv',$tipoprov));
            //         $detalleCompras->appendChild($xml->createElement('denoProv',$enti_descri));
            //       }
            //       $detalleCompras->appendChild($xml->createElement('tipoComprobante',$tipocomp));
            $detalleCompras->appendChild($xml->createElement('tipoComprobante', $tipocomp));
            if ($tpidprov == '03')
            {
                $detalleCompras->appendChild($xml->createElement('tipoProv', $tipoprov));
                $detalleCompras->appendChild($xml->createElement('denoProv', $enti_descri));
            }

            $detalleCompras->appendChild($xml->createElement('parteRel', 'NO'));
            $detalleCompras->appendChild($xml->createElement('fechaRegistro', $fecharegistro));
            $detalleCompras->appendChild($xml->createElement('establecimiento', $estab));
            $detalleCompras->appendChild($xml->createElement('puntoEmision', $ptoe));
            $detalleCompras->appendChild($xml->createElement('secuencial', $numero));
            $detalleCompras->appendChild($xml->createElement('fechaEmision', $fechaemision));
            $detalleCompras->appendChild($xml->createElement('autorizacion', $autorizacion));
            $detalleCompras->appendChild($xml->createElement('baseNoGraIva', number_format($basenograiva, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('baseImponible', number_format($baseimponible, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('baseImpGrav', number_format($baseimpgrav, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('baseImpExe', number_format($baseimpexe, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('montoIce', number_format($montoice, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('montoIva', number_format($montoiva, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('valRetBien10', number_format($valretbien10, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('valRetServ20', number_format($valretserv20, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('valorRetBienes', number_format($valorretbienes, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('valRetServ50', number_format($valretserv50, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('valorRetServicios', number_format($valorretservicios, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('valRetServ100', number_format($valretserv100, 2, '.', '')));
            $detalleCompras->appendChild($xml->createElement('totbasesImpReemb', number_format($totbasesimpreemb, 2, '.', '')));

            $paisefecpago = 'NA';
            $apliconvdobtrib = 'NA';
            $pagoextsujretnorleg = 'NA';

            $pagoExterior = $detalleCompras->appendChild($xml->createElement('pagoExterior'));
            $pagoExterior->appendChild($xml->createElement('pagoLocExt', $pagolocext));
            if ($pagolocext == '02')
            {
                $tipreg = r_fiel('enti', $enti, 'tipreg');
                $dobtri = r_fiel('enti', $enti, 'dobtri');
                $retnor = r_fiel('enti', $enti, 'retnor');
              
                $dobtri = 'NO';
                $apliconvdobtrib = 'NO';
                $pagoextsujretnorleg = 'NO';
              
                $paisefecpago = r_fiel('pais', $aso_comp['enti_pais'], 'pais_ats');

                $pagoExterior->appendChild($xml->createElement('tipoRegi', $tipreg));
                $pagoExterior->appendChild($xml->createElement('paisEfecPagoGen', $paisefecpago));
                $pagoExterior->appendChild($xml->createElement('paisEfecPago', $paisefecpago));
                $pagoExterior->appendChild($xml->createElement('aplicConvDobTrib', $apliconvdobtrib));
                if ($dobtri == 'NO')
                {
                    $pagoExterior->appendChild($xml->createElement('pagExtSujRetNorLeg', $pagoextsujretnorleg));
                }
            }
            else
            {
                $pagoExterior->appendChild($xml->createElement('paisEfecPago', $paisefecpago));
                $pagoExterior->appendChild($xml->createElement('aplicConvDobTrib', $apliconvdobtrib));
                $pagoExterior->appendChild($xml->createElement('pagExtSujRetNorLeg', $pagoextsujretnorleg));
            }

            if ($tipocomp == '04')
            {
                $docModificado = $aso_comp['todocu'];
                $estabModificado = substr($aso_comp['toptoe'], 0, 3);
                $ptoEmiModificado = substr($aso_comp['toptoe'], 3, 3);
                $secModificado = $aso_comp['tonume'];
                $autModificado = $aso_comp['toatrz'];
                if (empty($autModificado))
                {
                    $sql_auto = 'select * from comp1 ';
                    $sql_auto.= 'where status not in("O","X") ';
                    $sql_auto.= 'and docu="' . $docModificado . '" ';
                    $sql_auto.= 'and ptoe="' . $estabModificado . $ptoEmiModificado . '" ';
                    $sql_auto.= 'and numero="' . $secModificado . '" ';
                    $sql_auto.= 'and enti like "' .substr($enti,0,10). '%" ';
                    $res_auto = msql_query($sql_auto, $link_vcrx);
                    $autModificado = msql_result($res_auto, 0, 'autornum');
                    if (empty($autModificado))
                    {
                        $autModificado = msql_result($res_auto, 0, 'atrz');
                    }
//                      $autModificado=$sql_auto;
                }
                $docModificado = r_fiel('docu', $docModificado, 'tico');

                $detalleCompras->appendChild($xml->createElement('docModificado', $docModificado));
                $detalleCompras->appendChild($xml->createElement('estabModificado', $estabModificado));
                $detalleCompras->appendChild($xml->createElement('ptoEmiModificado', $ptoEmiModificado));
                $detalleCompras->appendChild($xml->createElement('secModificado', $secModificado));
                $detalleCompras->appendChild($xml->createElement('autModificado', $autModificado));
            }

            if (mb_stristr('41.47.48', $tipocomp))
            {
                $reembolsos = $detalleCompras->appendChild($xml->createElement('reembolsos'));
                $reembolso = $reembolsos->appendChild($xml->createElement('reembolso'));
                $reembolso->appendChild($xml->createElement('tipoComprobanteReemb', '01'));
                $reembolso->appendChild($xml->createElement('tpIdProvReemb', '01'));
                $reembolso->appendChild($xml->createElement('idProvReemb', '0000000000000'));
                $reembolso->appendChild($xml->createElement('establecimientoReemb', '001'));
                $reembolso->appendChild($xml->createElement('puntoEmisionReemb', '001'));
                $reembolso->appendChild($xml->createElement('secuencialReemb', '000000001'));
                $reembolso->appendChild($xml->createElement('fechaEmisionReemb', '01/01/2017'));
                $reembolso->appendChild($xml->createElement('autorizacionReemb', '0000000000'));
                $reembolso->appendChild($xml->createElement('baseImponibleReemb', '0.00'));
                $reembolso->appendChild($xml->createElement('baseImpGravReemb', '0.00'));
                $reembolso->appendChild($xml->createElement('baseNoGraIvaReemb', '0.00'));
                $reembolso->appendChild($xml->createElement('baseImpExeReemb', '0.00'));
                $reembolso->appendChild($xml->createElement('montoIceRemb', '0.00'));
                $reembolso->appendChild($xml->createElement('montoIvaRemb', '0.00'));
            }

            if ($tipocomp != '04' and $total > 1000)
            {
                $formapago = $aso_comp['fpag'];
                //         if($formapago=='-'){$formapago='01';}
                if ($formapago == '-')
                {
                    $formapago = '20';
                }
                if ($formapago == '')
                {
                    $formapago = '20';
                }
                $formasdepago = $detalleCompras->appendChild($xml->createElement('formasDePago'));
                $formasdepago->appendChild($xml->createElement('formaPago', $formapago));
            }

            $sql_retp = 'select *,';
            $sql_retp .= 'sum(brta) as sbrta,';
            $sql_retp .= 'sum(biva) as sbiva,';
            $sql_retp .= 'sum(rrta) as srrta,';
            $sql_retp .= 'sum(riva) as sriva,';
            $sql_retp .= 'status ';
            $sql_retp .= 'from retp12 ';
            $sql_retp .= 'where status!="O" ';
            $sql_retp .= 'and substring(cair,1,1)in(3,4,5) ';
            $sql_retp .= 'and concat(docum,ptoem,numer,enti)="' . $docu . $estab . $ptoe . $numero . $enti . '" ';
            $sql_retp .= 'group by cair,puni';
            $res_retp = msql_query($sql_retp, $link_vcrx);

            //     explain_sql($sql_retp);
            if (msql_num_rows($res_retp) != 0)
            {
                if ($pagolocext == '02')
                {
                    while ($aso_retp = msql_fetch_assoc($res_retp))
                    {
                        $detalleCompras->appendChild($xml->createElement('estabRetencion1', substr($aso_retp['ptoe'], 0, 3)));
                        $detalleCompras->appendChild($xml->createElement('ptoEmiRetencion1', substr($aso_retp['ptoe'], 3, 3)));
                        $detalleCompras->appendChild($xml->createElement('secRetencion1', $aso_retp['numero']));
                        $detalleCompras->appendChild($xml->createElement('autRetencion1', $aso_retp['autornum']));
                        $detalleCompras->appendChild($xml->createElement('fechaEmiRet1', date('d/m/Y', strtotime($aso_retp['fecha']))));
                    }
                }
                else
                {
                    $air = $detalleCompras->appendChild($xml->createElement('air'));
                    while ($aso_retp = msql_fetch_assoc($res_retp))
                    {
                        $xcairb = $aso_retp['cair'];
                        if (mb_stristr('cpc1.stp1.flmn', $cfg_empr))
                        {
                            if ($xcairb == '351')
                            {
                                $xcairb = '346';
                            }
                        }
                        $detalleAir = $air->appendChild($xml->createElement('detalleAir'));
                        $detalleAir->appendChild($xml->createElement('codRetAir', $xcairb));
//             $baseimpgrav = abs($aso_comp['stsubtiva']);
//             $montoice = abs($aso_comp['stice']);
                         
                        $detalleAir->appendChild($xml->createElement('baseImpAir', number_format($aso_retp['sbrta'], 2, '.', '')));
//                         $detalleAir->appendChild($xml->createElement('baseImpAir', number_format(999.88, 2, '.', '')));
                         
                        $detalleAir->appendChild($xml->createElement('porcentajeAir', number_format($aso_retp['puni'], 2, '.', '')));
                        $detalleAir->appendChild($xml->createElement('valRetAir', number_format($aso_retp['srrta'], 2, '.', '')));
                    }

                    // Actualizado el 23/jun/2020 MI FINCA
                    
                    {
                        $sql_retp = str_replace('group by cair,puni', 'group by idnum1 order by idnum1 desc limit 1', $sql_retp);
                        $res_retp = msql_query($sql_retp, $link_vcrx);
                        while ($aso_retp = msql_fetch_assoc($res_retp))
                        {
                            $autornum = $aso_retp['autornum'];
                            if (empty($autornum) or substr($autornum, 23, 1) == '1')
                            {
                                $autornum = get_atrz0($aso_retp['docu'], $aso_retp['idnum1']);
                            }

                            $detalleCompras->appendChild($xml->createElement('estabRetencion1', substr($aso_retp['ptoe'], 0, 3)));
                            $detalleCompras->appendChild($xml->createElement('ptoEmiRetencion1', substr($aso_retp['ptoe'], 3, 3)));
                            $detalleCompras->appendChild($xml->createElement('secRetencion1', $aso_retp['numero']));
                            $detalleCompras->appendChild($xml->createElement('autRetencion1', $autornum));
                            $detalleCompras->appendChild($xml->createElement('fechaEmiRet1', date('d/m/Y', strtotime($aso_retp['fecha']))));
                        }
                    }
                }
            }
            else
            {
//                 $sql_comp3 = 'select sum(tsubt-tdcto+tprop) as stsubt,comp12.* from comp12 ';
                $sql_comp3 = 'select sum(tsubt-tdcto+tice+tprop) as stsubt,comp12.* from comp12 ';
                $sql_comp3 .= 'where idnum1="' . $idnum1 . '" ';
                $sql_comp3 .= 'and cair in("332","312","344") ';
                $sql_comp3 .= 'and docu_tico!="04" ';
                $sql_comp3 .= 'group by cair';
                $res_comp3 = msql_query($sql_comp3, $link_vcrx);

                if (msql_num_rows($res_comp3) != 0)
                {
                    $air = $detalleCompras->appendChild($xml->createElement('air'));
                    while ($aso_comp3 = msql_fetch_assoc($res_comp3))
                    {
                        $cair3 = trim($aso_comp3['cair']);
                        $stsubt = $aso_comp3['stsubt'];
                        $porc3 = get_porcair($cair3, $aso_comp3['fecha']);
                        $valor3 = $stsubt * $porc3 / 100;
                        $detalleAir = $air->appendChild($xml->createElement('detalleAir'));
                        $detalleAir->appendChild($xml->createElement('codRetAir', $cair3));
                        $detalleAir->appendChild($xml->createElement('baseImpAir', number_format($stsubt, 2, '.', '')));
                        $detalleAir->appendChild($xml->createElement('porcentajeAir', number_format($porc3, 2, '.', '')));
                        $detalleAir->appendChild($xml->createElement('valRetAir', number_format($valor3, 2, '.', '')));
                    }
                }
            }
        }

        if (@msql_num_rows($res_vtas) != 0)
        {
            $ventas = $anexo->appendChild($xml->createElement('ventas'));
            while ($aso_vtas = msql_fetch_assoc($res_vtas))
            {
                $enti = $aso_vtas['enti'];
                $enti_tipoid = $aso_vtas['enti_tipoid'];
                $denoclie = $aso_vtas['enti_descri'];
                $tipocomp = $aso_vtas['docu_tico'];
                $tipoemi = $aso_vtas['tipoemi'];
                $numcomp = $aso_vtas['cidnum1'];

                $basenograiva = 0;
                $baseimponible = 0;
                $baseimpgrav = 0;
                $montoiva = 0;
                $montoice = 0;

                //       $basenograiva=$aso_vtas['stsubtiva0'];
                $baseimponible = $aso_vtas['stsubtiva0'];
                $baseimpgrav = $aso_vtas['stsubtiva'];
                $montoiva = $aso_vtas['stiva'];
                $montoice = $aso_vtas['stice'];
                $fpag = $aso_vtas['fpag'];

                $tpidclie = '00';
                $idclie = '00';
                if ($enti_tipoid == 'R')
                {
                    $tpidclie = '04';
                    $idclie = substr($enti, 0, 10) . '001';
                }
                if ($enti_tipoid == 'C')
                {
                    $tpidclie = '05';
                    $idclie = substr($enti, 0, 10);
                }
                if ($enti_tipoid == 'P')
                {
                    $tpidclie = '06';
                    $idclie = $aso_vtas['enti_pasaporte'];
                }
                if ($enti_tipoid == 'E')
                {
                    $tpidclie = '06';
                    $idclie = $aso_vtas['enti_idexterior'];
                }
                if ($enti_tipoid == 'F')
                {
                    $tpidclie = '07';
                    $idclie = $aso_vtas['enti'];
                }

                $detalleventas = $ventas->appendChild($xml->createElement('detalleVentas'));
                $detalleventas->appendChild($xml->createElement('tpIdCliente', $tpidclie));
                $detalleventas->appendChild($xml->createElement('idCliente', $idclie));
                if (mb_stristr('04.05.06', $tpidclie))
                {
                    $detalleventas->appendChild($xml->createElement('parteRelVtas', 'NO'));
                }
                if (mb_stristr('06', $tpidclie))
                {
                    $detalleventas->appendChild($xml->createElement('tipoCliente', '02'));
                    $detalleventas->appendChild($xml->createElement('denoCli', $denoclie));
                }
                $detalleventas->appendChild($xml->createElement('tipoComprobante', $tipocomp));
                $detalleventas->appendChild($xml->createElement('tipoEmision', $tipoemi));
                $detalleventas->appendChild($xml->createElement('numeroComprobantes', number_format($numcomp, 0)));
                $detalleventas->appendChild($xml->createElement('baseNoGraIva', number_format($basenograiva, 2, '.', '')));
                $detalleventas->appendChild($xml->createElement('baseImponible', number_format($baseimponible, 2, '.', '')));
                $detalleventas->appendChild($xml->createElement('baseImpGrav', number_format($baseimpgrav, 2, '.', '')));
                $detalleventas->appendChild($xml->createElement('montoIva', number_format($montoiva, 2, '.', '')));
                $detalleventas->appendChild($xml->createElement('montoIce', number_format($montoice, 2, '.', '')));

                $sql_retc = 'select *,';
                $sql_retc .= 'sum(brta) as sbrta,';
                $sql_retc .= 'sum(biva) as sbiva,';
                $sql_retc .= 'sum(rrta) as srrta,';
                $sql_retc .= 'sum(riva) as sriva,';
                $sql_retc .= 'status ';
                $sql_retc .= 'from retc12 ';
                $sql_retc .= 'where status!="O" ';
//                 $sql_retc .= 'and fanio="' . $panio . '" and fmes="' . $pmes . '" ';
                $sql_retc .= 'and fanio="' . $panio . '" and fmes>="' . $pmes1 . '" and fmes<="' . $pmes2 . '" ';
                $sql_retc .= 'and substring(enti,1,10)="' . substr($enti, 0, 10) . '"';
                $res_retc = msql_query($sql_retc, $link_vcrx);

                $valorretiva = msql_result($res_retc, 0, 'sriva');
                $valorretrta = msql_result($res_retc, 0, 'srrta');
                //         if(msql_num_rows($res_retc)!=0)
                
                {
                    $detalleventas->appendChild($xml->createElement('valorRetIva', number_format($valorretiva, 2, '.', '')));
                    $detalleventas->appendChild($xml->createElement('valorRetRenta', number_format($valorretrta, 2, '.', '')));
                }

                if ($tipocomp != '04')
                {
                    $formasdepago = $detalleventas->appendChild($xml->createElement('formasDePago'));
                    $formasdepago->appendChild($xml->createElement('formaPago', $fpag));
                }

            }

            $ventasestablecimiento = $anexo->appendChild($xml->createElement('ventasEstablecimiento'));
            while ($aso_vtase = msql_fetch_assoc($res_vtase))
            {
                $vtasestab = $aso_vtase['stsubtiva0'] + $aso_vtase['stsubtiva'];
                $ventaest = $ventasestablecimiento->appendChild($xml->createElement('ventaEst'));
                $ventaest->appendChild($xml->createElement('codEstab', substr($aso_vtase['ptoe'], 0, 3)));
                $ventaest->appendChild($xml->createElement('ventasEstab', number_format($vtasestab, 2, '.', '')));
            }

        }

        //   echo 'anula::  '.msql_num_rows($res_vtaso);
        $anulados = $anexo->appendChild($xml->createElement('anulados'));
        if (@msql_num_rows($res_vtaso) != 0 and 1==2)
        {
            while ($aso_vtaso = msql_fetch_assoc($res_vtaso))
            {
                $autorizacion = $aso_vtaso['autorizacion'];
                $autornum = $aso_vtaso['autornum'];
                if ($autorizacion == '')
                {
                    $autorizacion = $autornum;
                };
                $detalleanulados = $anulados->appendChild($xml->createElement('detalleAnulados'));
                $detalleanulados->appendChild($xml->createElement('tipoComprobante', $aso_vtaso['docu_tico']));
                $detalleanulados->appendChild($xml->createElement('establecimiento', substr($aso_vtaso['ptoe'], 0, 3)));
                $detalleanulados->appendChild($xml->createElement('puntoEmision', substr($aso_vtaso['ptoe'], 3, 3)));
                $detalleanulados->appendChild($xml->createElement('secuencialInicio', $aso_vtaso['numero']));
                $detalleanulados->appendChild($xml->createElement('secuencialFin', $aso_vtaso['numero']));
                $detalleanulados->appendChild($xml->createElement('autorizacion', $autorizacion));
            }
        }

        $xml3 = $rutadoc . 'ATS_' . $panio . $pmes2 . '_' . $cfg_empr . '.xml';
        $xml->formatOut = true;
        $xml->save($xml3);

        $xmlfile = file_get_contents($xml3);
        $xmlfile = xml_chr13($xmlfile);
        file_put_contents($xml3, $xmlfile);

        //     $xmlfile=file_get_contents($xml3);
        //     $xmlfile=str_replace('<',chr(13).'<',$xmlfile);
        //     file_put_contents($xml3,$xmlfile);
        //   unlink($xml3);
        return;
    }

    function porc_rrta($docu, $idnum)
    {
    }

    function porc_riva($docu, $idnum)
    {

        include ('../_cfg/config.php');

        $xobcon = r_fiel('enti', $cfg_ruc, 'obcon');

        $porc_iva = 0;
        $sql_docu = 'select * from comp11 where idnum1=' . $idnum;
        $res_docu = msql_query($sql_docu, $link_vcrx);
        $tiporuc = msql_result($res_docu, 0, 'enti_tiporuc');

        if (mb_stristr('FP03.FP11', $docu))
        {
            $porc_iva = 100;
        }

        return $porc_iva;
    }

     
    function get_fechaclose($modu)
    {
        include ('../_cfg/config.php');
         $fechaclose=get_fechadtr();
         
         $sql_updt='update modu0 set modu_closed="'.$fechaclose.'" where modu_closed is null or modu_closed=""';
         $res_updt=msql_query($sql_updt,$link_vcrx);
         
//         $sql_updt='update modu0 set modu_closed="'.$fechaclose.'" where modu_codigo="CONT" ';
//         $res_updt=msql_query($sql_updt,$link_vcrx);
         
         $sql_modu='select * from modu0 where modu_codigo="'.$modu.'"';
         $res_modu=msql_query($sql_modu,$link_vcrx);
         $fechaclose=msql_result($res_modu,0,'modu_closed');
//          if(empty($fechaclose)){$fechaclose=get_fechadtr();}
         return $fechaclose;
         
    }
     
    function get_fechadtr()
    {
        include ('../_cfg/config.php');

        $fechadtr = '2010-12-31';

        $sql_dtr1 = 'select * from cont1 ';
        $sql_dtr1 .= ' where docu like "DTR%" and status!="O" and status!="X" ';
        $sql_dtr1 .= ' and fecha<=now() ';
        $sql_dtr1 .= ' order by fecha desc';
        $sql_dtr1 .= ' limit 1';
        $res_dtr1 = msql_query($sql_dtr1, $link_vcrx);
        if (msql_num_rows($res_dtr1) != 0)
        {
            $fechadtr = msql_result($res_dtr1, 0, 'fecha');
        }
        else
        {
            $fechadtr = fecha_modu('cont');
        }
        //   echo '******'.$fechadtr;
        return $fechadtr;

    }

    function get_idnum1($docu, $ptoe = '001001', $numero, $enti = '')
    {
        include ('../_cfg/config.php');
        $tabla = r_fiel('docu', $docu, 'tabla');
        $numero = fillzero($numero, 9);

        $sql_idnum = 'select * from ' . $tabla . '1 ';
        $sql_idnum .= ' where numero="' . $numero . '"';
        $sql_idnum .= ' and docu="' . $docu . '"';
        $sql_idnum .= ' and status!="X"';
        if (mb_stristr('FP.RC.', substr($docu, 0, 2)))
        {
            $sql_idnum .= ' and enti like"' . substr($enti, 0, 10) . '%"';
        }
        $sql_idnum .= ' order by idnum1 desc';

        $res_idnum = msql_query($sql_idnum, $link_vcrx);

        $xidnum1 = msql_query($res_idnum, 0, 'idnum1');
        return $xidnum1;

    }

    function updt_cairetp($idnum)
    {
        $updt_retp = 'update retp1, retp2, comp1, comp2 set retp2.cair=comp2.cair ';
        $updt_retp .= ' where retp1.idnum1=retp2.idnum2 and comp1.idnum1=comp2.idnum2 ';
        $updt_retp .= ' and retp2.numer =comp1.numero and retp1.enti=comp1.enti ';
        $updt_retp .= ' and retp1.idnum1=' . $idnum;
    }

    function updt_ctascomp($docu, $idnum)
    {
        if (!mb_stristr('FP.NP', substr($docu, 0, 2)))
        {
            return;
        }
        if ($idnum == '')
        {
            return;
        }
        include ('../_cfg/config.php');

        //   $xfecha1=date('Y-m-d', strtotime('today -90 days'));
        $xfecha1 = date('Y-m-01', strtotime('today'));
        $xfecharete = "2018-03-01";

        $sql_info = 'update comp1 set enti=concat(trim(enti),"001") where docu="FP10" and length(trim(enti))=10 and idnum1="' . $idnum . '"';
        $res_info = msql_query($sql_info, $link_vcrx);

        $sql_info = 'update comp1 set enti=substring(enti,1,10) where (docu="FP03" or docu="FP11") and idnum1="' . $idnum . '"';
        $res_info = msql_query($sql_info, $link_vcrx);

        $sql_info = 'update comp1 set suco="02" where docu="FP14" and idnum1="' . $idnum . '"';
        $res_info = msql_query($sql_info, $link_vcrx);

        //   $sql_info='update comp1 set atrz=null where docu="FP10" and claveacc!="" and claveacc is not null and idnum1="'.$idnum.'"';
        //   $res_info=msql_query($sql_info,$link_vcrx);
        $cont = r_fiel('empr', $cfg_empr, 'cont');
        if ($cont != 1)
        {
            return;
        }

        $sql_comp = 'select * from comp1 left join comp2 on idnum1=idnum2 where idnum1=' . $idnum;
        $res_comp = msql_query($sql_comp, $link_vcrx);
        //   echo explain_sql($sql_comp);
        while ($aso_comp = msql_fetch_assoc($res_comp))
        {
            $xdocu = $aso_comp['docu'];
            $xenti = $aso_comp['enti'];
            $xitem = $aso_comp['item'];
            $xitemce = $aso_comp['itemce'];
            $xctas = $aso_comp['ctas'];
            $xcair = $aso_comp['cair'];
            $xfecha = $aso_comp['fecha'];
            $iddet = $aso_comp['iddet'];

            if (substr($xitem, 0, 4) == "9999")
            {
                $litem = get_litem($xenti, $xitemce);
                $sql_updt = 'update comp2 set item="' . $litem . '" where idnum2=' . $idnum . ' and iddet=' . $iddet;
                $res_updt = msql_query($sql_updt, $link_vcrx);
                $xitem = $litem;
            }

            if ($xctas == '')
            {
                $lctas = get_lctas($xenti, $xitem);
                $sql_updt = 'update comp2 set ctas="' . $lctas . '" where idnum2=' . $idnum . ' and iddet=' . $iddet;
                $res_updt = msql_query($sql_updt, $link_vcrx);
            }

            if ($xcair == '')
            {
                $lcair = get_lcair($xenti, $xitem);
                $sql_updt = 'update comp2 set cair="' . $lcair . '" where idnum2=' . $idnum . ' and iddet=' . $iddet;
                $res_updt = msql_query($sql_updt, $link_vcrx);
                //       echo '*/*'.$xcair;
                
            }

            if ($xfecha >= $xfecharete)
            {
                $sql_updt = 'update comp2 left join cair0 on cair=cair_codigo set prrta=cair_porc where idnum2=' . $idnum . ' and iddet=' . $iddet;
                $res_updt = msql_query($sql_updt, $link_vcrx);

                if ($xdocu == 'FP03' or $xdocu == 'FP11')
                {
                    $sql_updt = 'update comp2 set priva=100 where iva>0 and idnum2=' . $idnum . ' and iddet=' . $iddet;
                    $res_updt = msql_query($sql_updt, $link_vcrx);
                }
                else
                {
                    //         $lriva=get_lriva2($xenti,$xitem);
                    $lriva = get_lriva($xenti, $xitem);
                    $sql_updt = 'update comp2 set priva="' . $lriva . '" where idnum2=' . $idnum . ' and iddet=' . $iddet;
                    $res_updt = msql_query($sql_updt, $link_vcrx);
                }
            }

            if ($xfecha < $xfecharete)
            {
                $sql_updt = 'update comp1,comp2,retp1,retp2 set comp2.prrta=retp2.puni ';
                $sql_updt .= ' where comp2.idnum2=' . $idnum . ' and comp2.iddet=' . $iddet;
                $sql_updt .= ' and comp1.idnum1=comp2.idnum2';
                $sql_updt .= ' and comp1.enti=retp1.enti';
                $sql_updt .= ' and comp1.docu=retp2.docum';
                $sql_updt .= ' and comp1.numero=retp2.numer';
                $sql_updt .= ' and comp2.cair=retp2.cair';
                $sql_updt .= ' and retp1.status!="O"';
                $sql_updt .= ' and retp1.status!="X"';
                $res_updt = msql_query($sql_updt, $link_vcrx);
            }

            // 		echo $sql_updt;
            
        }
    }

    function gen_contab($docu, $idnum)
    {
//          return ;
        include ('../_cfg/config.php');
        include ('php_session.php');
        // transferencias entre caja/bancos pasan por caja general
//           echo '*/*/*/'.$empr_codigo;
        if ($empr_codigo == 'apri')
        {
            return;
        }
        if ($empr_codigo == 'unil')
        {
            return;
        }
        if ($empr_codigo == 'fran')
        {
            return;
        }

//          echo '*/*/*/-----'.$empr_codigo;
         
        // 1010205
        // cxc clientes
        // 2010301
        // cxp locales
        // 520220
        // para iva/ice en compras
        // 2010701
        // para iva en ventas
        // 520118
        // AGUA, ENERG?A, LUZ Y TELECOMUNICACIONES
        // la misma para el ice
        

        // ret cli
        // 1010502
        // retp pro
        //   201070101
        

        // ingresos diferidos
        $ctaingredife = '2020901';

        if (!mb_stristr('RC.RP', substr($docu, 0, 2)) and substr($docu, 2, 2) == '00')
        {
            return;
        }
        // 	if(mb_stristr('IB.EB',substr($docu,0,2))){return;}
        

        // 		set_docu("IB10","TRAN","inve","ING.X COMPRA");
        // 		set_docu("IB11","TRAN","inve","ING.X CAMBIO");
        // 		set_docu("IB12","TRAN","inve","ING.X DEVOLUCION");
        // 		set_docu("IB13","TRAN","inve","ING.X TRANSFERENCIA");
        // 		set_docu("IB14","TRAN","inve","ING.X PRODUCCION");
        // // 		set_docu("IB15","TRAN","inve","ING.X REPROCESO");
        // 		set_docu("IB15","TRAN","inve","ING.X IMPORTACION");
        // 		set_docu("IB16","TRAN","inve","ING.X CONSIGNACION");
        // 		set_docu("IB17","TRAN","inve","ING.X AJUSTE");
        // 		set_docu("IB18","TRAN","inve","ING.X OPENPACK");
        // // 		set_docu("IB19","TRAN","inve","ING.X ");
        // 		set_docu("EB10","TRAN","inve","EGR.X VENTA");
        // 		set_docu("EB11","TRAN","inve","EGR.X CAMBIO");
        // 		set_docu("EB12","TRAN","inve","EGR.X DEVOLUCION");
        // 		set_docu("EB13","TRAN","inve","EGR.X TRANSFERENCIA");
        // 		set_docu("EB14","TRAN","inve","EGR.X PRODUCCION");
        // // 		set_docu("EB15","TRAN","inve","EGRESO X REPROCESO");
        // 		set_docu("EB15","TRAN","inve","EGRESO X EXPORTACION");
        // // 		set_docu("EB15","TRAN","inve","EGR.X CONSUMO");
        // 		set_docu("EB16","TRAN","inve","EGR.X CONSIGNACION");
        // 		set_docu("EB17","TRAN","inve","EGR.X AJUSTE");
        // 		set_docu("EB18","TRAN","inve","EGR.X OPENPACK");
        // 		set_docu("EB19","TRAN","inve","EGR.X BAJA");
        // documentos no se contabilizan
        //   if(mb_stristr('IB11.IB13.IB18.....EB11.EB13.EB18',$docu)){return;}
        // 	if(mb_stristr('IB.EB',substr($docu,0,2)))
        //   {if(!mb_stristr('IB10.IB12.IB14.IB15.IB16.IB.EB10',$docu)){return;}}
        

        $cont = r_fiel('empr', $cfg_empr, 'cont');
//              echo '*/*/*/'.$cont;
        if ($cont != 1)
        {
            return;
        }

        $xfechanow = date('Y-m-d');
        $xuser = $_SESSION['user_vcrx_id'];

        $idcont = '';
        $xmdfrom = 'X';
        $xbode = 'B010';
        $xbode2 = '';
        $xptoe = '001001';

        $sql_empr = 'select * from empr1';
        $res_empr = msql_query($sql_empr, $link_vcrx);
        $empr_ruc = msql_result($res_empr, 0, 'empr_ruc');
        $empr = msql_result($res_empr, 0, 'empr_codigo');

        // VALIDA DOCU
        $tdocu = substr($docu, 0, 2);
        $sql_docu = 'select * from docu0 where docu_codigo="' . $docu . '"';
        $res_docu = msql_query($sql_docu, $link_vcrx);

        if ($res_docu == 0)
        {
            die('Error en DOCU');
        }
        if (substr($docu, 0, 2) == "DD")
        {
            die('Error en DOCU');
        }

        // FECHA CONTABILIZAR
        //  1 enero anio actual-1
        $xfcont1 = date('2019-01-01');

        if ($empr_codigo == 'pisa')
        {
            $xfcont1 = date('2010-01-01');
        }

        if ($_SESSION['user_vcrx_empr'] != "")
        {
            $cfg_empr = $_SESSION['user_vcrx_empr'];
        }

        if (mb_stristr('apri', $cfg_empr))
        {
            $xfcont1 = date('2016-03-01');
        }

        if (mb_stristr('pcs1', $cfg_empr))
        {
            $xfcont1 = date('2017-01-01');
        }

        if (mb_stristr('prs1', $cfg_empr))
        {
            $xfcont1 = date('2016-12-31');
        }
        // 		{$xfcont1=date('2017-01-01');}
        $fechatr = get_fechadtr();
        if (empty($fechatr))
        {
            $fechatr = fecha_modu('cont');
        }
        if (empty($fechatr))
        {
            $fechatr = '2010-12-31';
        }

        $cont_closed = r_fiel('modu', 'cont', 'closed');
        if ($cont_closed > $fechatr)
        {
            $fechatr = $cont_closed;
        }

//            echo '*/*/*/*/'.$fechatr;
        if ($cfg_empr == 'demo')
        {
            $fechatr = date('Y-12-31', strtotime('today -12 month'));
        }
        if ($fechatr > $xfcont1)
        {
            $xfcont1 = date('Y-m-d', strtotime($fechatr . ' +1 day'));
        }

        // DOCU
        $xidfrom = $idnum;
        $xmdfrom = strtoupper(msql_result($res_docu, 0, 'docu_tabla'));
        $tabla = strtolower(msql_result($res_docu, 0, 'docu_tabla'));

        if (mb_stristr('IE13.DB13', $docu))
        {
            $sql_elim = 'update ' . $tabla . '1,' . $tabla . '2 set status="O" where idnum1=idnum2 and caba2!="" and ctas!="" and ctas is not null and idnum2="' . $idnum . '"';
            $res_elim = msql_query($sql_elim, $link_vcrx);
        }

         
        if (mb_stristr('vtas.comp.inve.caja.bcos.dxco.dxpa.retc.retp.retb.rolp.nvdd.', $tabla))
        {
            $ctadeb = msql_result($res_docu, 0, 'docu_ctadeb');
            $ctacre = msql_result($res_docu, 0, 'docu_ctacre');
            $ctadcto = msql_result($res_docu, 0, 'docu_ctadcto');
            $ctaprop = msql_result($res_docu, 0, 'docu_ctaprop');
            $ctaice = msql_result($res_docu, 0, 'docu_ctaice');
            $ctaiva = msql_result($res_docu, 0, 'docu_ctaiva');
            $ctairbp = msql_result($res_docu, 0, 'docu_ctairbp');
            $rescont = msql_result($res_docu, 0, 'docu_rescont');

//                 echo '*'.$ctadeb;
//                 echo '*'.$ctacre;
//                 echo '*'.$ctaiva;
            if ($tabla == 'vtas')
            {
                $sql_doco = 'select * from docu0 where docu_codigo like "FC%" order by docu_codigo';
                $res_doco = msql_query($sql_doco, $link_vcrx);
                if ($ctaiva == '')
                {
                    $ctaiva = msql_result($res_doco, 0, 'docu_ctaiva');
                }
            }

            if ($tabla == 'comp')
            {
                $sql_doco = 'select * from docu0 where docu_codigo like "FP%" order by docu_codigo';
                $res_doco = msql_query($sql_doco, $link_vcrx);
                if ($ctaiva == '')
                {
                    $ctaiva = msql_result($res_doco, 0, 'docu_ctaiva');
                }
            }

            if ($ctadcto == '')
            {
                $ctadcto = $ctacre;
            }
            if ($ctaice == '')
            {
                $ctaice = $ctadeb;
            }
            if ($ctaiva == '')
            {
                $ctaiva = $ctadeb;
            }
            if ($ctairbp == '')
            {
                $ctairbp = $ctadeb;
            }
            if ($ctaprop == '')
            {
                $ctairbp = $ctaprop;
            }

            $tabla1 = $tabla . '1';
            $tabla2 = $tabla . '2';
            $tabla11 = $tabla . '12';
            $tabla12 = $tabla . '12';

            //     echo '*/*/*/'.$xfcont1;
            //     $xfcont1='2010-01-01';
            $sql_tab1 = 'select * from ' . $tabla1 . ' where fecha>="' . $xfcont1 . '" and idnum1="' . $idnum . '"';
            $res_tab1 = msql_query($sql_tab1, $link_vcrx);
            if ($res_tab1 == 0)
            {
                die('ERROR EN TABLA 1');
            }
            // 		if (msql_num_rows($res_tab1)==0){die ('NO HAY DATOS X CONTABILIZAR');}
            if (msql_num_rows($res_tab1) == 0)
            {
                return;
            }

            $sql_tab2 = 'select * from ' . $tabla2 . ' where idnum2="' . $idnum . '" order by iddet';
            $res_tab2 = msql_query($sql_tab2, $link_vcrx);
            if ($res_tab2 == 0)
            {
                die('ERROR EN TABLA 2');
            }

            // 		$sql_tab11='select * from '.$tabla11.' where fecha>="'.$xfcont1.'" and idnum1="'.$idnum.'"';
            $sql_tab11 = 'select * from ' . $tabla12 . ' where fecha>="' . $xfcont1 . '" and idnum1="' . $idnum . '"';
            $total_sql = sql_total($tabla);
            $sql_tab11 = str_replace('select *', 'select *,' . $total_sql, $sql_tab11);
            //     $sql_tab11.=' group by idnum1';
            $res_tab11 = msql_query($sql_tab11, $link_vcrx);
            if ($res_tab11 == 0)
            {
                die('ERROR EN TABLA 11');
            }

            $sql_tab12 = 'select * from ' . $tabla12 . ' where fecha>="' . $xfcont1 . '" and idnum2="' . $idnum . '" order by iddet';
            $res_tab12 = msql_query($sql_tab12, $link_vcrx);
            if ($res_tab12 == 0)
            {
                die('ERROR EN TABLA 12');
            }

            $docu = @msql_result($res_tab1, 0, 'docu');
            $ptoe = @msql_result($res_tab1, 0, 'ptoe');
            $numero = @msql_result($res_tab1, 0, 'numero');
            $fecha = @msql_result($res_tab1, 0, 'fecha');
            $fcobro = @msql_result($res_tab1, 0, 'fcobro');
            $fechacont = @msql_result($res_tab1, 0, 'fechacont');
            $enti = @msql_result($res_tab1, 0, 'enti');
            $status = @msql_result($res_tab1, 0, 'status');
            $concepto = @msql_result($res_tab1, 0, 'concepto');
            $ctab = @msql_result($res_tab1, 0, 'ctab');
            $caba2 = @msql_result($res_tab1, 0, 'caba2');
            $tdocu = substr($docu, 0, 2);

            $tpro = r_fiel('enti',$enti,'tpro');
            $zsub = r_fiel('enti',$enti,'zsub');
             
            $docum = @msql_result($res_tab12, 0, 'docum');
            $ptoem = @msql_result($res_tab12, 0, 'ptoem');
            $numer = @msql_result($res_tab12, 0, 'numer');

                 $autocon=r_fiel('ptov',$ptoe,'autocon');
                 if($autocon==1)
                 {$ctaautocon=r_fiel('ptov',$ptoe,'ctacont');}
             
             
//              echo $docum.$ptoem.$numer;

            if ($enti == '')
            {
                $enti = '9999999999999';
                $sql_enti = 'update ' . $tabla . '1 set enti="' . $enti . '" where idnum1=' . $idnum;
                $res_enti = msql_query($sql_enti, $link_vcrx);
            }

            if (mb_stristr('OX', $status))
            {
                $sql_cont = 'update cont1 set status="' . $status . '" ';
                $sql_cont .= 'where upper(mdfrom)="' . strtoupper($xmdfrom) . '" ';
                $sql_cont .= 'and idfrom="' . $idnum . '" ';
                $res_cont = msql_query($sql_cont, $link_vcrx);
                return;
            }

            if (mb_stristr('pcs1.prs1', $cfg_empr) and mb_stristr('RBCO', substr($docu, 0, 4)) and $fecha <= "2018-12-31")
            {
                return;
            }

            // capturo el id de contabilidad
            $sql_cont = 'select * from cont1 where upper(mdfrom)="' . strtoupper($xmdfrom) . '" and idfrom="' . $idnum . '" order by idnum1';
            $res_cont = msql_query($sql_cont, $link_vcrx);

            if (msql_num_rows($res_cont) == 0)
            {
                $sql_icont = 'insert into cont1(docu,mdfrom,idfrom,iuser,idate) values("' . $docu . '","' . strtoupper($xmdfrom) . '","' . $idnum . '","' . $_SESSION['user_vcrx_id'] . '",now())';
                $res_icont = msql_query($sql_icont, $link_vcrx);
            }
            $res_cont = msql_query($sql_cont, $link_vcrx);
            $idcont = msql_result($res_cont, 0, 'idnum1');

            $sql_cont = 'delete from cont2 where idnum2="' . $idcont . '"';
            $res_cont = msql_query($sql_cont, $link_vcrx);

            if (substr($docu, 2, 2) == '00')
            {
                $status = 'X';
            }

            $sql_upd1 = 'update cont1 set ';
            $sql_upd1 .= ' docu="' . $docu . '",';
            $sql_upd1 .= ' ptoe="' . $ptoe . '",';
            $sql_upd1 .= ' numero="' . $numero . '",';
            $sql_upd1 .= ' fecha="' . $fecha . '",';
            $sql_upd1 .= ' enti="' . $enti . '",';
            $sql_upd1 .= ' status="' . $status . '",';
            $sql_upd1 .= ' idate=now(),';
            $sql_upd1 .= ' concepto="' . $concepto . '" ';
            $sql_upd1 .= ' where idnum1=' . $idcont . '';
            $res_upd1 = msql_query($sql_upd1, $link_vcrx);

            $sql_upd1 = 'update cont1 set ';
            if ($tabla == 'vtas')
            {
            }

            if ($tabla == 'comp')
            {
                $sql_upd1 .= ' suco="' . msql_result($res_tab1, 0, 'suco') . '",';
                if ($fechacont > $fecha)
                {
                    $sql_upd1 .= ' fecha="' . $fechacont . '",';
                }
            }

            if ($tabla == 'caja')
            {
            }

            if ($tabla == 'bcos')
            {
            }

            if ($tabla == 'retc')
            {
            }

            if ($tabla == 'retp')
            {
            }

            if ($tabla == 'inve')
            {
            }

            if ($tabla == 'nomi')
            {
            }

            $sql_upd1 .= ' concepto="' . $concepto . '" ';
            $sql_upd1 .= ' where idnum1=' . $idcont . '';
            $res_upd1 = msql_query($sql_upd1, $link_vcrx);

            if (mb_stristr('apri.emar.emun', $cfg_empr))
            {
                $sql_upd1 = 'update cont1 set ';
                $sql_upd1 .= ' bldn="' . msql_result($res_tab1, 0, 'bldn') . '" ';
                $sql_upd1 .= ' concepto="' . $concepto . '" ';
                $sql_upd1 .= ' where idnum1=' . $idcont . '';
                $res_upd1 = msql_query($sql_upd1, $link_vcrx);
            }

            if (mb_stristr('rcsa', $cfg_empr))
            {
                $sql_upd1 = 'update cont1 set ';
                $sql_upd1 .= ' sntr="' . msql_result($res_tab1, 0, 'sntr') . '" ';
                $sql_upd1 .= ' concepto="' . $concepto . '" ';
                $sql_upd1 .= ' where idnum1=' . $idcont . '';
                $res_upd1 = msql_query($sql_upd1, $link_vcrx);
            }

            // 		$res_tab1=msql_query($sql_tab1,$link_vcrx);
            // 		$res_tab2=msql_query($sql_tab2,$link_vcrx);
            // 		$res_tab11=msql_query($sql_tab11,$link_vcrx);
            // 		$res_tab12=msql_query($sql_tab12,$link_vcrx);
            @msql_data_seek($res_tab1, 0);
            @msql_data_seek($res_tab2, 0);
            @msql_data_seek($res_tab11, 0);
            @msql_data_seek($res_tab12, 0);

            if ($status != "X" and $status != "O")
            {
                $entidescri = msql_result($res_tab11, 0, 'enti_descri');
                $concepto = msql_result($res_tab11, 0, 'concepto');
                $detalle = msql_result($res_tab11, 0, 'detalle');
                // 			$total=abs(msql_result($res_tab11,0,'total'));
                $total = abs(msql_result($res_tab11, 0, 'stotal'));

                $iddet = 0;
                if (mb_stristr('vtas.comp', $tabla))
                {
                    $tdcto = abs(msql_result($res_tab11, 0, 'stdcto'));
                    $tice = abs(msql_result($res_tab11, 0, 'stice'));
                    $tiva = abs(msql_result($res_tab11, 0, 'stiva'));
                    $tirbp = abs(msql_result($res_tab11, 0, 'stirbp'));
                    $tprop = abs(msql_result($res_tab11, 0, 'stprop'));

                    if (mb_stristr('FC.NP.NV.FR.', $tdocu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('FP.NC', $tdocu))
                    {
                        $stran = - 1;
                    }

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                    $xctas = '';

                    if ($tabla == 'vtas')
                    {
                        if ($xctas == '')
                        {
                            $xctas = msql_result($res_tab11, 0, 'enti_ctaxcob');
                        }

                        if ($xctas == '')
                        {
                            $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaxcob');
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . msql_result($res_tab11, 0, 'docu') . '"  order by docu_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctacre');
                            }
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 ';
                            $sql_ctas0 .= ' where left(ctas_codigo,1)="1" ';
                            $sql_ctas0 .= ' and (ctas_descri like "%POR COBRAR%" or ctas_descri like "%X COBRAR%") ';
                            $sql_ctas0 .= ' and (ctas_descri like "CUEN%" or ctas_descri like "CTA%") ';
                            $sql_ctas0 .= ' order by ctas_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                        }

                        if ($xctas == '')
                        {
                            $xctas = '1010205';
                        }

                    }

                    if ($tabla == 'comp')
                    {
                        if ($xctas == '')
                        {
                            $xctas = msql_result($res_tab11, 0, 'enti_ctaxpag');
                        }

                        if ($xctas == '')
                        {
                            $xctas = r_fiel('tpro', msql_result($res_tab11, 0, 'enti_tpro') , 'ctaxpag');
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . msql_result($res_tab11, 0, 'docu') . '"';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            // 							$xctas=msql_result($res_ctas0,0,'docu_ctacre');
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctacre');
                            }
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 ';
                            $sql_ctas0 .= ' where left(ctas_codigo,1)="2" ';
                            $sql_ctas0 .= ' and (ctas_descri like "%POR PAGAR%" or ctas_descri like "%X PAGAR%") ';
                            $sql_ctas0 .= ' and (ctas_descri like "CUEN%" or ctas_descri like "CTA%") ';
                            $sql_ctas0 .= ' order by ctas_codigo desc';
                        }

                        if ($xctas == '')
                        {
                            $xctas = '2010301';
                        }

                    }
                     
                     $concepto=str_replace('"','\"',$concepto);

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . ',';
                    $sql_upd2 .= ' detalle="' . $concepto . '"';
                    $sql_upd2 .= ' where idnum2="' . $idcont . '" and iddet="' . $iddet . '"';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    // 				$rescont=0;
//                             echo '*/*/*/'.$sql_upd2;
                    if ($rescont == 1)
                    {
                        // 					$sql_tab12=str_replace('*','*,sum(tsubt)as tsubtd',$sql_tab12);
                        $sql_tab12 = str_replace('*', '*,sum(tsubt)as tsubtd,sum(tdcto)as tdctod,sum(tprop)as tpropd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by ctas,cair order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,tsubt as tsubtd,tdcto as tdctod,tprop as tpropd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }

                    // GRABA DETALLE
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {
                        if ($tabla == 'vtas')
                        {
                            $xctas = $r_deta['item_ctavtas'];
                             if($autocon==1)
                             {$xctas=$ctaautocon;}
                        }
                        if ($tabla == 'comp')
                        {
                            $xctas = $r_deta['ctas'];
                        }

                        if ($tabla == 'comp' and mb_stristr('pcs1.prs1', $cfg_empr))
                        {
                            $ctaice = $r_deta['ctas'];
                        }
                        if ($tabla == 'comp' and $ctaice == '')
                        {
                            $ctaice = $r_deta['ctas'];
                        }
                        if ($tabla == 'comp' and $ctaice == '')
                        {
                            $ctaice = '520220';
                        }

                        // 					if ($tabla=='comp' and mb_stristr('prs1',$cfg_empr)){$ctaiva=$r_deta['ctas'];}
                        if ($tabla == 'vtas' and $ctaiva == '')
                        {
                            $ctaiva = r_fiel('docu', 'FC10', 'ctaiva');
                        }
                        if ($tabla == 'comp' and $ctaiva == '')
                        {
                            $ctaiva = r_fiel('docu', 'FP10', 'ctaiva');
                        }

                        if ($tabla == 'vtas' and $ctaiva == '')
                        {
                            $ctaiva = '2010701';
                        }
                        if ($tabla == 'comp' and $ctaiva == '')
                        {
                            $ctaiva = '520220';
                        }

//                         if ($xctas == '')
//                         {
//                             if ($stran == 1)
//                             {
//                                 $xctas = $ctacre;
//                             }
//                             if ($stran == - 1)
//                             {
//                                 $xctas = $ctadeb;
//                             }
//                         }

                        if ($tabla == 'vtas')
                        {
                            if ($xctas == '')
                            {
                                $xctas = $r_deta['lsub_ctavtas'];
                            }

                             if ($xctas == '')
                             {
                                 if ($stran == 1)
                                 {
                                     $xctas = $ctacre;
                                 }
                                 if ($stran == - 1)
                                 {
                                     $xctas = $ctadeb;
                                 }
                             }

                             
                             
//                                         echo '******'.$r_deta['item'];
//                                         echo '******'.$r_deta['item_lsub'];
//                                         echo '******'.$r_deta['lsub_ctavtas'];
//                                         echo '*/*/*/'.$xctas;
                             
                             
                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" ';
                                $sql_ctas0 .= ' and (ctas_descri like "VENTA%" or ctas_descri like "INGRESO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=8 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }

                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" ';
                                $sql_ctas0 .= ' and (ctas_descri like "VENTA%" or ctas_descri like "INGRESO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=6 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }

                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" ';
                                $sql_ctas0 .= ' and (ctas_descri like "VENTA%" or ctas_descri like "INGRESO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=4 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }

                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" ';
                                $sql_ctas0 .= ' and (ctas_descri like "VENTA%" or ctas_descri like "INGRESO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=2 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }
                        }

                        if ($tabla == 'comp')
                        {
                             if ($xctas == '')
                             {
                                 if ($stran == 1)
                                 {
                                     $xctas = $ctacre;
                                 }
                                 if ($stran == - 1)
                                 {
                                     $xctas = $ctadeb;
                                 }
                             }

                             
                             
                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="5" ';
                                $sql_ctas0 .= ' and (ctas_descri like "COMPRA%" or ctas_descri like "COSTO%"  or ctas_descri like "GASTO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=8 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }

                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="5" ';
                                $sql_ctas0 .= ' and (ctas_descri like "COMPRA%" or ctas_descri like "COSTO%"  or ctas_descri like "GASTO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=6 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }

                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="5" ';
                                $sql_ctas0 .= ' and (ctas_descri like "COMPRA%" or ctas_descri like "COSTO%"  or ctas_descri like "GASTO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=4 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }

                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="5" ';
                                $sql_ctas0 .= ' and (ctas_descri like "COMPRA%" or ctas_descri like "COSTO%"  or ctas_descri like "GASTO%") ';
                                $sql_ctas0 .= ' and length(trim(ctas_codigo))>=2 ';
                                $sql_ctas0 .= ' order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                                //               echo msql_error($link_vcrx);
                                
                            }
                        }

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . abs($r_deta['tsubtd']) * $stran . '*-1,';
                        $sql_upd2 .= ' item="' . $r_deta['item'] . '",';
                        $sql_upd2 .= ' csub="' . $r_deta['csub'] . '",';
                        $sql_upd2 .= ' cair="' . $r_deta['cair'] . '",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        //                          echo '*/*/*/'.$sql_upd2;
                        // 					if($r_deta['tdctod']!=0 and $tabla=='vtas' and mb_stristr('pcs1.',$cfg_empr))
                        if ($r_deta['tdctod'] != 0 and $tabla == 'vtas')
                        {
                            if ($xctas == '')
                            {
                                $xctas = $r_deta['lsub_ctadcto'];
                            }

                            if ($xctas != '')
                            {
                                $iddet++;
                                $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                                $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                                $sql_upd2 = 'update cont2 set ';
                                $sql_upd2 .= ' ctas="' . $xctas . '",';
                                $sql_upd2 .= ' cant=' . abs($r_deta['tdctod']) * $stran . '*1,';
                                $sql_upd2 .= ' item="' . $r_deta['item'] . '",';
                                $sql_upd2 .= ' csub="' . $r_deta['csub'] . '",';
                                $sql_upd2 .= ' cair="' . $r_deta['cair'] . '",';
                                $sql_upd2 .= ' detalle="DESCUENTO  ' . round($r_deta['dcto'],2) . '%"';
                                $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                                $res_upd2 = msql_query($sql_upd2, $link_vcrx);
//                                               echo '<br>*/*/*/'.$sql_upd2;
                                $tdcto = $tdcto - ($r_deta['tdctod']) * $stran;
                            }

                        }

                        if ($r_deta['tdctod'] != 0 and $tabla == 'comp')
                        {
                            $iddet++;
                            $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                            $sql_upd2 = 'update cont2 set ';
                            $sql_upd2 .= ' ctas="' . $xctas . '",';
                            $sql_upd2 .= ' cant=' . abs($r_deta['tdctod']) * $stran . '*1,';
                            $sql_upd2 .= ' item="' . $r_deta['item'] . '",';
                            $sql_upd2 .= ' csub="' . $r_deta['csub'] . '",';
                            $sql_upd2 .= ' cair="' . $r_deta['cair'] . '",';
                            $sql_upd2 .= ' detalle="DESCUENTO  ' . round($r_deta['dcto'],2) . '%"';
                            $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                        }

                        if ($r_deta['tpropd'] != 0)
                        {
                            $iddet++;
                            $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                            $sql_upd2 = 'update cont2 set ';
                            $sql_upd2 .= ' ctas="' . $xctas . '",';
                            // 						$sql_upd2.=' cant='.abs($r_deta['tprop'])*$stran.'*-1,';
                            $sql_upd2 .= ' cant=' . abs($r_deta['tpropd']) * $stran . '*-1,';
                            $sql_upd2 .= ' item="' . $r_deta['item'] . '",';
                            $sql_upd2 .= ' csub="' . $r_deta['csub'] . '",';
                            $sql_upd2 .= ' cair="' . $r_deta['cair'] . '",';
                            $sql_upd2 .= ' detalle="PROPINA"';
                            $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                        }
                    }

                    if ($tdcto != 0 and $tabla == 'vtas')
                    {
                        $ctavtas = $xctas;
                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $xctas = $ctadcto;
                        if ($tabla == 'vtas')
                        {
                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" and (ctas_descri like "%DESCUENTO%") order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }
                            if ($xctas == '')
                            {
                                $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" order by ctas_codigo';
                                $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                                $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                            }
                        }

                        if ($cfg_empr == 'pcs1')
                        {
                            $xctas = $ctavtas;
                        }

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $tdcto * $stran . ',';
                        $sql_upd2 .= ' detalle="' . $concepto . '"';
                        $sql_upd2 .= ' where idnum2="' . $idcont . '" and iddet="' . $iddet . '"';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                    }

                    if ($tice != 0)
                    {
                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $xctas = $ctaice;
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="1" and (ctas_descri like "% ICE %") order by ctas_codigo';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                        }
                        if ($xctas == '')
                        {
                            $xctas = '1';
                        }

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $tice * $stran . '*-1,';
                        $sql_upd2 .= ' detalle="ICE  ' . $r_deta['ice'] . '"';
                        $sql_upd2 .= ' where idnum2="' . $idcont . '" and iddet="' . $iddet . '"';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                    }

                    if ($tiva != 0)
                    {
                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $xctas = $ctaiva;
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="2" and (ctas_descri like "%IVA%") order by ctas_codigo';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            $xctas = @msql_result($res_ctas0, 0, 'ctas_codigo');
                        }
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="2" order by ctas_codigo';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            $xctas = msql_result($res_ctas0, 0, 'ctas_codigo');
                        }

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $tiva * $stran . '*-1,';
                        $sql_upd2 .= ' detalle="IVA  ' . $r_deta['iva'] . '%"';
                        $sql_upd2 .= ' where idnum2="' . $idcont . '" and iddet="' . $iddet . '"';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                         
//                          echo '<br>'.$xctas;
                    }

                    if ($tirbp != 0)
                    {
                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '",0)';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $xctas = $ctairbp;
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 where left(ctas_codigo,1)="4" and (ctas_descri like "% IRBP %") order by ctas_codigo';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            $xctas = msql_result($res_ctas0, 0, 'ctas_codigo');
                        }
                        if ($xctas == '' and $tabla == 'vtas')
                        {
                            $xctas = '4';
                        }
                        if ($xctas == '' and $tabla == 'comp')
                        {
                            $xctas = '5';
                        }

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $tirbp * $stran . '*-1,';
                        $sql_upd2 .= ' detalle="IRBP ' . $r_deta['irbp'] . '"';
                        $sql_upd2 .= ' where idnum2="' . $idcont . '" and iddet="' . $iddet . '"';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                    }
                }

                if ($tabla == 'caja')
                {
                    if (mb_stristr('IE.IC.IV.CC.NA', $tdocu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('EE.EC.EV', $tdocu))
                    {
                        $stran = - 1;
                    }
                    if (mb_stristr('AC11.', $docu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('AP11.', $docu))
                    {
                        $stran = - 1;
                    }
                    if (mb_stristr('IV11.', $docu))
                    {
                        $stran = - 1;
                    }

                    $xcaja = msql_result($res_tab11, 0, 'caja');
                    $xcaba2 = msql_result($res_tab11, 0, 'caba2');

                    if ($xcaja == $xcaba2)
                    {
                        $xcaba2 = '';
                    }
                    if (mb_stristr('IV10.', $docu))
                    {
                        $xcaba2 = '';
                    }

                    if ($xctas == '')
                    {
                        $xctas = r_fiel('caja', $xcaja, 'ctacont');
                    }
                    if ($xctas == '')
                    {
                        $xctas = '10101';
                    }

                    $xctas2 = r_fiel('caba', $xcaba2, 'ctacont');
                    if ($xctas == '' and substr($docu, 2, 2) == '13')
                    {
                        $xctas = '10101';
                    }

                    if (substr($docu, 0, 2) == 'AC')
                    {
                        $xctas = '';
                        $sql_ap10 = 'select * from dcxo12 where docu like "AC10" and ctas!="" and ctas is not null and enti="' . $enti . '"';
                        $res_ap10 = msql_query($sql_ap10, $link_vcrx);
                        $xctas = @msql_result($res_ap10, 0, 'ctas');
                        if (empty($xctas))
                        {
                            $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaacli');
                        }
                        if (empty($xctas))
                        {
                            $xctas = r_fiel('docu', $docu, 'ctadeb');
                        }
                        if (empty($xctas))
                        {
                            $xctas = r_fiel('docu', 'AC10', 'ctacre');
                        }
                        if (empty($xctas))
                        {
                            $xctas = '20110';
                        }
                    }

                    //            echo '*/*/*/'.$docu;
                    if (substr($docu, 0, 2) == 'AP')
                    {
                        $xctas = '';
                        $sql_ap10 = 'select * from prov12 where docu like "AP10" and ctas!="" and ctas is not null and enti="' . $enti . '"';
                        $res_ap10 = msql_query($sql_ap10, $link_vcrx);
                        $xctas = @msql_result($res_ap10, 0, 'ctas');
                        if (empty($xctas))
                        {
                            $xctas = r_fiel('tpro', msql_result($res_tab11, 0, 'enti_tpro') , 'ctaapro');
                        }

                        if (empty($xctas))
                        {
                            $xctas = r_fiel('docu', $docu, 'ctacre');
                        }
                        if (empty($xctas))
                        {
                            $xctas = r_fiel('docu', 'AP10', 'ctadeb');
                        }
                        if (empty($xctas))
                        {
                            $xctas = '10104';
                        }
                    }

                    //            echo '<br>*/*/*/'.$fcobro;
                    //            echo '<br>*/*/*/'.$fecha;
                    /// cheque post-fechado
                    if ($fcobro > $fecha)
                    {
                        $xctas = '1010106';
                    }

                    if ($docu == 'ECH1')
                    {
                        $sql_ich1 = 'select * from caja1 ';
                        $sql_ich1 .= ' where docu like "ICH%" and numero="' . $numero . '" and enti like "' . substr($enti, 0, 10) . '%" and status not in ("O","X") ';
                        $sql_ich1 .= ' order by fecha desc';
                        $res_ich1 = msql_query($sql_ich1, $link_vcrx);
                        $fecha = msql_result($res_ich1, 0, 'fecha');
                        $idate = msql_result($res_ich1, 0, 'idate');
                        $fechadepo = msql_result($res_ich1, 0, 'fechadepo');
                        $fcobro = msql_result($res_ich1, 0, 'fcobro');
                        $idate = substr($idate, 0, 10);
                        //            if($fechadepo>$idate)
                        if ($fcobro > $fecha)
                        {
                            $xctas = '1010106';
                        }
                    }

                    $sql_cta13 = 'select * from ctas0 where ctas_codigo like "1%" and ctas_descri like "EFECTIVO%" order by ctas_codigo';
                    $res_cta13 = msql_query($sql_cta13, $link_vcrx);
                    $cta13 = @msql_result($res_cta13, 0, 'ctas_codigo');

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    if (@mb_stristr('apri', $_SESSION['user_vcrx_empr']))
                    {
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $docu . '" ';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            // 					echo $sql_ctas0;
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctacre');
                            }
                        }
                        // 					echo '*/*/*'.$xctas;
                        
                    }

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . '*1,';
                    $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                                echo $sql_upd2;
                    $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tcant)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by ctas,docum order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tcant) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    // GRABA DETALLE
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {
                        //cheque anulado
                        // 					if(mb_stristr('CA',$tdocu)){$stran=-1;}
                        $xctas = $r_deta['ctas'];
                        $docum = $r_deta['docum'];
                        $numer = $r_deta['numer'];

                        if (mb_stristr('FC.FP.AC.AP', substr($docum, 0, 2)) and $numer > 0)
                        {
                            $xctas = '';
                        }

                        if (substr($docu, 2, 2) == '13')
                        {
                            $xctas = $xctas2;
                        }

                        if (mb_stristr('IV11', $docu))
                        {
                            $sql_iv10 = 'select * from cont12 ';
                            $sql_iv10 .= 'where docu like "IV10" ';
                            $sql_iv10 .= 'and status!="0" and fecha<="' . $fecha . '" ';
                            $sql_iv10 .= 'and cant<0 ';
                            $sql_iv10 .= 'order by fecha desc, idnum1 desc';
                            $res_iv10 = msql_query($sql_iv10, $link_vcrx);
                            $xctas = msql_result($res_iv10, 0, 'ctas');
                        }

                         
                        if (substr($docum,0,2) == 'PR')
                        {
                            $xctas = '';
                            $sql_pr10='select * from caja12 where ifnull(status,"")not in ("O","X") and docu="'.$docum.'" and numero="'.$numer0.'"';
                            $res_pr10=msql_query($sql_pr10,$link_vcrx);
                            $xctas=@msql_result($res_pr10,0,'ctas');
                             
                            if(empty($xctas))
                            {
                                 $sql_pr10='select * from docu0 where docu_codigo="'.$docum.'"';
                                 $res_pr10=msql_query($sql_pr10,$link_vcrx);
                                 $xctas=@msql_result($res_pr10,0,'docu_ctadeb');
                            }
                        }
                         
                         
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from enti0,' . $tabla . '1 where enti=enti_codigo and idnum1="' . $idnum . '" order by enti_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'enti_ctaxcob');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'enti_ctaxpag');
                            }
                        }

                        if ($xctas == '')
                        {
                            $zsub = r_fiel('enti', $enti, 'zsub');
                            $tpro = r_fiel('enti', $enti, 'tpro');
                            if ($tpro == '')
                            {
                                $tpro = val_tpro($enti);
                            }

                            if ($stran == 1)
                            {
                                $xctas = r_fiel('zsub', $zsub, 'ctaxcob');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = r_fiel('tpro', $tpro, 'ctaxpag');
                            }
                            if ($stran == - 1 and substr($docu, 0, 2) == 'ND' and $xcaba2 == '')
                            {
                                $xctas = '5203';
                            }
                            if ($stran == - 1 and substr($docu, 0, 2) == 'DB' and $xcaba2 == '')
                            {
                                $xctas = '4302';
                            }
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $r_deta['docum'] . '"  order by docu_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctacre');
                            }
                        }

                        if (mb_stristr('PR', substr($docum,0,2)))
                        {
                            $stran = 1;
                        }
                        if (mb_stristr('PR', substr($docum,0,2)))
                        {
                            $stran = 1;
//                             $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $r_deta['docum'] . '"  order by docu_codigo desc';
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $docum. '"  order by docu_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
//                              echo '<br>'.$sql_ctas0;
                            if ($stran == 1)
                            {
                                $xctas = @msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = @msql_result($res_ctas0, 0, 'docu_ctacre');
                            }

                        }

                        if ($xctas == '')
                        {
                            if ($stran == 1 or $docu == 'IV11')
                            {
                                $xctas = r_fiel('zsub', r_fiel('enti', $enti, 'zsub') , 'ctaxcob');
                            }
                            if ($stran == - 1 or $docu == 'EV11')
                            {
                                $xctas = r_fiel('tpro', r_fiel('enti', $enti, 'tpro') , 'ctaxpag');
                            }
                        }

                        if ($xctas == '')
                        {
                            if ($stran == 1)
                            {
                                $xctas = $ctacre;
                            }
                            if ($stran == - 1)
                            {
                                $xctas = $ctadeb;
                            }
                        }
                         
                         
                         
// echo '/*/*/*/';
                        // 					if($caba2!=""){$xctas=$cta13;}
                        if ($xcaba2 != '')
                        {
                            $tcaba = 'caja';
                            $xcaba2desc = r_fiel('ctab', $xcaba2);
                            if ($xcaba2desc != '')
                            {
                                $tcaba = 'ctab';
                            }

                            // cuenta efectivo en transito
                            $xctas = '';
                            //             $xctas=r_fiel($tcaba,$xcaba2,'ctacont');
                            if ($xctas == '')
                            {
                                $xctas = '10101';
                            }
                            if ($cfg_empr == 'imcp')
                            {
                                $xctas = '1010104';
                            }
                            if ($cfg_empr == 'hg01')
                            {
                                $xctas = '1010101';
                            }
                             if($cfg_empr=='pcs1')
                             {
                                  $xctas='110101010007';
                             }

                        }

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . '*-1,';
                        // 				$sql_upd2.=' item="'.$r_deta['item'].'",';
                        // 				$sql_upd2.=' csub="'.$r_deta['csub'].'",';
                        // 				$sql_upd2.=' cair="'.$r_deta['cair'].'",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
//                         echo '<br>*/*/*/*'.$sql_upd2;
                        $xctas = "";
                    }

                }

                if ($tabla == 'bcos')
                {
//                             echo '1';
                    if (mb_stristr('DB.DC.NC.DX.CA', $tdocu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('DP.CH.ND.TB.PR.EV', $tdocu))
                    {
                        $stran = - 1;
                    }

                    // 				if(mb_stristr('AC11.',$docu)){$stran=1;}
                    // 				if(mb_stristr('AP11.',$docu)){$stran=1;}
                    if (mb_stristr('EV11.', $docu))
                    {
                        $stran = 1;
                    }

                    $xctab = @msql_result($res_tab11, 0, 'ctab');
                    $xcaba2 = @msql_result($res_tab11, 0, 'caba2');

                    if (mb_stristr('EV10.', $docu))
                    {
                        $xcaba2 = '';
                    }

                    if ($xctab == $xcaba2)
                    {
                        $xcaba2 = '';
                    }
                    //                     echo '*/*/*/'.$xctab;
                    $xctas = r_fiel('ctab', $xctab, 'ctacont');
                    $xctas2 = r_fiel('caba', $xcaba2, 'ctacont');
//                             echo '*/*/*/'.$xctas;
                    if ($xctas == '')
                    {
                        $xctas = '10101';
                    }

                    $sql_cta13 = 'select * from ctas0 where ctas_codigo like "1%" and ctas_descri like "EFECTIVO%" order by ctas_codigo';
                    $res_cta13 = msql_query($sql_cta13, $link_vcrx);
                    $cta13 = @msql_result($res_cta13, 0, 'ctas_codigo');

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . '*1,';
                    $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                     echo '<br>*/*/*/*'.$sql_upd2;
                    $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tcant)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by ctas,docum order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tcant) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }

                    // GRABA DETALLE
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {
                        //cheque anulado
                        if (mb_stristr('CA', $tdocu))
                        {
                            $stran = - 1;
                        }
                        if (mb_stristr('PR', $tdocu))
                        {
                            $stran = 1;
                        }

                        $xctas = $r_deta['ctas'];
                        $docum = $r_deta['docum'];
                        $numer = $r_deta['numer'];
                        $xctasdeta = $r_deta['ctas'];

                        // 					if(substr($docum,0,2)=='FC' and $numer*1==0 and substr($xctas,0,1)!="4"){$xctas='';}
                        // 					if(substr($docum,0,2)=='FP' and $numer*1==0 and substr($xctas,0,1)!="5"){$xctas='';}
                        // 					if(substr($docum,0,2)=='FP' and $numer>0){$xctas='';}
                        // 					if(substr($docum,0,2)=='FC' and $numer>0){$xctas='';}
                        if (@mb_stristr('FC.FP.AC.AP', substr($docum, 0, 2)) and $numer > 0)
                        {
                            $xctas = '';
                        }
                        if (@mb_stristr('FC.FP.AC.AP', substr($docum, 0, 2)) and $numer > 0 and !empty($xctasdeta))
                        {
                            $xctas = $xctasdeta;
                        }

                        if ($docum == 'AP10' and 1==2)
                        {
                            $xctas = '';
//                                       $sql_ap10='select * from prov12 where docu like "AP10" and ctas!="" and ctas is not null and enti="'.$enti.'"';
//                                       $res_ap10=msql_query($sql_ap10,$link_vcrx);
//                                       $xctas=@msql_result($res_ap10,0,'ctas');
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('tpro', msql_result($res_tab11, 0, 'enti_tpro') , 'ctaapro');
                            }

                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', $docum, 'ctacre');
                            }
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', 'AP10', 'ctadeb');
                            }
                            if (empty($xctas))
                            {
                                $xctas = '2010301';
                            }
//                              echo '*/*/*'.$xctas;
                        }

                        if ($docum == 'AP11')
                        {
                            $xctas = '';
                            //           $sql_ap10='select * from prov12 where docu like "AP10" and ctas!="" and ctas is not null and enti="'.$enti.'"';
                            //           $res_ap10=msql_query($sql_ap10,$link_vcrx);
                            //           $xctas=@msql_result($res_ap10,0,'ctas');
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('tpro', msql_result($res_tab11, 0, 'enti_tpro') , 'ctaxpag');
                            }

                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', $docum, 'ctacre');
                            }
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', 'AP11', 'ctacre');
                            }
                            if (empty($xctas))
                            {
                                $xctas = '2010301';
                            }
                        }

                        if ($docum == 'AC11')
                        {
                            $xctas = '';
                            //           $sql_ap10='select * from prov12 where docu like "AP10" and ctas!="" and ctas is not null and enti="'.$enti.'"';
                            //           $res_ap10=msql_query($sql_ap10,$link_vcrx);
                            //           $xctas=@msql_result($res_ap10,0,'ctas');
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaxcob');
                            }

                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', $docum, 'ctacre');
                            }
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', 'AC11', 'ctacre');
                            }
                            if (empty($xctas))
                            {
                                $xctas = '20110';
                            }
                        }

                        if (substr($docum,0,2) == 'PR')
                        {
                            $xctas = '';
                            $sql_pr10='select * from caja12 where ifnull(status,"")not in ("O","X") and docu="'.$docum.'" and numero="'.$numer0.'"';
                            $res_pr10=msql_query($sql_pr10,$link_vcrx);
                            $xctas=@msql_result($res_pr10,0,'ctas');
                             
                            if(empty($xctas))
                            {
                                 $sql_pr10='select * from docu0 where docu_codigo="'.$docum.'"';
                                 $res_pr10=msql_query($sql_pr10,$link_vcrx);
                                 $xctas=@msql_result($res_pr10,0,'docu_ctadeb');
                            }
                        }

                        if (substr($docu, 2, 2) == '13')
                        {
                            $xctas = $xctas2;
                        }
                        //           echo '*/*/*'.$stran.$docum;
                        //  					if(substr($docum,0,2)=='AP' and empty($xctas)){$xctas='10104';}
                         
                        if (mb_stristr('PR', $tdocu))
                        {
                            $stran = - 1;
                        }
                        if (mb_stristr('PR', $tdocu))
                        {
                            $stran = - 1;
//                             $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $r_deta['docum'] . '"  order by docu_codigo desc';
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $docu. '"  order by docu_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
//                              echo '<br>'.$sql_ctas0;
                            if ($stran == 1)
                            {
                                $xctas = @msql_result($res_ctas0, 0, 'docu_ctacre');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = @msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }

                        }

                         
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from enti0,' . $tabla . '1 where enti=enti_codigo and idnum1="' . $idnum . '" order by enti_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'enti_ctaxcob');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'enti_ctaxpag');
                            }
                        }

                        if ($xctas == '')
                        {
                            $zsub = r_fiel('enti', $enti, 'zsub');
                            $tpro = r_fiel('enti', $enti, 'tpro');
                            if ($tpro == '')
                            {
                                $tpro = val_tpro($enti);
                            }
                            if ($zsub == '')
                            {
                                $zsub = val_zsub($enti);
                            }

                            if ($stran == 1 or $docu == 'IV11')
                            {
                                $xctas = r_fiel('zsub', $zsub, 'ctaxcob');
                                 if(substr($docum,0,2)=='FP')
                                 {$xctas = r_fiel('tpro', $tpro, 'ctaxpag');}
                            }
                            if ($stran == - 1 or $docu == 'EV11')
                            {
                                $xctas = r_fiel('tpro', $tpro, 'ctaxpag');
                            }
                            if ($stran == - 1 and substr($docu, 0, 2) == 'ND' and $xcaba2 == '')
                            {
                                $xctas = '5203';
                            }
                            if ($stran == - 1 and substr($docu, 0, 4) == 'ND17' and $xcaba2 == '')
                            {
                                $xctas = r_fiel('tpro', $tpro, 'ctaxpag');
                            }
                            if ($stran == - 1 and substr($docu, 0, 2) == 'DB' and $xcaba2 == '')
                            {
                                $xctas = '4302';
                            }
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . $r_deta['docum'] . '"  order by docu_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            if ($stran == 1)
                            {
                                $xctas = @msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = @msql_result($res_ctas0, 0, 'docu_ctacre');
                            }

                        }

                        if ($xctas == '')
                        {
                            if ($stran == 1)
                            {
                                $xctas = $ctacre;
                            }
                            if ($stran == - 1)
                            {
                                $xctas = $ctadeb;
                            }
                        }

                        if (mb_stristr('CA', $tdocu))
                        {
                            $stran = 1;
                        }
                         

                        if ($xcaba2 != '')
                        {
                            $tcaba = 'caja';
                            $xcaba2desc = r_fiel('ctab', $xcaba2);
                            if ($xcaba2desc != '')
                            {
                                $tcaba = 'ctab';
                            }

                            // cuenta efectivo en transito
                            $xctas = '';
                            //             $xctas=r_fiel($tcaba,$xcaba2,'ctacont');
                            if ($xctas == '')
                            {
                                $xctas = '10101';
                            }
                            if ($cfg_empr == 'imcp')
                            {
                                $xctas = '1010104';
                            }
                            if ($cfg_empr == 'hg01')
                            {
                                $xctas = '1010101';
                            }
                             
                             if($cfg_empr=='pcs1')
                             {
                                  $xctas='110101010007';
//                                   $xctas=r_fiel($tcaba,$xcaba2,'ctacont');
                             }

                        }

                        if ($xctas == '')
                        {
                            //             if(@mb_stristr('FC.AC',substr($docum,0,2))){$xctas='1010205';}
                            
                        }

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . '*-1,';
                        // 				$sql_upd2.=' item="'.$r_deta['item'].'",';
                        // 				$sql_upd2.=' csub="'.$r_deta['csub'].'",';
                        // 				$sql_upd2.=' cair="'.$r_deta['cair'].'",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                         					echo '<br>'. $sql_upd2;
                        //           echo '*/*/'.msql_error($link_vcrx);
                        $xctas = "";
                    }

                }

//                                echo '*/*/*/'.$tabla;
                if (mb_stristr('dxco.dxpa', $tabla) and 1 == 1)
                {
                    if ($tabla == 'dxco')
                    {
                        $stran = - 1;
                    }
                    if ($tabla == 'dxpa')
                    {
                        $stran = 1;
                    }

                    if (mb_stristr('AC10', $docu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('AP10', $docu))
                    {
                        $stran = - 1;
                    }
                    if (mb_stristr('CC', substr($docu,0,2)))
                    {
                        $stran = -1;
                    }
                    if (mb_stristr('XC', substr($docu,0,2)))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('CP', substr($docu,0,2)))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('XP', substr($docu,0,2)))
                    {
                        $stran = -1;
                    }
                    //  				if(substr($docu,0,2)=='AP')
//                      echo '*/*/*/'.$tabla;
                    if ($tabla == 'dxpa')
                    {
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = msql_result($res_tab11, 0, 'enti_ctaxpag');
//                          echo '*/*/*/a'.$xctas;
                        }

                        if ($xctas == '')
                        {
                            $xctas = r_fiel('tpro', msql_result($res_tab11, 0, 'enti_tpro') , 'ctaxpag');
//                          echo '*/*/*/b'.$xctas;
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . msql_result($res_tab11, 0, 'docu') . '"';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
//                              echo '*/*/*/'.$sql_ctas0;
                             
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == -1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctacre');
//                                  echo '*/*/*'.$xctas;
                            }
                        }
                         
//                          echo '*/*/*/'.$xctas;
                         
                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 ';
                            $sql_ctas0 .= ' where left(ctas_codigo,1)="2" ';
                            $sql_ctas0 .= ' and (ctas_descri like "%POR PAGAR%" or ctas_descri like "%X PAGAR%") ';
                            $sql_ctas0 .= ' and (ctas_descri like "CUEN%" or ctas_descri like "CTA%") ';
                            $sql_ctas0 .= ' order by ctas_codigo desc';
                        }
                         
                        if ($xctas == '')
                        {
                            $xctas = '1010403';
                        }
                        //           {$xctas='2010301';}
                        
                    }

                    //  				if(substr($docu,0,2)=='AC')
                    if ($tabla == 'dxco')
                    {
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = msql_result($res_tab11, 0, 'enti_ctaxcob');
                        }

                        if ($xctas == '')
                        {
                            $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaxcob');
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from docu0 where docu_codigo="' . msql_result($res_tab11, 0, 'docu') . '"';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);
                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctadeb');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'docu_ctacre');
                            }
                        }

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from ctas0 ';
                            $sql_ctas0 .= ' where left(ctas_codigo,1)="2" ';
                            $sql_ctas0 .= ' and (ctas_descri like "%POR COBRA%" or ctas_descri like "%X COBRA%") ';
                            $sql_ctas0 .= ' and (ctas_descri like "CUEN%" or ctas_descri like "CTA%") ';
                            $sql_ctas0 .= ' order by ctas_codigo desc';
                        }

//                                                  echo '*/*/*/*'.$xctas;
                        if ($xctas == '')
                        {
                            $xctas = '2010301';
                        }

                    }

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                      echo $total;
//                      echo $stran;
                     
                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . '*1,';
                    $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);
//                             echo '<br>*/*/*/*'.$sql_upd2;
                    $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tcant*puni)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by ctas,docum order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tcant*puni) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }

                    //         explain_sql($sql_tab12);
                    // GRABA DETALLE
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {

                        $xctas = $r_deta['ctas'];
                        $docum = $r_deta['docum'];
                        $numer = $r_deta['numer'];

                        if (substr($docu, 0, 2) == 'AP')
                        {
                            $xctas = '';

                            //           $sql_ap10='select * from dxpa12 where docu like "'.$docu.'" and ctas!="" and ctas is not null and enti="'.$enti.'"';
                            //           $res_ap10=msql_query($sql_ap10,$link_vcrx);
                            //           $xctas=@msql_result($res_ap10,0,'ctas');
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('tpro', msql_result($res_tab11, 0, 'enti_tpro') , 'ctaapro');
                            }

                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', $docu, 'ctadeb');
                            }
                            if (empty($xctas))
                            {
                                $xctas = '10104';
                            }
                            //                     echo '*/*/*'.$xctas;
                            
                        }

                        if (substr($docu, 0, 2) == 'AC')
                        {
                            $xctas = '';
                            $sql_ap10 = 'select * from dxco12 where docu like "' . $docu . '" and ctas!="" and ctas is not null and enti="' . $enti . '"';
                            $res_ap10 = msql_query($sql_ap10, $link_vcrx);
                            $xctas = @msql_result($res_ap10, 0, 'ctas');
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaacli');
                            }
                            if (empty($xctas))
                            {
                                $xctas = r_fiel('docu', $docu, 'ctacre');
                            }
                            //                     210209010002
                            if (empty($xctas))
                            {
                                $xctas = '20110';
                            }
                        }
                         
                        if (substr($docu, 0, 2) == 'CC')
                        {
                            if ($docum=='AC10')
                            {
                                $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaacli');
                             if (empty($xctas))
                             {
                                 $xctas = r_fiel('docu', 'AC10', 'ctadeb');
                             }
                             if (empty($xctas))
                             {
                                 $xctas = '20110';
                             }
                            }
                             if(empty($xctas)){$xctas=$ctadeb;}
                        }
                             
                        if (substr($docu, 0, 2) == 'XC')
                        {
                            if ($docum=='AC10')
                            {
                                $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaacli');
                             if (empty($xctas))
                             {
                                 $xctas = r_fiel('docu', 'AC10', 'ctacre');
                             }
                             if (empty($xctas))
                             {
                                 $xctas = '20110';
                             }
                            }
                             
                             if(empty($xctas)){$xctas=$ctacre;}
                        }
                        
                        if (substr($docu, 0, 2) == 'CP')
                        {
                            if ($docum=='AP10')
                            {
                                $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaacli');
                             if (empty($xctas))
                             {
                                 $xctas = r_fiel('docu', 'AP10', 'ctadeb');
                             }
                             if (empty($xctas))
                             {
                                 $xctas = '20110';
                             }
                            }
                             if(empty($xctas)){$xctas=$ctacre;}
                        }
                             
                        if (substr($docu, 0, 2) == 'XP')
                        {
                            if ($docum=='AP10')
                            {
                                $xctas = r_fiel('zsub', msql_result($res_tab11, 0, 'enti_zsub') , 'ctaacli');
                             if (empty($xctas))
                             {
                                 $xctas = r_fiel('docu', 'AP10', 'ctacre');
                             }
                             if (empty($xctas))
                             {
                                 $xctas = '20110';
                             }
                            }
                             
                             if(empty($xctas)){$xctas=$ctadeb;}
                        }
                        

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . '*-1,';
                        // 				$sql_upd2.=' item="'.$r_deta['item'].'",';
                        // 				$sql_upd2.=' csub="'.$r_deta['csub'].'",';
                        // 				$sql_upd2.=' cair="'.$r_deta['cair'].'",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
//                         echo '<br>'.$sql_upd2;
                        $xctas = "";
                    }

                }

//                       echo '--+-+'.$tabla;
                if (mb_stristr('retc.retp.retb', $tabla))
                {
                    if (mb_stristr('RC', $tdocu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('RP', $tdocu))
                    {
                        $stran = 1;
                    }
                    if (mb_stristr('RB', $tdocu))
                    {
                        $stran = 1;
                    }

                    if (mb_stristr('RC', $tdocu))
                    {
                        $xctas = $ctadeb;
                        $xsigno = '1';
                    }
                    if (mb_stristr('RP', $tdocu))
                    {
                        $xctas = $ctacre;
                        $xsigno = '1';
                    }

                    // echo '*/*/*/'.$tdocu;
                    if (mb_stristr('RP', $tdocu))
                    {
                        $xctas = r_fiel('tpro', r_fiel('enti', $enti, 'tpro') , 'ctaxpag');
                        $xsigno = 1;
                    }
                    if (mb_stristr('RC', $tdocu))
                    {
                        $xctas = r_fiel('zsub', r_fiel('enti', $enti, 'zsub') , 'ctaxcob');
                        $xsigno = - 1;
                    }

//                                echo '<br>/**/*/'.$xctas;
                    if (mb_stristr('RB', $tdocu))
                    {
                         $xctas='';
                        $sql_ctab = 'select * from ctab0 where ';
                        $sql_ctab .= ' ctab_enti like "' . substr($enti,0,10) . '%" ';
                        $sql_ctab .= 'and ctab_ctacont!="" and ctab_ctacont is not null ';
                        $res_ctab = msql_query($sql_ctab, $link_vcrx);
                        $xctas = @msql_result($res_ctab, 0, 'ctab_ctacont');
                         
                        if ($xctas == '')
                        {
                        $sql_ctab = 'select * from ctab0 where ';
                        $sql_ctab .= ' ctab_codigo="' . $ctab . '"';
                        $res_ctab = msql_query($sql_ctab, $link_vcrx);
                        $xctas = @msql_result($res_ctab, 0, 'ctab_ctacont');
                        }
                         
                        if ($xctas == '')
                        {
                            $enti_descri = explode(' ', $entidescri);
                            $cidx = 0;
                            $sql_ctab = 'select * from ctab0 where ';
                            $sql_ctab .= ' ctab_ctacont!=""';
                            $sql_ctab .= ' and (';
                            $sql_ctab .= ' trim(left(ctab_descri,5)) like "%' . trim(substr($enti_descri[$cidx], 0, 5)) . '%"';
                            for ($cidx = 1;$cidx < count($enti_descri);$cidx++)
                            {
                                $sql_ctab .= ' or trim(left(ctab_descri,5)) like "%' . trim(substr($enti_descri[$cidx], 0, 5)) . '%"';
                            }
                            $sql_ctab .= ')';
                            $sql_ctab .= ' and ctab_status!="X"';
                            $sql_ctab .= ' and ctab_codigo!="-"';
                            $res_ctab = msql_query($sql_ctab, $link_vcrx);
                            $xctas = @msql_result($res_ctab, 0, 'ctab_ctacont');
                        }

                        if ($xctas == '')
                        {
                            $sql_ctab = 'select * from ctab0 where ';
                            $sql_ctab .= ' ctab_ctacont!="" ';
                            $sql_ctab .= ' and ctab_codigo!="-"';
                            $sql_ctab .= ' and ctab_status!="X"';
                            $sql_ctab .= ' order by ctab_codigo';
                            $res_ctab = msql_query($sql_ctab, $link_vcrx);
                            $xctas = @msql_result($res_ctab, 0, 'ctab_ctacont');
                        }

                         //rbco
//                          if($cfg_empr=='imcp')
//                         $sql_ctae = 'select * from tpro0 where tpro_codigo="'.$tp.'"';
//                         $res_ctae = msql_query($sql_ctae, $link_vcrx);
//                         $xctas = @msql_result($res_ctae, 0, 'tpro_ctaxpag');
//                          echo '*/*/*'.$tpro;
                         $xctas = r_fiel('tpro', $tpro, 'ctaxpag');
                         if(empty($xctas))
                         {
                        $sql_ctae = 'select * from tpro0 where tpro_ctaxpag!="" and tpro_ctaxpag is not null order by tpro_ctaxpag';
                        $res_ctae = msql_query($sql_ctae, $link_vcrx);
                        $xctas = @msql_result($res_ctae, 0, 'tpro_ctaxpag');
                         }
                         
                        $xsigno = - 1;
                    }

                    if ($xctas == '' and mb_stristr('RP', $tdocu))
                    {
                        $sql_ctae = 'select * from tpro0 where tpro_ctaxpag!="" and tpro_ctaxpag is not null order by tpro_ctaxpag';
                        $res_ctae = msql_query($sql_ctae, $link_vcrx);
                        $xctas = @msql_result($res_ctae, 0, 'tpro_ctaxpag');
                    }
                    if ($xctas == '' and mb_stristr('RC', $tdocu))
                    {
                        $sql_ctae = 'select * from zsub0 where zsub_ctaxcob!="" and zsub_ctaxcob is not null order by zsub_ctaxcob';
                        $res_ctae = msql_query($sql_ctae, $link_vcrx);
                        $xctas = @msql_result($res_ctae, 0, 'zsub_ctaxcob');
                    }

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . '*' . $xsigno . ',';
                    $sql_upd2 .= ' cair="' . $r_deta['cair'] . '",';
                    $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                    // linea 1
//                     echo '<br>'.$sql_upd2;
                    $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tcant)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by cair,puni,docu order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tcant) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    // 				echo $sql_tab12;
                    //         echo explain_sql($sql_tab12);
                    // GRABA DETALLE
                    $xsigno = $xsigno * -1;
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {
                        $cair = $r_deta['cair'];
                        if ($cair == '')
                        {
                            $cair = '-';
                        }
//                         if (mb_stristr('1.2.3'),$cair)
                        if (intval($cair)<100)
                        {
                            $cair = '-';
                        }
                        $puni = intval($r_deta['puni']);
                        // 					$xctas=$r_deta['ctas'];
                        $xctas = r_fiel('cair', $cair, 'ctacont');

//                                             echo '<br>A*/*/*/'.$xctas.$docu.$cair;
                        

                        if (mb_stristr('RC', substr($docu, 0, 2)))
                        {
                            $xctas = r_fiel('cair', $cair . '', 'ctaxcob');
                        }
                        if (mb_stristr('RP', substr($docu, 0, 2)))
                        {
                            $xctas = r_fiel('cair', $cair . '', 'ctaxpag');
                        }
                        if (mb_stristr('RB', substr($docu, 0, 2)))
                        {
                            $xctas = r_fiel('cair', $cair . '', 'ctaxcob');
                        }
                        if (mb_stristr('RB', substr($docu, 0, 2)) and $xctas=='')
                        {
                            $xctas = r_fiel('cair', $cair . '', 'ctacont');
                        }
//                                   echo '<br>B*/*/*/'.$xctas;
//                                   echo '<br>*/*/*/'.$cair;

                        if ($cair == '4580' and $xctas == '')
                        {
                            $xctas = '1010502';
                        }

                        if ($cair == '4580' and $empr == 'pcs1')
                        {
                            $xctas = '603020100002';
                        }
                        if ($cair == '4580' and $empr == 'prs1')
                        {
                            $xctas = '110301060001';
                        }
                        if ($cair == '4580' and mb_stristr($r_deta['concepto'], 'CARGA') and $cfg_empr == 'pcs1')
                        {
                            $xctas = '110301060001';
                        }
                         
                        if ($cair == '4580' and mb_stristr($r_deta['concepto'], 'IFIS') and $cfg_empr == 'pcs1')
                        {
                            $xctas = '110301060001';
                        }

                        // CAIR 323 4580
                        //110301060001
                        if ($xctas == '')
                        {
                            if (mb_stristr('RC', substr($docu, 0, 2)))
                            {
                                $xctas = r_fiel('cair', substr($cair, 0, 3) , 'ctaxcob');
                            }
                            if (mb_stristr('RP', substr($docu, 0, 2)))
                            {
                                $xctas = r_fiel('cair', substr($cair, 0, 3) , 'ctaxpag');
                            }
                        }
//                                   echo '<br>C*/*/*/'.$xctas;
                        

                        if ($xctas == '')
                        {
                            $sql_ctas1 = 'select * from cont12 where docu like "' . $docu . '" and cair like "' . $cair . '%" and fecha<"' . $fecha . '" order by fecha desc limit 1';
                            $res_ctas1 = msql_query($sql_ctas1, $link_vcrx);
                            $xctas = @msql_result($res_ctas1, 0, 'ctas');

                            if (mb_stristr('RC', substr($docu, 0, 2)))
                            {
                                $sql_ctas2 = 'update cair0 set cair_ctaxcob="' . $xctas . '" where cair_codigo like "' . $cair . '%" and (cair_ctaxcob="" or cair_ctaxcob is null)';
                            }
                            if (mb_stristr('RP', substr($docu, 0, 2)))
                            {
                                $sql_ctas2 = 'update cair0 set cair_ctaxpag="' . $xctas . '" where cair_codigo like "' . $cair . '%" and (cair_ctaxpag="" or cair_ctaxpag is null)';
                            }
                            $res_ctas2 = msql_query($sql_ctas2, $link_vcrx);
                        }

                        //           echo '<br>D*/*/*/'.$xctas;
                        

                        if ($xctas == '')
                        {
                            if (mb_stristr('RC', substr($docu, 0, 2)))
                            {
                                $sql_caircta = 'select cair_ctaxcob as ctacont from cair0 where cair_ctaxcob!="" and cair_ctaxcob is not null order by cair_ctaxcob';
                            }
                            if (mb_stristr('RP', substr($docu, 0, 2)))
                            {
                                $sql_caircta = 'select cair_ctaxpag as ctacont from cair0 where cair_ctaxpag!="" and cair_ctaxpag is not null order by cair_ctaxpag';
                            }
                            $res_caircta = msql_query($sql_caircta, $link_vcrx);
                            $xctas = @msql_result($res_caircta, 0, 'ctacont');
                            // 					echo '<br>E*/*/*/*/'.$cair.$xctas;
                            
                        }

                        // 					if(($cair=='-' or strlen($cair)==1 or strlen($xctas)<10) and $xctas!='' and mb_stristr('RC.RP',substr($docu,0,2)))
                        if (($cair == '-' or strlen($cair) == 1 or strlen($xctas) < 7) and $xctas != '' and mb_stristr('RC.RP', substr($docu, 0, 2)))
                        {
//                             					echo '<br>E*/*/*/*/'.$cair.$xctas;
                            $sql_cair = 'select * from ctas0 ';
                            if (mb_stristr('RC', substr($docu, 0, 2)))
                            {
                                $sql_cair .= 'where ctas_codigo like "1%" ';
                            }
                            if (mb_stristr('RP', substr($docu, 0, 2)))
                            {
                                $sql_cair .= 'where ctas_codigo like "2%" ';
                            }
                            $sql_cair .= ' and ctas_codigo like "' . substr($xctas, 0, 5) . '%" and ctas_descri like "%' . $puni . '%"';
                            //                               echo '<br>'.$sql_cair;
                            $res_cair = msql_query($sql_cair, $link_vcrx);
                            if (msql_num_rows($res_cair) != 0)
                            {
                                $xctas = msql_result($res_cair, 0, 'ctas_codigo');
                            }
                            // 					echo '<br>F*/*/*/*/'.$cair.$xctas;
                            
                        }
//                                         echo '<br>F*/*/*/*/'.$cair.$xctas;

                        if ($xctas == '')
                        {
                            $sql_ctas0 = 'select * from enti0,' . $tabla . '1 where enti=enti_codigo and idnum1="' . $idnum . '" order by enti_codigo desc';
                            $res_ctas0 = msql_query($sql_ctas0, $link_vcrx);

                            if ($stran == 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'enti_ctaxcob');
                            }
                            if ($stran == - 1)
                            {
                                $xctas = msql_result($res_ctas0, 0, 'enti_ctaxpag');
                            }
                        }

                        if ($xctas == '')
                        {
                            if (mb_stristr('RC', substr($docu, 0, 2)))
                            {
                                $xctas = '1010502';
                            }
                            //             if(mb_stristr('RP',substr($docu,0,2))){$xctas='201070101';}
                            if (mb_stristr('RP', substr($docu, 0, 2)))
                            {
                                $xctas = '2010701';
                            }
                        }

                        if ($cfg_empr == 'imcp' and strlen($cair)<=1)
                        {
                            if (mb_stristr('RC', substr($docu, 0, 2)))
                            {
                                                 $xctas='1010502';
                            }
                            //             if(mb_stristr('RP',substr($docu,0,2))){$xctas='2010701';}
                            
                        }

                        if ($xctas == '')
                        {
                            if ($stran == 1)
                            {
                                $xctas = $ctacre;
                            }
                            if ($stran == - 1)
                            {
                                $xctas = $ctadeb;
                            }
                        }

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . '*' . $xsigno . ',';
                        $sql_upd2 .= ' cair="' . $r_deta['cair'] . '",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                        //linea 2
                        // 					echo '<br>'.$sql_upd2;
                        
                    }

                }

                if ($tabla == 'inve')
                {
                    $xbode = msql_result($res_tab11, 0, 'bode');
                    if (mb_stristr('IB', $tdocu))
                    {
                        $stran = 1;
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', $docu, 'ctadeb');
                        };
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', 'IB10', 'ctadeb');
                        };
                        if ($xctas == '')
                        {
                            $xctas = '10103';
                        }
                    }

                    if (mb_stristr('EB', $tdocu))
                    {
                        $stran = - 1;
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', $docu, 'ctacre');
                        };
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', 'EB10', 'ctacre');
                        };
                        if ($xctas == '')
                        {
                            $xctas = '5101';
                        }
                    }

                    if (mb_stristr('IB11.IB13.IB18.....EB11.EB13.EB18', $docu))
                    {
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('bode', $xbode, 'ctacont');
                        };
                        $xctas = substr($xctas, 0, 5);
                    }
                    $xctas = '';
                     
                    if ($xctas == '')
                    {
                        $xctas = r_fiel('bode', $xbode, 'ctacont');
                    };

                    if ($xctas == '')
                    {
                        $sql_bodectas = 'select * from bode0 where bode_ctacont!="" and bode_ctacont is not null order by bode_codigo';
                        $res_bodectas = msql_query($sql_bodectas, $link_vcrx);
                        $xctas = msql_result($res_bodectas, 0, 'bode_ctacont');
                    }

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . '*1,';
                    $sql_upd2 .= ' detalle="' . $r_deta['concepto'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                             echo $sql_upd2;
                     
                     
//                     if ($docu == 'EB10' and $empr_codigo == 'imcp')
                     
//                      echo '*/*/*/*'.$docu;
//                      echo '*/*/*/*'.$empr_codigo;
                    if (mb_stristr('EB10.IB12',$docu) and $empr_codigo == 'imcp')
                    {
                        // ingreso diferido
                        $sql_tab122 = $sql_tab12;
                        $sql_tab122 = str_replace('*', '*,sum(abs(tsubt)) as tsubtd, sum(abs(cant)) as tcantd ', $sql_tab122);
                        $sql_tab122 = str_replace('order by ', 'group by item order by ', $sql_tab122);
                        // 					$res_tdet2=msql_query($sql_tab122,$link_vcrx);
//                                   explain_sql($sql_tab122);
                        
                    }

                    $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tsubt)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by item_lsub order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tsubt) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }

                    //         explain_sql($sql_tab12);
                    // GRABA DETALLE
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {
                        $xitem = $r_deta['item'];
                        $xlsub = $r_deta['item_lsub'];
                        $xbode = $r_deta['bode'];
                        $xctas = $r_deta['item_ctainve'];
                        $xptoe = $r_deta['ptoe'];

                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('item', $xitem, 'ctainve');
                        }
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('lsub', $xlsub, 'ctainve');
                        }
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('bode', $xbode, 'ctacont');
                        };

                        if ($xctas == '')
                        {
                            $sql_ctainve = 'select * from ctas0 where ctas_codigo like "1%" and ctas_descri like "INVENTA%" order by ctas_codigo';
                            $res_ctainve = msql_query($sql_ctainve, $link_vcrx);
                            $xctas = @msql_result($res_ctainve, 0, 'ctas_codigo');
                        }

                        if (mb_stristr('IB', $tdocu))
                        {
                            $stran = 1;
                            $xctas = '';
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', $docu, 'ctacre');
                            };
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', 'IB10', 'ctacre');
                            };
                            if ($xctas == '')
                            {
                                $xctas = '10103';
                            }
                        }

                        if (mb_stristr('EB', $tdocu))
                        {
                            $stran = - 1;
                            $xctas = '';
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', $docu, 'ctadeb');
                            };
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', 'EB10', 'ctadeb');
                            };
                            //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('lsub', $xlsub, 'ctacvta');
                            };
                            if ($xctas == '')
                            {
                                $xctas = '5101';
                            }
                        }

                        if (mb_stristr('IB11.IB13.IB18.....EB11.EB13.EB18', $docu))
                        {
                            $xctas = '';
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('bode', $xbode, 'ctacont');
                            };
                            $xctas = substr($xctas, 0, 5);
                        }

                        //         if(mb_stristr('IB11.EB11',$docu))
                        //         {
                        //           $xctas='';
                        // //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                        //           // inventario en transito
                        //   				if($xctas==''){$xctas='1010307';}
                        //         }
                        if (mb_stristr('IB10.IB13.EB13', $docu))
                        {
                            $xctas = '';
                            //   				if($xctas==''){$xctas='1010307';}
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                                 if($cfg_empr=='imcp')
                                 {$xctas='1010308';}
                            }
                        }

                        if (mb_stristr('IB11.EB11', $docu))
                        {
                            $xctas = '';
                            //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                            // inventario en transito
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                            }
                             
//                              if($cfg_empr=='pcs1'){$xctas='1103010';}
                             if($cfg_empr=='pcs1')
                             {
                                  $xctas='110301070001';
                             }
                        }

                        if (mb_stristr('IB12.EB12', $docu))
                        {
                            $xctas = '';
                            //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                            // inventario en transito
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('lsub', $xlsub, 'ctacvta');
                            };
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                            }
                        }

                        if (mb_stristr('IB17', $docu))
                        {
                            $xctas = '';
                           $xctas = r_fiel('docu', $docu, 'ctacre');
                             
                            if ($xctas == '')
                            {
                                 $xctas=$r_deta['ctas'];;
                            }
                             
                            // inventario ajuste x sobrante
                            if ($xctas == '')
                            {
                                $xctas = '4114';
                            }
                        }

                        if (mb_stristr('EB17', $docu))
                        {
                            $xctas = '';
                            // inventario ajuste x baja vencimiento o deterioro
                            //   				if($xctas==''){$xctas='510102';}
                            if ($xctas == '')
                            {
                                $xctas = '510103';
                            }
                             
                             
                        }

                        if ($xctas == '')
                        {
                            $xctas = '10103';
                        }

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . '*-1,';
                        $sql_upd2 .= ' item="' . $xitem . '",';
                        // 				$sql_upd2.=' item="'.$r_deta['item'].'",';
                        // 				$sql_upd2.=' csub="'.$r_deta['csub'].'",';
                        // 				$sql_upd2.=' cair="'.$r_deta['cair'].'",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                                   echo '<br>'.$sql_upd2;
                        $xctas = "";
                    }

                    // GRABA DETALLE INGRESO DIFERIDO
//                     if ($docu == 'EB10' and $empr_codigo == 'imcp')
                    if (mb_stristr('EB10.IB12',$docu) and $empr_codigo == 'imcp')
                    {
                        $cantidad = 0;
                        $xtingdif = 0;
                        $xidvtas = get_idvtas($docu, $idnum);
                         
//                          echo '**/*/'.$xidvtas;
                         
                         $docu2='FC10';
                         if(substr($docu,0,2)=='IB'){$docu2='NC10';}

                        $xvtas_ing_difer = vtas_ingr_difer($docu2, $xidvtas);
                         
//                          echo '/*/*/',$xvtas_ing_difer;

                        if ($xvtas_ing_difer == 1)
                        {

                            $res_tdet2 = msql_query($sql_tab122, $link_vcrx);
                            while ($r_deta2 = msql_fetch_assoc($res_tdet2))
                            {
                                $xitem = $r_deta2['item'];
                                $xlsub = $r_deta2['item_lsub'];
                                $xbode = $r_deta2['bode'];
                                $xctas = $r_deta2['item_ctainve'];
                                $xcant = $r_deta2['tcantd'];

                                $xctas = '';
                                if ($xctas == '')
                                {
                                    $xctas = r_fiel('item', $xitem, 'ctainve');
                                }
                                if ($xctas == '')
                                {
                                    $xctas = r_fiel('lsub', $xlsub, 'ctainve');
                                }
                                if ($xctas == '')
                                {
                                    $xctas = r_fiel('bode', $xbode, 'ctacont');
                                };

                                // 				if(mb_stristr('EB',$tdocu))
                                
                                {
                                    $stran = - 1;
                                    $xctas = '';
                                    if ($xctas == '')
                                    {
                                        $xctas = r_fiel('docu', $docu2, 'ctacre');
                                    };
                                    //           if($xctas==''){$xctas=r_fiel('docu','EB10','ctadeb');};
                                    if ($xctas == '')
                                    {
                                        $xctas = r_fiel('lsub', $xlsub, 'ctavtas');
                                    };
                                    if ($xctas == '')
                                    {
                                        $xctas = '4101';
                                    }
                                }

                                $iddet++;
                                $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                                $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                                $xpvta = 0;
                                $sql_pvta = 'select * from vtas2 where idnum2=' . $xidvtas . ' and item="' . $xitem . '"';
                                $res_pvta = @msql_query($sql_pvta, $link_vcrx);
                                if (@msql_num_rows($res_pvta) != 0)
                                {
                                    $xpvta = @msql_result($res_pvta, 0, 'puni');
                                }

                                $cantidad = $r_deta2['cant'] * $xpvta;
                                 if(substr($docu,0,2)=='IB'){$cantidad=$cantidad*-1;}

                                $sql_upd2 = 'update cont2 set ';
                                $sql_upd2 .= ' ctas="' . $xctas . '",';
                                // 					$sql_upd2.=' cant='.$r_deta['tcantd']*$r_deta['pvta'].'*-1,';
                                $sql_upd2 .= ' cant=' . $cantidad . '*-1,';
                                $sql_upd2 .= ' item="' . $xitem . '",';
                                $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                                $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                                $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                                $xtingdif = $xtingdif + $cantidad;

                                $xctas = "";
                            }

                            // 					if($xctas=='')
                            
                            {
                                $xctas = $ctaingredife;
                            }

                            $iddet++;
                            $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                            //           $cantidad=$r_deta['tcantd']*$r_deta['pvta'];
                            $cantidad = $r_deta['tcantd'] * $r_deta['puni'];

                            $sql_upd2 = 'update cont2 set ';
                            $sql_upd2 .= ' ctas="' . $xctas . '",';
                            // 					$sql_upd2.=' cant='.$r_deta['tcantd']*$r_deta['pvta'].'*-1,';
                            $sql_upd2 .= ' cant=' . $xtingdif . ',';
                            $sql_upd2 .= ' item="' . $xitem . '",';
                            $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                            $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                             
//                              echo '<br>'.$sql_upd2;

                        }

                    }

                }

                 
//                 echo '++++++'.$cfg_empr.$tabla;
                if ($tabla == 'inve' and $cfg_empr=='pcs1')
                {
                     if(1==2)
                     {
                    $xbode = msql_result($res_tab11, 0, 'bode');
                    if (mb_stristr('IB', $tdocu))
                    {
                        $stran = 1;
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', $docu, 'ctadeb');
                        };
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', 'IB10', 'ctadeb');
                        };
                        if ($xctas == '')
                        {
                            $xctas = '10103';
                        }
                    }

                    if (mb_stristr('EB', $tdocu))
                    {
                        $stran = - 1;
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', $docu, 'ctacre');
                        };
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('docu', 'EB10', 'ctacre');
                        };
                        if ($xctas == '')
                        {
                            $xctas = '5101';
                        }
                    }

                    if (mb_stristr('IB11.IB13.IB18.....EB11.EB13.EB18', $docu))
                    {
                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('bode', $xbode, 'ctacont');
                        };
                        $xctas = substr($xctas, 0, 5);
                    }
                    $xctas = '';
                     
                    if ($xctas == '')
                    {
                        $xctas = r_fiel('bode', $xbode, 'ctacont');
                    };

                    if ($xctas == '')
                    {
                        $sql_bodectas = 'select * from bode0 where bode_ctacont!="" and bode_ctacont is not null order by bode_codigo';
                        $res_bodectas = msql_query($sql_bodectas, $link_vcrx);
                        $xctas = msql_result($res_bodectas, 0, 'bode_ctacont');
                    }

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . $total * $stran . '*1,';
                    $sql_upd2 .= ' detalle="' . $r_deta['concepto'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    //         echo $sql_upd2;
                     
//                     if ($docu == 'EB10' and $empr_codigo == 'imcp')
                    if (mb_stristr('EB10.IB12',$docu) and $empr_codigo == 'imcp')
                    {
                        // ingreso diferido
                        $sql_tab122 = $sql_tab12;
                        $sql_tab122 = str_replace('*', '*,sum(abs(tsubt)) as tsubtd, sum(abs(cant)) as tcantd ', $sql_tab122);
                        $sql_tab122 = str_replace('order by ', 'group by item order by ', $sql_tab122);
                        // 					$res_tdet2=msql_query($sql_tab122,$link_vcrx);
                        //           explain_sql($sql_tab122);
                        
                    }

                    $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tsubt)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by item_lsub order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tsubt) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }

                    //         explain_sql($sql_tab12);
                           }
                     
                     $sql_dele='delete from cont2 where idnum2='.$idcont.' ';
                     $res_dele=msql_query($sql_dele,$link_vcrx);
                     
                    // GRABA DETALLE
                     $iddet=0;
                     msql_data_seek($res_tdet);
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {
                         
                         //PCS1
                        //$xctas = $r_deta['item_ctainve'];
                        $xctas = $r_deta['lsub_ctainve'];

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . ',';
                        $sql_upd2 .= ' item="' . $xitem . '",';
                        // 				$sql_upd2.=' item="'.$r_deta['item'].'",';
                        // 				$sql_upd2.=' csub="'.$r_deta['csub'].'",';
                        // 				$sql_upd2.=' cair="'.$r_deta['cair'].'",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                         
//                         echo '<br>+++++'.$sql_upd2;
                         
                         
                        $xitem = $r_deta['item'];
                        $xlsub = $r_deta['item_lsub'];
                        $xbode = $r_deta['bode'];
                        $xctas = $r_deta['item_ctainve'];
                        $xptoe = $r_deta['ptoe'];

                        $xctas = '';
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('item', $xitem, 'ctainve');
                        }
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('lsub', $xlsub, 'ctainve');
                        }
                        if ($xctas == '')
                        {
                            $xctas = r_fiel('bode', $xbode, 'ctacont');
                        };

                        if ($xctas == '')
                        {
                            $sql_ctainve = 'select * from ctas0 where ctas_codigo like "1%" and ctas_descri like "INVENTA%" order by ctas_codigo';
                            $res_ctainve = msql_query($sql_ctainve, $link_vcrx);
                            $xctas = @msql_result($res_ctainve, 0, 'ctas_codigo');
                        }

                        if (mb_stristr('IB', $tdocu))
                        {
                            $stran = 1;
                            $xctas = '';
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', $docu, 'ctacre');
                            };
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', 'IB10', 'ctacre');
                            };
                            if ($xctas == '')
                            {
                                $xctas = '10103';
                            }
                        }

                        if (mb_stristr('EB', $tdocu))
                        {
                            $stran = - 1;
                            $xctas = '';
                             $xctas = $r_deta['lsub_ctacvta'];
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', $docu, 'ctadeb');
                            };
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('docu', 'EB10', 'ctadeb');
                            };
                            //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('lsub', $xlsub, 'ctacvta');
                            };
                            if ($xctas == '')
                            {
                                $xctas = '5101';
                            }
                        }

                        if (mb_stristr('IB11.IB13.IB18.....EB11.EB13.EB18', $docu))
                        {
                            $xctas = '';
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('bode', $xbode, 'ctacont');
                            }
                            $xctas = substr($xctas, 0, 5);
                        }

                        //         if(mb_stristr('IB11.EB11',$docu))
                        //         {
                        //           $xctas='';
                        // //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                        //           // inventario en transito
                        //   				if($xctas==''){$xctas='1010307';}
                        //         }
                         
                        if (mb_stristr('IB10.IB13', $docu))
                        {
                            $xctas = '';
                            $xctas=r_fiel('docu',$docu,'ctacre'); 
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                                if($cfg_empr=='imcp'){$xctas='1010308';}
                            }
                        }

                        if (mb_stristr('EB13', $docu))
                        {
                            $xctas = '';
                            $xctas=r_fiel('docu',$docu,'ctadeb'); 
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                                if($cfg_empr=='imcp'){$xctas='1010308';}
                            }
                        }

                        if (mb_stristr('IB11.EB11', $docu))
                        {
                            $xctas = '';
                            //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                            // inventario en transito
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                            }
                           if($cfg_empr=='pcs1')
                           {
                                $xctas=r_fiel('lsub',$xlsub,'ctacvta');
                           }

                        }

                        if (mb_stristr('IB12.EB12', $docu))
                        {
                            $xctas = '';
                            //           if($xctas==''){$xctas=r_fiel('bode',$xbode,'ctacont');};
                            // inventario en transito
                            if ($xctas == '')
                            {
                                $xctas = r_fiel('lsub', $xlsub, 'ctacvta');
                            };
                            if ($xctas == '')
                            {
                                $xctas = '1010307';
                            }
                        }

                        if (mb_stristr('IB17', $docu))
                        {
                            $xctas = '';
                           $xctas = r_fiel('docu', $docu, 'ctacre');
                            if ($xctas == '')
                            {
                                 $xctas=$r_deta['ctas'];
                            }

                             // inventario ajuste x sobrante
                            if ($xctas == '')
                            {
                                $xctas = '4114';
                            }
                        }

                        if (mb_stristr('EB17', $docu))
                        {
                            $xctas = '';
                            // inventario ajuste x baja vencimiento o deterioro
                            //   				if($xctas==''){$xctas='510102';}
                            if ($xctas == '')
                            {
                                $xctas = '510103';
                            }
                            if($cfg_empr=='pcs1')
                            {
                                 $xctas='520102010007';
                                 if(substr($r_deta['item_lsub'],0,4)=='COMP')
                                 {$xctas='520101010005';}
                            }
                             
                        }

                        if ($xctas == '')
                        {
                            $xctas = '10103';
                        }

                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . $r_deta['tsubtd'] * $stran . '*-1,';
                        $sql_upd2 .= ' item="' . $xitem . '",';
                        // 				$sql_upd2.=' item="'.$r_deta['item'].'",';
                        // 				$sql_upd2.=' csub="'.$r_deta['csub'].'",';
                        // 				$sql_upd2.=' cair="'.$r_deta['cair'].'",';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

//                                   echo '<br>'.$sql_upd2;
                        $xctas = "";
                         
                         
                         
                    }

                    // GRABA DETALLE INGRESO DIFERIDO
//                     if ($docu == 'EB10' and $empr_codigo == 'imcp')
                    if (mb_stristr('EB10.IB12',$docu) and $empr_codigo == 'imcp')
                    {
                        $cantidad = 0;
                        $xtingdif = 0;
                        $xidvtas = get_idvtas($docu, $idnum);
                         
//                          echo '**/*/'.$xidvtas;
                         
                         $docu2='FC10';
                         if(substr($docu,0,2)=='IB'){$docu2='NC10';}

                        $xvtas_ing_difer = vtas_ingr_difer($docu2, $xidvtas);
                         
//                          echo '/*/*/',$xvtas_ing_difer;

                        if ($xvtas_ing_difer == 1)
                        {

                            $res_tdet2 = msql_query($sql_tab122, $link_vcrx);
                            while ($r_deta2 = msql_fetch_assoc($res_tdet2))
                            {
                                $xitem = $r_deta2['item'];
                                $xlsub = $r_deta2['item_lsub'];
                                $xbode = $r_deta2['bode'];
                                $xctas = $r_deta2['item_ctainve'];
                                $xcant = $r_deta2['tcantd'];

                                $xctas = '';
                                if ($xctas == '')
                                {
                                    $xctas = r_fiel('item', $xitem, 'ctainve');
                                }
                                if ($xctas == '')
                                {
                                    $xctas = r_fiel('lsub', $xlsub, 'ctainve');
                                }
                                if ($xctas == '')
                                {
                                    $xctas = r_fiel('bode', $xbode, 'ctacont');
                                };

                                // 				if(mb_stristr('EB',$tdocu))
                                
                                {
                                    $stran = - 1;
                                    $xctas = '';
                                    if ($xctas == '')
                                    {
                                        $xctas = r_fiel('docu', $docu2, 'ctacre');
                                    };
                                    //           if($xctas==''){$xctas=r_fiel('docu','EB10','ctadeb');};
                                    if ($xctas == '')
                                    {
                                        $xctas = r_fiel('lsub', $xlsub, 'ctavtas');
                                    };
                                    if ($xctas == '')
                                    {
                                        $xctas = '4101';
                                    }
                                }

                                $iddet++;
                                $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                                $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                                $xpvta = 0;
                                $sql_pvta = 'select * from vtas2 where idnum2=' . $xidvtas . ' and item="' . $xitem . '"';
                                $res_pvta = @msql_query($sql_pvta, $link_vcrx);
                                if (@msql_num_rows($res_pvta) != 0)
                                {
                                    $xpvta = @msql_result($res_pvta, 0, 'puni');
                                }

                                $cantidad = $r_deta2['cant'] * $xpvta;
                                 if(substr($docu,0,2)=='IB'){$cantidad=$cantidad*-1;}

                                $sql_upd2 = 'update cont2 set ';
                                $sql_upd2 .= ' ctas="' . $xctas . '",';
                                // 					$sql_upd2.=' cant='.$r_deta['tcantd']*$r_deta['pvta'].'*-1,';
                                $sql_upd2 .= ' cant=' . $cantidad . '*-1,';
                                $sql_upd2 .= ' item="' . $xitem . '",';
                                $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                                $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                                $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                                $xtingdif = $xtingdif + $cantidad;

                                $xctas = "";
                            }

                            // 					if($xctas=='')
                            
                            {
                                $xctas = $ctaingredife;
                            }

                            $iddet++;
                            $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                            //           $cantidad=$r_deta['tcantd']*$r_deta['pvta'];
                            $cantidad = $r_deta['tcantd'] * $r_deta['puni'];

                            $sql_upd2 = 'update cont2 set ';
                            $sql_upd2 .= ' ctas="' . $xctas . '",';
                            // 					$sql_upd2.=' cant='.$r_deta['tcantd']*$r_deta['pvta'].'*-1,';
                            $sql_upd2 .= ' cant=' . $xtingdif . ',';
                            $sql_upd2 .= ' item="' . $xitem . '",';
                            $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                            $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                            $res_upd2 = msql_query($sql_upd2, $link_vcrx);
                             
//                              echo '<br>'.$sql_upd2;

                        }

                    }

                }

                 
                 
                if ($tabla == 'nvdd')
                {

                    $total = $rescont = 1;
                    if ($rescont == 1)
                    {
                        $sql_tab12 = str_replace('*', '*,sum(abs(tcant)) as tsubtd', $sql_tab12);
                        $sql_tab12 = str_replace('order by ', 'group by ctas,docum order by ', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    else
                    {
                        $sql_tab12 = str_replace('*', '*,abs(tcant) as tsubtd', $sql_tab12);
                        $res_tdet = msql_query($sql_tab12, $link_vcrx);
                    }
                    // GRABA DETALLE
                    while ($r_deta = msql_fetch_assoc($res_tdet))
                    {

                        if ($r_deta['nvdd_tipo'] == 1)
                        {
                            $signo = 1;
                        }
                        if ($r_deta['nvdd_tipo'] == 2)
                        {
                            $signo = - 1;
                        }

                        $xctas = $r_deta['ctas'];

                        $docum = $r_deta['docum'];
                        $numer = $r_deta['numer'];
                        // 					if(substr($docum,0,2)=='FP' and $numer>0 and substr($xctas,0,1)>="4"){$xctas='';}
                        // 					if(substr($docum,0,2)=='FC' and $numer>0 and substr($xctas,0,1)>="4"){$xctas='';}
                        $xctas = r_fiel('nvdd', $r_deta['nvdd']);

                        if ($xctas == '')
                        {
                            // 					$sql_ctas0='select * from enti0,'.$tabla.'1 where enti=enti_codigo and idnum1="'.$idnum.'" order by enti_codigo desc';
                            // 					$res_ctas0=msql_query($sql_ctas0,$link_vcrx);
                            // 					if($stran==1){$xctas=msql_result($res_ctas0,0,'enti_ctaxcob');}
                            // 					if($stran==-1){$xctas=msql_result($res_ctas0,0,'enti_ctaxpag');}
                            
                        }

                        if ($xctas == '')
                        {
                            // 					$sql_ctas0='select * from docu0 where docu_codigo="'.$r_deta['docum'].'"  order by docu_codigo desc';
                            // 					$res_ctas0=msql_query($sql_ctas0,$link_vcrx);
                            // 					if($stran==1){$xctas=msql_result($res_ctas0,0,'docu_ctadeb');}
                            // 					if($stran==-1){$xctas=msql_result($res_ctas0,0,'docu_ctacre');}
                            
                        }

                        if ($xctas == '')
                        {
                            // 					if($stran==1){$xctas=$r_deta['zsub_ctaxcob'];}
                            // 					if($stran==-1){$xctas=$r_deta['tpro_ctaxpag'];}
                            
                        }

                        if ($xctas == '')
                        {
                            // 					if($stran==1){$xctas=r_fiel('zsub',r_fiel('enti',$enti,'zsub'),'ctaxcob');}
                            // 					if($stran==-1){$xctas=r_fiel('tpro',r_fiel('enti',$enti,'tpro'),'ctaxpag');}
                            
                        }

                        if ($xctas == '')
                        {
                            // 					if($stran==1){$xctas=$ctacre;}
                            // 					if($stran==-1){$xctas=$ctadeb;}
                            $ctas = '5010101';
                        }

                        // 					if($caba2!=""){$xctas=$cta13;}
                        $xctas = '2010301021';
                        $iddet++;
                        $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        $sql_upd2 = 'update cont2 set ';
                        $sql_upd2 .= ' ctas="' . $xctas . '",';
                        $sql_upd2 .= ' cant=' . ($r_deta['tsubtd'] * $signo) . ',';
                        $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                        $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                        $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                        if ($r_deta['nvdd_tipo'] == 1 or $r_deta['nvdd_tipo'] == 2)
                        {
                            $total = $total + ($r_deta['tsubtd'] * $signo);
                        }

                        $xctas = "";
                    }

                    $iddet++;
                    $sql_upd2 = 'insert into cont2(idnum2,iddet,cant)value("' . $idcont . '","' . $iddet . '","' . $total . '")';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                    $sql_upd2 = 'update cont2 set ';
                    $sql_upd2 .= ' ctas="' . $xctas . '",';
                    $sql_upd2 .= ' cant=' . ($total) . ',';
                    $sql_upd2 .= ' detalle="' . $r_deta['detalle'] . '"';
                    $sql_upd2 .= ' where idnum2=' . $idcont . ' and iddet=' . $iddet . '';
                    $res_upd2 = msql_query($sql_upd2, $link_vcrx);

                }

            }
        }

        if ((int)$numero == 0)
        {
            $sql_cont = 'update cont1 set status="O" ';
            $sql_cont .= 'where upper(mdfrom)="' . strtoupper($xmdfrom) . '" ';
            $sql_cont .= 'and idfrom="' . $idnum . '" ';
            $sql_cont .= 'and numero*1=0 ';
            $res_cont = msql_query($sql_cont, $link_vcrx);
            return $idcont;
        }

        //ingreso diferido
        if ($empr_codigo == 'imcp')
        {
            gen_ingr_difer($docu, $idnum);
        }

        return $idcont;
    }

    function gen_ingr_difer($docu, $idnum)
    {
        if ($idnum == ""){return;}
        $xvtas_ing_difer = vtas_ingr_difer($docu, $idnum);
        if ($xvtas_ing_difer == 0){return;}

        include ('../_cfg/config.php');

        $ctaingredife = '2020901';
        $sql_cont = 'select * from cont1 where docu="' . $docu . '" and idnum1>0 and lower(mdfrom)="vtas" and idfrom="' . $idnum . '" and status!="X"';
        $res_cont = msql_query($sql_cont, $link_vcrx);

        if (msql_num_rows($res_cont) == 1)
        {
            $idcont = @msql_result($res_cont, 0, 'idnum1');
            {
                $sql_updt = 'update cont2 set ctas="' . $ctaingredife . '" where idnum2="' . $idcont . '" and ctas like "4%"';
                $res_updt = msql_query($sql_updt, $link_vcrx);
            }
        }
    }

    function fill_ctas()
    {
        include ('../_cfg/config.php');
        // 	msql_query('insert into ctas0(ctas_codigo,ctas_descri)value("1","ACTIVOS")',$link_vcrx);
        // SIGNO			TIPO CTA	TIPO ESTADO
        // P=POSITIVO	T=TOTAL		1=ESTADO DE SITUACIÓN FINANCIERA
        // N=NEGATIVO	D=DETALLE	2=ESTADO DE RESULTADO INTEGRAL
        // D=DOBLE 							3=ESTADO DE FLUJOS DE EFECTIVO
        //											5=ESTADO DE CAMBIOS EN EL PATRIMONIO
        

        $filetxt = '../../_lib/ctas1super.txt';
        if (file_exists($filetxt))
        {
            $sql_ctas = 'delete from ctas0 where length(trim(ctas_codigo))=1';
            $res_ctas = msql_query($sql_ctas, $link_vcrx);
            //     echo '**/*/*'.msql_error($link_vcrx);
            foreach (file($filetxt) as $line)
            {
                $regis = explode("\t", trim($line));
                for ($ccol = 0;$ccol <= count($regis);$ccol++)
                {
                    $codigo = trim(substr($regis[$ccol], 0, strpos($regis[$ccol], ' ')));
                    $descri = trim(substr($regis[$ccol], strpos($regis[$ccol], ' ')));
                    $signo = substr($descri, strlen($descri) - 5, 1);
                    $tipoc = substr($descri, strlen($descri) - 3, 1);
                    $tipoe = substr($descri, strlen($descri) - 1, 1);
                    //  				$descri=ucfirst2(substr($descri,0,strlen($descri)-6));
                    $descri = strtoupper2(substr($descri, 0, strlen($descri) - 6));
                    if ($codigo != "")
                    {
                        echo '<br>' . $codigo . '-' . $descri . '    ' . $signo . $tipoc . $tipoe;
                        $sql_ctas = 'insert into ctas0(ctas_codigo,ctas_status)value("' . $codigo . '","-")';
                        $res_ctas = msql_query($sql_ctas, $link_vcrx);
                        $sql_ctas = 'update ctas0 set ctas_descri="' . $descri . '" where ctas_codigo="' . $codigo . '"';
                        $res_ctas = msql_query($sql_ctas, $link_vcrx);
                        $sql_ctas = 'update ctas0 set ctas_signo="' . $signo . '" where ctas_codigo="' . $codigo . '"';
                        $res_ctas = msql_query($sql_ctas, $link_vcrx);
                        $sql_ctas = 'update ctas0 set ctas_tipo="' . $tipoe . '" where ctas_codigo="' . $codigo . '"';
                        $res_ctas = msql_query($sql_ctas, $link_vcrx);
                        $sql_ctas = 'update ctas0 set ctas_super=1 where ctas_codigo="' . $codigo . '"';
                        $res_ctas = msql_query($sql_ctas, $link_vcrx);
                        // 					$sql_ctas ='update ctas0 set ctas_descri="'.$descri.'" where ctas_codigo="'.$codigo.'"';
                        // 					$res_ctas = msql_query($sql_ctas,$link_vcrx);
                        
                    }
                }
            }
        }

    }

    function gen_dtr1($cuenta, $fecha2 = "")
    {
        include ('../_cfg/config.php');

        // 	if($cuenta==''){$cuenta='9999999999'; return 'Falta Cuenta Contable';}
        if ($cuenta == '')
        {
            $cuenta = '306';
        }

        $fecha1 = date('Y-01-01');
        $fecha1 = strtotime('-1 year', strtotime($fecha1));
        $fecha1 = date('Y-m-d', $fecha1);

        if ($fecha2 == '')
        {
            $fecha2 = date('Y-12-31');
            $fecha2 = strtotime('-1 year', strtotime($fecha2));
            $fecha2 = date('Y-m-d', $fecha2);
        }
        else
        {
            $fecha2 = date('Y-12-31', strtotime($fecha2));
            $fecha1 = date('Y-01-01', strtotime($fecha2));
        }

        $numero = '0' . str_replace('-', '', $fecha2);
        $ptoe = '001001';
        $concepto = 'TRANSFERENCIA DE RESULTADOS AL ' . $fecha2;
        echo '<br' . $concepto;

        $sql_cont = 'select * from cont1 ';
        $sql_cont .= ' where status!="X" and status!="O"';
        $sql_cont .= ' and docu ="DTR1"';
        $sql_cont .= ' and fecha="' . $fecha2 . '"';
        $res_cont = msql_query($sql_cont, $link_vcrx);

        if (msql_num_rows($res_cont) == 0)
        {
            $sql_idtr = 'insert into cont1(docu,numero,fecha,status)value("DTR1","' . $numero . '","' . $fecha2 . '","-")';
            $res_idtr = msql_query($sql_idtr, $link_vcrx);
            $res_cont = msql_query($sql_cont, $link_vcrx);
        }

        $idnum = msql_result($res_cont, 0, 'idnum1');

        $sql_idtr = 'update cont1 set ';
        $sql_idtr .= ' concepto="' . $concepto . '",';
        $sql_idtr .= ' idate=now(),';
        $sql_idtr .= ' status="-"';
        $sql_idtr .= ' where idnum1=' . $idnum;
        $res_idtr = msql_query($sql_idtr, $link_vcrx);

        // 	echo msql_error($link_vcrx);
        $sql_ddtr = 'delete from cont2 where idnum2="' . $idnum . '"';
        $res_ddtr = msql_query($sql_ddtr, $link_vcrx);

        $sql_dtr1 = 'select *, sum(cant) as tcant ';
        // 	$sql_dtr1 ='select *, (cant) as tcant ';
        $sql_dtr1 .= ' from cont1 left join cont2 ';
        $sql_dtr1 .= ' on idnum1=idnum2 ';
        $sql_dtr1 .= ' where status!="X" and status!="O"';
        $sql_dtr1 .= ' and left(ctas,1) in ("4","5","6","7","8","9")';
        $sql_dtr1 .= ' and fecha>="' . $fecha1 . '"';
        $sql_dtr1 .= ' and fecha<="' . $fecha2 . '"';
        // 	$sql_dtr1.=' and docu not like "DTR1"';
        // 	$sql_dtr1.=' and ctas like "5020101001"';
        $sql_dtr1 .= ' group by ctas,csub ';
        $sql_dtr1 .= ' order by ctas,csub ';
        // 	$res_dtr1=msql_query($sql_dtr1,$link_vcrx);
        //   explain_sql($sql_dtr1);
        

        $iddet = 0;
        $total = 0;

        $iddet++;
        $sql_idtr = 'insert into cont2(idnum2,iddet)value("' . $idnum . '","' . $iddet . '")';
        $res_idtr = msql_query($sql_idtr, $link_vcrx);

        $res_dtr1 = msql_query($sql_dtr1, $link_vcrx);
        // 	echo $sql_dtr1;
        // 	echo msql_error($link_vcrx);
        while ($r_dtr1 = msql_fetch_assoc($res_dtr1))
        {
            if ($r_dtr1['tcant'] != 0)
            {
                $iddet++;
                $sql_idtr = 'insert into cont2(idnum2,iddet)value("' . $idnum . '","' . $iddet . '")';
                $res_idtr = msql_query($sql_idtr, $link_vcrx);

                $sql_idtr = 'update cont2 set ';
                $sql_idtr .= ' ctas="' . $r_dtr1['ctas'] . '",';
                $sql_idtr .= ' cant=' . $r_dtr1['tcant'] . '*(-1),';
                $sql_idtr .= ' iddet="' . $iddet . '"';
                $sql_idtr .= ' where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
                $res_idtr = msql_query($sql_idtr, $link_vcrx);
                $total += $r_dtr1['tcant'];
                // 		echo '<br>'.$sql_idtr;
                echo '<br>' . $r_dtr1['ctas'] . ' ' . number_format($r_dtr1['tcant'], 2, '.', ',');
                // 			echo '<br>'.$r_dtr1['fecha'].' '.$r_dtr1['ctas'].' '.number_format($r_dtr1['tcant'],2,'.',',');
                // 		echo '<br>'.$sql_idtr;
                
            }
        }

        $sql_idtr = 'update cont2 set ';
        $sql_idtr .= ' ctas="' . $cuenta . '",';
        $sql_idtr .= ' cant="' . $total . '",';
        $sql_idtr .= ' iddet=1 ';
        $sql_idtr .= ' where idnum2="' . $idnum . '" and iddet=1 ';
        $res_idtr = msql_query($sql_idtr, $link_vcrx);

        echo '<br>TOTAL:' . $total;

    }

    function apli_rpro($idnum)
    {
        $sql_comp = 'select * from comp1 left join comp2 on idnum1=idnum2 ';
        $sql_comp .= 'where idnum1 ="' . $idnum . '"';
        $sql_comp .= 'and status!="O" and status!="X"';
        $res_comp = msql_query($sql_comp, $link_vcrx);
        while ($aso_comp = msql_fetch_assoc($res_comp))
        {
            $xenti = substr($aso_comp['enti'], 0, 10);
            $xiddet = $aso_comp['iddet'];
            $xitem = $aso_comp['item'];
            $xcair = $aso_comp['cair'];
            $xfecha = $aso_comp['fecha'];

            $lrrta = get_lrrta($xenti, $xitem, $xcair);
            $lriva = get_lriva($xenti, $xitem);

            $sql_ucom = 'update comp2 set rrta="' . $lrrta . '" ';
            $sql_ucom .= 'where idnum2="' . $idnum . '" and iddet="' . $xiddet . '" ';
            $sql_ucom .= 'and (rrta="" or rrta is null)';
            $res_ucom = msql_query($sql_ucom, $link_vcrx);

            $sql_ucom = 'update comp2 set riva="' . $lriva . '" ';
            $sql_ucom .= 'where idnum2="' . $idnum . '" and iddet="' . $xiddet . '" ';
            $sql_ucom .= 'and (riva="" or riva is null)';
            $res_ucom = msql_query($sql_ucom, $link_vcrx);
        }
    }

    function Xgen_rpro($idnum = '')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($idnum == '')
        {
            return;
        }

        $sql_comp = 'select * from comp11 where idnum1=' . $idnum;
        $res_comp = msql_query($sql_comp, $link_vcrx);
        $enti = msql_result($res_comp, 0, 'enti');
        $docu = msql_result($res_comp, 0, 'docu');
        $ptoe = msql_result($res_comp, 0, 'ptoe');
        $numero = msql_result($res_comp, 0, 'numero');
        $fecha = msql_result($res_comp, 0, 'fecha');
        $rrta = msql_result($res_comp, 0, 'rrta');
        $riva = msql_result($res_comp, 0, 'riva');
        $fechamax = date('Y-m-d', strtotime($fecha . ' +5 days'));
        $xfecha = date('Y-m-d', strtotime('today'));

        echo $numero;
        return $fecha;

        if ($rrta == 0 and $riva == 0)
        {
            return;
        }
        if ($xfecha > $fechamax)
        {
            return;
            die('ERROR : Fecha fuera de tiempo');
        }

        $sql_retp = 'select * from retp1 left join retp2 on idnum1=idnum2 ';
        $sql_retp .= 'where enti like "' . substr($enti, 0, 10) . '%" ';
        $sql_retp .= ' and docum="' . $docu . '"';
        // 	$sql_retp.=' and ptoem="'.$ptoe.'"';
        $sql_retp .= ' and numer="' . $numero . '"';
        $sql_retp .= ' and fecha>="' . $fecha . '"';
        $sql_retp .= ' and status!="O" and status!="X"';
        $res_retp = msql_query($sql_retp, $link_vcrx);
        if (msql_num_rows($res_retp) != 0)
        {
            return;
        } //ya tiene retencion
        $newdocu = 'RPRO';
        $newnumero = nume_docu($newdocu);
        $newidnum = clon_docu($docu, $idnum, $newdocu);

        $sql_rete = 'delete from retp2 where idnum2=' . $newidnum;
        $res_rete = msql_query($sql_rete, $link_vcrx);

        $ciddet = 0;
        if ($rrta != 0)
        {
            $sql_rrta = 'select cair,sum(tsubt) as tsubt, sum(tdcto) as tdcto, prrta, sum(rrta) as rrta from comp12 ';
            $sql_rrta .= ' where idnum1=' . '"' . $idnum . '" ';
            //     $sql_rrta.=' group by idnum1,cair order by cair';
            $sql_rrta .= ' group by cair order by cair';
            $res_rrta = msql_query($sql_rrta, $link_vcrx);
            while ($aso_rrta = msql_fetch_assoc($res_rrta))
            {
                $ciddet++;
                $sql_rete = 'insert into retp2(idnum2,iddet)value("' . $newidnum . '","' . $ciddet . '")';
                $res_rete = msql_query($sql_rete, $link_vcrx);
                $sql_rete = 'update retp2 set ';
                $sql_rete .= ' docum="' . $docu . '",';
                $sql_rete .= ' ptoem="' . $ptoe . '",';
                $sql_rete .= ' numer="' . $numero . '",';
                $sql_rete .= ' cant="' . $aso_rrta['tsubt'] - $aso_rrta['tdcto'] . '",';
                $sql_rete .= ' puni="' . $aso_rrta['prrta'] . '",';
                $sql_rete .= ' cair="' . $aso_rrta['cair'] . '",';
                $sql_rete .= ' detalle=""';
                $sql_rete .= ' where idnum2="' . $newidnum . '" and iddet="' . $ciddet . '"';
                $res_rete = msql_query($sql_rete, $link_vcrx);
            }
        }

        if ($riva != 0)
        {
            $sql_riva = 'select iva, sum(tiva) as tiva, priva, sum(riva) as riva from comp12 ';
            $sql_riva .= ' where idnum1=' . '"' . $idnum . '" and iva>0';
            $sql_riva .= ' group by idnum1,priva order by priva';
            $res_riva = msql_query($sql_riva, $link_vcrx);
            while ($aso_riva = msql_fetch_assoc($res_riva))
            {
                $cair = "-";
                $ciddet++;
                $sql_rete = 'insert into retp2(idnum2,iddet)value("' . $newidnum . '","' . $ciddet . '")';
                $res_rete = msql_query($sql_rete, $link_vcrx);
                $sql_rete = 'update retp2 set ';
                $sql_rete .= ' docum="' . $docu . '",';
                $sql_rete .= ' ptoem="' . $ptoe . '",';
                $sql_rete .= ' numer="' . $numero . '",';
                $sql_rete .= ' cant="' . $aso_riva['tiva'] . '",';
                $sql_rete .= ' puni="' . $aso_riva['priva'] . '",';
                $sql_rete .= ' cair="' . $cair . '",';
                $sql_rete .= ' detalle=""';
                $sql_rete .= ' where idnum2="' . $newidnum . '" and iddet="' . $ciddet . '"';
                $res_rete = msql_query($sql_rete, $link_vcrx);
            }
        }

        return;

    }

    function tran_carr($idnum)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }

        $sql_tran = 'select from carr2 ';
        $sql_tran .= 'left join item0 on item=item_codigo ';
        $sql_tran .= 'where idnum2="' . $idnum . '" ';
        $sql_tran .= 'and item_descri like "TRANSP%" ';
        $res_tran = msql_query($sql_tran, $link_vcrx);
        if (msql_num_rows($res_tran) == 0)
        {
            $sql_tran = 'insert into ';
            $sql_tran .= 'left join item0 on item=item_codigo ';
            $res_tran = msql_query($sql_tran, $link_vcrx);
        }

        $sql_tran = 'select * from carr2 ';
        $sql_tran .= 'left join item0 on item=item_codigo ';
        $sql_tran .= 'where idnum2="' . $idnum . '" ';
        $sql_tran .= 'and item_descri not like "TRANSP%" ';
        $res_tran = msql_query($sql_tran, $link_vcrx);
        if (msql_num_rows($res_tran) > 0)
        {
            $sql_tran = 'select * from carr2 ';
            $sql_tran .= 'left join item0 on item=item_codigo ';
        }

    }

    function add_carr($idnum, $item, $cant = 1, $deta = '')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');
        // 	include('php_gene1.php');
        //   echo '*****'.$deta;
        //   echo '1111';
        if ($docu == '' or $docu == 'undefined')
        {
            $docu = 'CAR1';
        }
        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }
        if ($item == '' or $item == 'undefined' or substr($item, 0, 2) == '99')
        {
            return;
        }
        if (strlen(trim($item)) < 6)
        {
            return;
        }

        $xptoe = '001101';

        // echo '22222';
        $sql_updt = 'update carr1 set ptoe="' . $xptoe . '" where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr1 set numero=lpad(idnum1,9,"0") where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr1 set idate=now() where idnum1="' . $idnum . '" and idate is null';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr1 set fecha=now() where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr1 set status="-" where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_idet = 'select * from carr1 where idnum1="' . $idnum . '" ';
        $res_idet = msql_query($sql_idet, $link_vcrx);
        $docu = msql_result($res_idet, 0, 'docu');

        $sql_item = 'select * from item0 where item_codigo like "' . trim($item) . '%" order by item_codigo';
        $res_item = msql_query($sql_item, $link_vcrx);
        $item = @msql_result($res_item, 0, 'item_codigo');

        //   echo '****'.$cfg_empr;
        //   if($cfg_empr=='dly1'){echo 'aquiZZZZZZZZZZZZZZZZZZZZZzz';dly1_calc1($docu,$idnum);}
        

        $iddet = 0;
        $sql_idet = 'select * from carr2 where idnum2="' . $idnum . '" order by iddet desc';
        $res_idet = msql_query($sql_idet, $link_vcrx);
        if (msql_num_rows($res_idet) != 0)
        {
            $iddet = msql_result($res_idet, 0, 'iddet');
        }

        $sql_carr = 'select * from carr2 where idnum2="' . $idnum . '" and item="' . $item . '" order by iddet desc';
        $res_carr = msql_query($sql_carr, $link_vcrx);

        if (msql_num_rows($res_carr) == 0)
        {
            $iddet++;
            $sql_icarr = 'insert into carr2(idnum2,iddet,item)value("' . $idnum . '","' . $iddet . '","' . $item . '")';
            $res_icarr = msql_query($sql_icarr, $link_vcrx);
            $res_carr = msql_query($sql_carr, $link_vcrx);
        }
        $iddet = msql_result($res_carr, 0, 'iddet');

        $sql_updt = 'update carr2 set cant=0 where idnum2="' . $idnum . '" and cant is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set dcto=0 where idnum2="' . $idnum . '" and dcto is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set ice=0 where idnum2="' . $idnum . '" and ice is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set iva=0 where idnum2="' . $idnum . '" and iva is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set irbp=0 where idnum2="' . $idnum . '" and irbp is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set detalle="" where idnum2="' . $idnum . '" and detalle is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set cant=cant+' . $cant . ' where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update carr2 set idate2=now() where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        if (strlen(trim($deta)) > 2)
        {
            $sql_updt = 'update carr2 set detalle=concat(detalle," /",' . $deta . ') where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);
        }

        $msgalert = '<msgalert style="display:none">';
        if (msql_error($link_vcrx) == '')
        {
            $msgalert .= 'Se añadió al Carrito el Código: ' . $item . ' (' . $cant . ')';
        }
        $msgalert .= '<msgalert>';

        echo '<result>';
        // 	echo $msgalert;
        echo '</result>';

        $sql_updt = 'update carr2,item0 set puni=item_puni, iva=item_iva where item=item_codigo and idnum2="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        return;
    }

    function add_carr2($docu, $item, $cant = 0, $deta = '', $enti2 = '')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');
        // 	include('php_gene1.php');
        if (empty($docu))
        {
            $docu = 'CAR1';
        }
        if (empty($cant))
        {
            return;
        }

        //   $idnum=get_carr($docu);
        

        if ($enti2 == '' or $enti2 == 'undefined')
        {
            $enti2 = '';
        }
        if ($docu == '' or $docu == 'undefined')
        {
            $docu = 'CAR1';
        }
        // 	if($idnum=='' or $idnum=='undefined'){return;}
        // 	if($item=='' or $item=='undefined' or substr($item,0,2)=='99'){return;}
        if ($item == '' or $item == 'undefined')
        {
            return;
        }
        if (strlen(trim($item)) < 6)
        {
            return;
        }

        $tabla = r_fiel('docu', $docu, 'tabla');

        $idnum = 0;

        if ($tabla == 'carr')
        {
            $idnum = get_carr($docu);
        }

        if ($tabla == 'clie')
        {
            $idnum = get_clie($docu, 0, $enti2);
        }

        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }
        $xptoe = '001101';

        //   echo '*/*/*/*/*/'.$tabla.$idnum;
        

        if (substr($item, 0, 2) != '99')
        {
            $sql_item = 'select * from item0 where item_codigo like "' . trim($item) . '%" order by item_codigo';
            $res_item = msql_query($sql_item, $link_vcrx);
            $item = @msql_result($res_item, 0, 'item_codigo');

            $sql_updt = 'update ' . $tabla . '1 set ';
            $sql_updt .= 'enti2="' . $enti2 . '", ';
            $sql_updt .= 'toenti="' . $enti2 . '", ';
            $sql_updt .= 'ptoe="' . $xptoe . '", ';
            $sql_updt .= 'ptov="' . $xptoe . '", ';
            $sql_updt .= 'status="-" ';
            $sql_updt .= 'where idnum1="' . $idnum . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);

            //     $sql_updt='update '.$tabla.'1 set enti2="'.$enti2.'" where idnum1="'.$idnum.'"';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'1 set toenti="'.$enti2.'" where idnum1="'.$idnum.'"';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'1 set ptoe="'.$xptoe.'" where idnum1="'.$idnum.'"';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'1 set ptov="'.$xptoe.'" where idnum1="'.$idnum.'"';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            if ($tabla == 'carr')
            {
                $sql_updt = 'update ' . $tabla . '1 set numero=lpad(idnum1,9,"0") where idnum1="' . $idnum . '"';
                $res_updt = msql_query($sql_updt, $link_vcrx);

                $sql_updt = 'update ' . $tabla . '1 set idate=now() where idnum1="' . $idnum . '" and idate is null';
                $res_updt = msql_query($sql_updt, $link_vcrx);

                $sql_updt = 'update ' . $tabla . '1 set fecha=now() where idnum1="' . $idnum . '"';
                $res_updt = msql_query($sql_updt, $link_vcrx);
            }

            $sql_updt = 'update ' . $tabla . '1 set status="-" where idnum1="' . $idnum . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);

            $sql_idet = 'select * from ' . $tabla . '1 where idnum1="' . $idnum . '" ';
            $res_idet = msql_query($sql_idet, $link_vcrx);
            $docu = msql_result($res_idet, 0, 'docu');

            $iddet = 0;
            $sql_idet = 'select * from ' . $tabla . '2 where idnum2="' . $idnum . '" order by iddet desc';
            $res_idet = msql_query($sql_idet, $link_vcrx);
            if (msql_num_rows($res_idet) != 0)
            {
                $iddet = msql_result($res_idet, 0, 'iddet');
            }

            $sql_carr = 'select * from ' . $tabla . '2 where idnum2="' . $idnum . '" and item="' . $item . '" order by iddet desc';
            $res_carr = msql_query($sql_carr, $link_vcrx);

            if (msql_num_rows($res_carr) == 0)
            {
                $iddet++;
                $sql_icarr = 'insert into ' . $tabla . '2(idnum2,iddet,item)value("' . $idnum . '","' . $iddet . '","' . $item . '")';
                $res_icarr = msql_query($sql_icarr, $link_vcrx);
                $res_carr = msql_query($sql_carr, $link_vcrx);
            }
            $iddet = msql_result($res_carr, 0, 'iddet');

            $sql_updt = 'update ' . $tabla . '2 set ';
            $sql_updt .= 'cant=case when cant is null then 0 else cant end, ';
            $sql_updt .= 'dcto=case when dcto is null then 0 else dcto end, ';
            $sql_updt .= 'ice=case when ice is null then 0 else ice end, ';
            $sql_updt .= 'iva=case when iva is null then 0 else iva end, ';
            $sql_updt .= 'irbp=case when irbp is null then 0 else irbp end, ';
            $sql_updt .= 'detalle=detalle ';
            $sql_updt .= 'where idnum2="' . $idnum . '" ';
            $res_updt = msql_query($sql_updt, $link_vcrx);

            //     $sql_updt='update '.$tabla.'2 set cant=0 where idnum2="'.$idnum.'" and cant is null ';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'2 set dcto=0 where idnum2="'.$idnum.'" and dcto is null ';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'2 set ice=0 where idnum2="'.$idnum.'" and ice is null ';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'2 set iva=0 where idnum2="'.$idnum.'" and iva is null ';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'2 set irbp=0 where idnum2="'.$idnum.'" and irbp is null ';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            //     $sql_updt='update '.$tabla.'2 set detalle="" where idnum2="'.$idnum.'" and detalle is null ';
            //     $res_updt=msql_query($sql_updt,$link_vcrx);
            $sql_updt = 'update ' . $tabla . '2 set cant=cant+' . $cant . ' where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);

            $sql_updt = 'update ' . $tabla . '2 set idate2=now() where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);

            if (strlen(trim($deta)) > 2)
            {
                $sql_updt = 'update ' . $tabla . '2 set detalle=concat(detalle," /",' . $deta . ') where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
                $res_updt = msql_query($sql_updt, $link_vcrx);
            }

            $msgalert = '<msgalert style="display:none">';
            if (msql_error($link_vcrx) == '')
            {
                $msgalert .= 'Se añadió al Carrito el Código: ' . $item . ' (' . $cant . ')';
            }
            $msgalert .= '<msgalert>';

        }

        $sql_updt = 'update ' . $tabla . '2,item0 set puni=item_puni, iva=item_iva where item=item_codigo and idnum2="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        //   echo '<msgalert>';
        if ($tabla == 'carr')
        {
            $xcarrito = get_carr($docu, 1);
        }

        if ($tabla == 'clie')
        {
            $xcarrito = get_clie($docu, 1, $enti2);
        }

        $idnum = $xcarrito[1];
        $ptoe = $xcarrito[2];
        $numero = $xcarrito[3];
        $unidades = $xcarrito[4];
        $total = $xcarrito[5];

        echo '<result>';
        echo '<idnum1>' . $idnum . '</idnum1>';
        echo '<ptoe>' . $ptoe . '</ptoe>';
        echo '<numero>' . $numero . '</numero>';
        echo '<unidades>' . number_format($unidades, 0) . '</unidades>';
        echo '<total>' . number_format($total, 2) . '</total>';
        // 	echo $msgalert;
        echo '</result>';

        //   echo '</msgalert>';
        //   vali_regidocu($docu,$idnum);
        return;
    }

    function add_clieX($idnum, $item, $cant = 1, $deta = '')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }
        if ($item == '' or $item == 'undefined' or substr($item, 0, 2) == '99')
        {
            return;
        }
        if (strlen(trim($item)) < 6)
        {
            return;
        }

        $newdocu = 'PF19';
        $newnumero = nume_docu($newdocu);

        $sql_updt = 'update clie1 set numero=lpad(' . $newnumero . ',9,"0") where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        // 	$sql_updt='update carr1 set idate=now() where idnum1="'.$idnum.'" and idate is null';
        // 	$res_updt=msql_query($sql_updt,$link_vcrx);
        $sql_updt = 'update clie1 set fecha=now() where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie1 set status="-" where idnum1="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_idet = 'select * from clie1 where idnum1="' . $idnum . '" ';
        $res_idet = msql_query($sql_idet, $link_vcrx);
        $docu = msql_result($sql_idet, 0, 'docu');

        $iddet = 0;
        $sql_idet = 'select * from clie2 where idnum2="' . $idnum . '" order by iddet desc';
        $res_idet = msql_query($sql_idet, $link_vcrx);
        if (msql_num_rows($res_idet) != 0)
        {
            $iddet = msql_result($res_idet, 0, 'iddet');
        }

        $sql_carr = 'select * from clie2 where idnum2="' . $idnum . '" and item="' . $item . '" order by iddet desc';
        $res_carr = msql_query($sql_carr, $link_vcrx);

        if (msql_num_rows($res_carr) == 0)
        {
            $iddet++;
            $sql_icarr = 'insert into clie2(idnum2,iddet,item)value("' . $idnum . '","' . $iddet . '","' . $item . '")';
            $res_icarr = msql_query($sql_icarr, $link_vcrx);
            $res_carr = msql_query($sql_carr, $link_vcrx);
        }
        $iddet = msql_result($res_carr, 0, 'iddet');

        $sql_updt = 'update clie2 set cant=0 where idnum2="' . $idnum . '" and cant is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie2 set dcto=0 where idnum2="' . $idnum . '" and dcto is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie2 set ice=0 where idnum2="' . $idnum . '" and ice is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie2 set iva=0 where idnum2="' . $idnum . '" and iva is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie2 set irbp=0 where idnum2="' . $idnum . '" and irbp is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie2 set detalle="" where idnum2="' . $idnum . '" and detalle is null ';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        $sql_updt = 'update clie2 set cant=cant+' . $cant . ' where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        if (strlen(trim($deta)) > 2)
        {
            $sql_updt = 'update clie2 set detalle=concat(detalle," /",' . $deta . ') where idnum2="' . $idnum . '" and iddet="' . $iddet . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);
        }

        $msgalert = '<msgalert style="display:none">';
        if (msql_error($link_vcrx) == '')
        {
            $msgalert .= 'Se añadió al Pedido el Código: ' . $item . ' (' . $cant . ')';
        }
        $msgalert .= '<msgalert>';

        echo '<result>';
        // 	echo $msgalert;
        echo '</result>';

        $sql_updt = 'update clie2,item0 set puni=item_puni, iva=item_iva where item=item_codigo and idnum2="' . $idnum . '"';
        $res_updt = msql_query($sql_updt, $link_vcrx);

        return;
    }

    function upd_carr($idnum, $item, $cant)
    {

    }

    function del_deta($docu, $idnum, $iddet)
    {
        // session_start();
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($docu == '' or $docu == 'undefined')
        {
            return;
        }
        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }
        if ($iddet == '' or $iddet == 'undefined')
        {
            $iddet = '';
        }
        // 	if($user_codigo=='' or $user_codigo=='undefined'){return;}
        $tablad = r_fiel('docu', $docu, 'tabla');
        $sql_carr = 'delete from ' . $tablad . '2 where idnum2 ="' . $idnum . '"';
        if ($iddet != "")
        {
            $sql_carr .= ' and iddet="' . $iddet . '"';
        }
        $res_carr = msql_query($sql_carr, $link_vcrx);

        // 	if(msql_error($link_vcrx)=='')
        // 	{$msgalert.='Se Eliminó el Código:'.$item.' ('.$cant.')';}
        // 	$msgalert.='<msgalert>';
        // 	echo'<result>';
        // 	echo $msgalert;
        // 	echo'</result>';
        
    }

    function del_carr($idnum, $iddet = '')
    {
        // session_start();
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }
        if ($iddet == '' or $iddet == 'undefined')
        {
            $iddet = '';
        }
        // 	if($user_codigo=='' or $user_codigo=='undefined'){return;}
        $sql_carr = 'delete from carr2 where idnum2 ="' . $idnum . '"';
        if ($iddet != "")
        {
            $sql_carr .= ' and iddet="' . $iddet . '"';
        }
        $res_carr = msql_query($sql_carr, $link_vcrx);

        // 	if(msql_error($link_vcrx)=='')
        // 	{$msgalert.='Se Eliminó el Código:'.$item.' ('.$cant.')';}
        // 	$msgalert.='<msgalert>';
        // 	echo'<result>';
        // 	echo $msgalert;
        // 	echo'</result>';
        
    }

    function del_clie($idnum, $iddet)
    {
        // session_start();
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($idnum == '' or $idnum == 'undefined')
        {
            return;
        }
        if ($iddet == '' or $iddet == 'undefined')
        {
            $iddet = '';
        }

        $sql_carr = 'delete from clie2 where idnum2 ="' . $idnum . '"';
        if ($iddet != "")
        {
            $sql_carr .= ' and iddet="' . $iddet . '"';
        }
        $res_carr = msql_query($sql_carr, $link_vcrx);

    }

    function carr2clie($idnum, $enti2 = '')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if (empty($idnum))
        {
            return;
        }

        $min_valor = 1;
        $min_canti = 1;

        $sql_carr = 'select * from carr2 where idnum2="' . $idnum . '"';
        $res_carr = msql_query($sql_carr, $link_vcrx);
        if (msql_num_rows($res_carr) == 0)
        {
            $msgalert = '<msgalert style="display:none">';
            $msgalert .= 'EL CARRITO ESTA VACIO ';
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
            return;
        }

        // 	if($user_codigo!='10')
        if ($cfg_empr == 'gmny')
        {
            $pri_valor = 300;

            //7/ene/18
            $pri_valor = 200;

            //26/feb/18
            $pri_valor = 50;

            //7/ago/18
            $pri_valor = 100;

            //14/ene/19
            $pri_valor = 300;

            //31/ene/20
            $pri_valor = 300;
            // 		$pri_valor=300/1.12;
            //31/ene/20
            $pri_valor = 1;

            // 		//7/jun/20
            // 		$pri_valor=100;
            // 		//8/jun/20
            // 		$pri_valor=100;
            // 		//3/jul/20
            $pri_valor = 50;

            // 		//25/sep/20
            $pri_valor = 100;

            // 		//22/feb/21
            $pri_valor = 300;

            $min_valor = $pri_valor;
            $min_canti = 1;

            //valida ventas del ultimo mes
            $fecha1 = date('Y-m-d', strtotime('-1 month'));
            $fecha2 = $fechaa;

            //     $user_cedula='0704548353';
            //     $idnum=60;
            $sql_carr = 'select *, sum(case when docu like "NC%" then abs(total)*-1 else abs(total) end) as stotal from vtas12 ';
            $sql_carr .= ' where fecha between "' . $fecha1 . '" and "' . $fecha2 . '"';
            $sql_carr .= ' and enti like "' . $user_cedula . '%" ';
            $res_carr = msql_query($sql_carr, $link_vcrx);

            $min_valor = $min_valor - msql_result($res_carr, 0, 'stotal');

            if ($min_valor < 1)
            {
                $min_valor = 1;
            }
            if ($min_valor < $pri_valor)
            {
                $min_canti = 1;
            }

            $sql_carr = 'select *, sum(total) as stotal, sum(tsubt) as stsubt from carr12 where idnum2="' . $idnum . '"';
            $res_carr = msql_query($sql_carr, $link_vcrx);
            $stsubt = msql_result($res_carr, 0, 'stsubt');
            $stotal = msql_result($res_carr, 0, 'stotal');

            //     if($stotal<$min_valor)
            if ($stotal < $pri_valor)
            {
                $msgalert = '<msgalert style="display:none">';
                $msgalert .= ' ***** ERROR : ';
                // 			$msgalert.='Orden de Pedido debe ser MINIMO : '.number_format($min_valor,2);
                $msgalert .= 'Orden de Pedido debe ser MINIMO : ' . number_format($pri_valor, 2);
                $msgalert .= ' ***** ';
                $msgalert .= '<msgalert>';

                echo '<result>';
                echo $msgalert;
                echo '</result>';
                return;
            }

            $sql_carr = 'select *, sum(cant) as scant from carr12 where idnum2="' . $idnum . '" group by item_raiz having scant<' . $min_canti . '';
            $res_carr = msql_query($sql_carr, $link_vcrx);
            if (msql_num_rows($res_carr) > 0)
            {
                $msgalert = '<msgalert style="display:none">';
                $msgalert .= ' ***** ERROR : ';
                $msgalert .= 'Cantidad por ITEM debe ser MINIMO : ' . number_format($min_canti, 0);
                $msgalert .= ' ***** ';
                $msgalert .= '<msgalert>';

                echo '<result>';
                echo $msgalert;
                echo '</result>';
                return;
            }

        }

        if ($cfg_empr == 'gnya')
        {
            //31/ene/20
            $pri_valor = 1;

            //22/mar/21
            $pri_cant = 3;

            //31/may/20
            $pri_cant = 1;

            $min_valor = $pri_valor;
            $min_canti = $pri_cant;

            //valida ventas del ultimo mes
            $fecha1 = date('Y-m-d', strtotime('-1 month'));
            $fecha2 = $fechaa;

            //     $user_cedula='0704548353';
            //     $idnum=60;
            $sql_carr = 'select *, sum(case when docu like "NC%" then abs(total)*-1 else abs(total) end) as stotal from vtas12 ';
            $sql_carr .= ' where fecha between "' . $fecha1 . '" and "' . $fecha2 . '"';
            $sql_carr .= ' and enti like "' . $user_cedula . '%" ';
            $res_carr = msql_query($sql_carr, $link_vcrx);

            $min_valor = $min_valor - msql_result($res_carr, 0, 'stotal');

            if ($min_valor < 1)
            {
                $min_valor = 1;
            }
            // 		if($min_valor<$pri_valor){$min_canti=1;}
            $sql_carr = 'select *, ';
            $sql_carr .= 'sum(cant) as stcant, sum(total) as stotal, sum(tsubt) as stsubt ';
            $sql_carr .= 'from carr12 ';
            $sql_carr .= 'where idnum2="' . $idnum . '"';
            $sql_carr .= ' and item_descri not like "%TRANS%"';
            $sql_carr .= ' and item_descri not like "%ENVIO%"';
            $sql_carr .= ' and item_descri not like "%LOGIS%"';
            $res_carr = msql_query($sql_carr, $link_vcrx);
            $stsubt = msql_result($res_carr, 0, 'stsubt');
            $stotal = msql_result($res_carr, 0, 'stotal');
            $stcant = msql_result($res_carr, 0, 'stcant');

            //     if($stotal<$min_valor)
            if ($stotal < $pri_valor)
            {
                $msgalert = '<msgalert style="display:none">';
                $msgalert .= ' ***** ERROR : ';
                // 			$msgalert.='Orden de Pedido debe ser MINIMO : '.number_format($min_valor,2);
                $msgalert .= 'Orden de Pedido debe ser MINIMO : $' . number_format($pri_valor, 2);
                $msgalert .= ' ***** ';
                $msgalert .= '<msgalert>';

                echo '<result>';
                echo $msgalert;
                echo '</result>';
                return;
            }

            if ($stcant < $pri_cant)
            {
                $msgalert = '<msgalert style="display:none">';
                $msgalert .= ' ***** ERROR : ';
                // 			$msgalert.='Orden de Pedido debe ser MINIMO : '.number_format($min_valor,2);
                $msgalert .= 'Orden de Pedido debe ser MINIMO : ' . number_format($pri_cant, 0) . ' UNIDADES';
                $msgalert .= ' ***** ';
                $msgalert .= '<msgalert>';

                echo '<result>';
                echo $msgalert;
                echo '</result>';
                return;
            }

            // 		$sql_carr='select *, sum(cant) as scant from carr12 where idnum2="'.$idnum.'" group by item_raiz having scant<'.$min_canti.'';
            // 		$res_carr=msql_query($sql_carr,$link_vcrx);
            // 		if(msql_num_rows($res_carr)>0)
            // 		{
            // 			$msgalert='<msgalert style="display:none">';
            // 			$msgalert.=' ***** ERROR : ';
            // 			$msgalert.='Cantidad por ITEM debe ser MINIMO : '.number_format($min_canti,0);
            // 			$msgalert.=' ***** ';
            // 			$msgalert.='<msgalert>';
            // 			echo'<result>';
            // 			echo $msgalert;
            // 			echo'</result>';
            // 			return;
            // 		}
            
        }

        // 	$newdocu='OP19';
        $newdocu = 'PC19';
        $newnumero = nume_docu($newdocu);
        $newidnum = clon_docu('CAR1', $idnum, $newdocu);

        $sql_clie = 'update clie1 set numero="' . $newnumero . '" where idnum1="' . $newidnum . '"';
        $res_clie = msql_query($sql_clie, $link_vcrx);

        $sql_clie = 'update clie1 set fecha=now() where idnum1="' . $newidnum . '"';
        $res_clie = msql_query($sql_clie, $link_vcrx);

        if (mb_stristr('dly1', $empr))
        {
            //$enti2=r_fiel('carr1',$idnum,'enti2');
            if ($enti2 != '')
            {
                $sql_clie = 'update clie1 set drtr=enti where idnum1="' . $newidnum . '"';
                $res_clie = msql_query($sql_clie, $link_vcrx);
                $sql_clie = 'update clie1 set enti="' . $enti2 . '" where idnum1="' . $newidnum . '"';
                $res_clie = msql_query($sql_clie, $link_vcrx);
            }

        }

        if (mb_stristr('gmny.gnya', $empr))
        {
            if ($empr == 'gnya')
            {
                // 			$xdcto=0;
                // 			if($stsubt>10){$xdcto=25;}
                // 			if($stsubt>50){$xdcto=30;}
                // 			$sql_clie ='update clie2 set dcto='.$xdcto.' where idnum2="'.$newidnum.'" ';
                // 			$res_clie=msql_query($sql_clie,$link_vcrx);
                
            }

            $xiddet = r_iddet('clie', $newidnum);
            $sql_clie = 'insert clie2(idnum2,iddet) value("' . $newidnum . '","' . $xiddet . '")';
            $res_clie = msql_query($sql_clie, $link_vcrx);
            $sql_clie = 'update clie2 set item="GENE-TRAN400", cant=1, puni=4, dcto=0, iva=0, ice=0, irbp=0 ';
            $sql_clie .= ' where idnum2="' . $newidnum . '" and iddet="' . $xiddet . '"';
            $res_clie = msql_query($sql_clie, $link_vcrx);
            if ($empr == 'gnya')
            {
                // dic/2017
                $sql_clie = 'update clie2 set item="GENE-TRAN400", cant=1, puni=0, dcto=0, iva=0, ice=0, irbp=0 ';
                $sql_clie .= ' where idnum2="' . $newidnum . '" and iddet="' . $xiddet . '"';
                $res_clie = msql_query($sql_clie, $link_vcrx);
            }
        }

        if (msql_error($link_vcrx) == '')
        {

            $newclave = gen_claveacc($newdocu, $newidnum);
            mail_ce($newclave, $user_email);

            $msgalert = '<msgalert style="display:none">';
            $msgalert .= 'Se GENERO la ORDEN Numero :' . $newnumero;
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
        }

        del_carr($idnum);
    }

    function clie2vtas($idnum, $enti2 = '')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        // 	if(empty($docu)){return;}
        if (empty($idnum))
        {
            return;
        }

        $tabla = r_fiel('docu', $docu, 'tabla');
        $tabla = 'clie';
        $min_valor = 1;
        $min_canti = 1;

        $sql_cli2 = 'select * from ' . $tabla . '2 where idnum2="' . $idnum . '"';
        $res_cli2 = msql_query($sql_cli2, $link_vcrx);
        if (msql_num_rows($res_cli2) == 0)
        {
            $msgalert = '';
            $msgalert .= '<msgalert style="display:none">';
            $msgalert .= 'EL DOCUMENTO ESTA VACIO ';
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
            return;
        }

        $sql_clie = 'select * from ' . $tabla . '1 where idnum1="' . $idnum . '"';
        $res_clie = msql_query($sql_clie, $link_vcrx);
        $olddocu = msql_result($res_clie, 0, 'docu');
        $oldstat = msql_result($res_clie, 0, 'status');
        if (mb_stristr('FROX', $oldstat))
        {
            $msgalert = '';
            $msgalert .= '<msgalert style="display:none">';
            $msgalert .= 'NO SE PUEDE PROCESAR DOCUMENTO ' . r_fiel('stat', $oldstat);
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
            return;
        }

        if ($cfg_empr == 'gmny' and $tabla == 'clie')
        {
            $pri_valor = 300;

            //7/ene/18
            $pri_valor = 200;

            //26/feb/18
            $pri_valor = 50;

            //7/ago/18
            $pri_valor = 100;

            $min_valor = $pri_valor;
            $min_canti = 1;

            //valida ventas del ultimo mes
            $fecha1 = date('Y-m-d', strtotime('-1 month'));
            $fecha2 = $fechaa;

            //     $user_cedula='0704548353';
            //     $idnum=60;
            $sql_carr = 'select *, sum(case when docu like "NC%" then abs(total)*-1 else abs(total) end) as stotal from vtas12 ';
            $sql_carr .= ' where fecha between "' . $fecha1 . '" and "' . $fecha2 . '"';
            $sql_carr .= ' and enti like "' . $user_cedula . '%" ';
            $res_carr = msql_query($sql_carr, $link_vcrx);

            $min_valor = $min_valor - msql_result($res_carr, 0, 'stotal');

            if ($min_valor < 1)
            {
                $min_valor = 1;
            }
            if ($min_valor < $pri_valor)
            {
                $min_canti = 1;
            }

            $sql_carr = 'select *, sum(total) as stotal, sum(tsubt) as stsubt from carr12 where idnum2="' . $idnum . '"';
            $res_carr = msql_query($sql_carr, $link_vcrx);
            $stsubt = msql_result($res_carr, 0, 'stsubt');
            $stotal = msql_result($res_carr, 0, 'stotal');

            if ($stotal < $pri_valor)
            {
                $msgalert = '<msgalert style="display:none">';
                $msgalert .= ' ***** ERROR : ';
                $msgalert .= 'Orden de Pedido debe ser MINIMO : ' . number_format($pri_valor, 2);
                $msgalert .= ' ***** ';
                $msgalert .= '<msgalert>';

                echo '<result>';
                echo $msgalert;
                echo '</result>';
                return;
            }

            $sql_carr = 'select *, sum(cant) as scant from clie12 where idnum2="' . $idnum . '" group by item_raiz having scant<' . $min_canti . '';
            $res_carr = msql_query($sql_carr, $link_vcrx);
            if (msql_num_rows($res_carr) > 0)
            {
                $msgalert = '<msgalert style="display:none">';
                $msgalert .= ' ***** ERROR : ';
                $msgalert .= 'Cantidad por ITEM debe ser MINIMO : ' . number_format($min_canti, 0);
                $msgalert .= ' ***** ';
                $msgalert .= '<msgalert>';

                echo '<result>';
                echo $msgalert;
                echo '</result>';
                return;
            }

        }

        $newdocu = 'FC10';
        $newptov = r_fiel('user', $user_codigo, 'ptov');
        $newptoe = r_fiel('ptov', $newptov, 'ptoe');
        if ($newptoe == '')
        {
            $newptov = '001101';
            $newptoe = '001101';
        }

        if ($cfg_empr == 'gmny')
        {
            $newptoe = '003101';
        }

        $newnumero = nume_docu($newdocu, $newptoe);
        $newidnum = clon_docu($olddocu, $idnum, $newdocu);

        $sql_clie = 'update vtas1 set numero="' . $newnumero . '",';
        $sql_clie = ' ptov="' . $newptov . '",';
        $sql_clie = ' ptoe="' . $newptoe . '",';
        $sql_clie = ' fecha=now() ';
        $sql_clie = ' where idnum1="' . $newidnum . '"';
        $res_clie = msql_query($sql_clie, $link_vcrx);

        if (mb_stristr('dly1', $empr))
        {
            if ($enti2 != '')
            {
                $sql_clie = 'update vtas1 set drtr=enti where idnum1="' . $newidnum . '"';
                $res_clie = msql_query($sql_clie, $link_vcrx);
                $sql_clie = 'update vtas1 set enti="' . $enti2 . '" where idnum1="' . $newidnum . '"';
                $res_clie = msql_query($sql_clie, $link_vcrx);
            }

        }

        if (mb_stristr('gmny.gnya', $empr) and $tabla == 'clie')
        {
            $xiddet = r_iddet($tabla, $newidnum);
            $sql_clie = 'insert vtas2(idnum2,iddet) value("' . $newidnum . '","' . $xiddet . '")';
            $res_clie = msql_query($sql_clie, $link_vcrx);
            $sql_clie = 'update vtas2 set item="GENE-TRAN400", cant=1, puni=4, dcto=0, iva=0, ice=0, irbp=0 ';
            $sql_clie .= ' where idnum2="' . $newidnum . '" and iddet="' . $xiddet . '"';
            $res_clie = msql_query($sql_clie, $link_vcrx);
            if ($empr == 'gnya')
            {
                $sql_clie = 'update vtas2 set item="GENE-TRAN400", cant=1, puni=0, dcto=0, iva=0, ice=0, irbp=0 ';
                $sql_clie .= ' where idnum2="' . $newidnum . '" and iddet="' . $xiddet . '"';
                $res_clie = msql_query($sql_clie, $link_vcrx);
            }
        }

        if (msql_error($link_vcrx) == '')
        {

            $newclave = gen_claveacc($newdocu, $newidnum);
            mail_ce($newclave, $user_email);

            $msgalert = '<msgalert style="display:none">';
            $msgalert .= 'Se GENERO la FACTURA Numero :' . $newnumero;
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
        }

        $sql_carr = 'update ' . $tabla . '1 set status="F" where idnum1="' . $idnum . '"';
        $res_carr = msql_query($sql_carr, $link_vcrx);
        // 	del_carr($idnum);
        
    }

    function docu2guia($docu, $idnum)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if (empty($docu))
        {
            return;
        }
        if (empty($idnum))
        {
            return;
        }

        $tabla = r_fiel('docu', $docu, 'tabla');

        if (!mb_stristr('FC.EB', substr($docu, 0, 2)))
        {
            return;
        }

        $sql_orig = 'select * from guia1 where lower(mdfrom) like "' . $tabla . '" and idfrom="' . $idnum . '" and status!="O" and status!="X"';
        $res_orig = msql_query($sql_orig, $link_vcrx);

        $newdocu = 'GR10';
        if (msql_num_rows($res_orig) != 0)
        {
            $newidnum = msql_result($res_orig, 0, 'idnum1');
        }
        else
        {
            $newptoe = r_fiel($tabla . '1', $idnum, 'ptoe');
            $newnumero = nume_docu($newdocu, $newptoe);
            $newidnum = clon_docu($docu, $idnum, $newdocu);

            $sql_guia = 'update guia1 set numero="' . $newnumero . '" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set fecha=now() where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set ruta="GUAYAQUIL" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set fecha1=now() where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set fecha2=now() where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set punto1="' . r_fiel('enti', $cfg_ruc, 'matriz') . '" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set punto2="' . r_fiel('enti', $enti, 'matriz') . '" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set cedula1="' . $cfg_ruc . '" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set cedula2=enti where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set nombre1="' . r_fiel('enti', $cfg_ruc) . '" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set nombre2="' . r_fiel('enti', $enti) . '" where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set claveacce=null where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set autorfec=null where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

            $sql_guia = 'update guia1 set autornum=null where idnum1="' . $newidnum . '"';
            $res_guia = msql_query($sql_guia, $link_vcrx);

        }

        $newclave = gen_claveacc($newdocu, $newidnum);

        if (msql_error($link_vcrx) == '')
        {
            // 		$newclave=gen_claveacc($newdocu,$newidnum);
            // 		mail_ce($newclave,$user_email);
            $msgalert = '<msgalert style="display:none">';
            $msgalert .= 'Se GENERO la GUIA Numero :' . $newnumero;
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
        }
        return $newidnum;
        // 	del_carr($idnum);
        
    }

    function clie2vtas2($docu, $idnum, $newdocu = 'FC10')
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if (empty($docu))
        {
            return;
        }
        if (empty($idnum))
        {
            return;
        }

        $tabla = r_fiel('docu', $docu, 'tabla');
        $tablad = r_fiel('docu', $newdocu, 'tabla');

        if (!mb_stristr('PF.PC.FC', substr($docu, 0, 2)))
        {
            return;
        }
        if (!mb_stristr('PF.PC.FC', substr($newdocu, 0, 2)))
        {
            return;
        }

        $sql_orig = 'select * from ' . $tablad . '1 where lower(mdfrom) like "' . $tabla . '" and idfrom="' . $idnum . '" and status!="O" and status!="X"';
        $res_orig = msql_query($sql_orig, $link_vcrx);

        // 	$newdocu='GR10';
        if (msql_num_rows($res_orig) != 0)
        {
            $newidnum = msql_result($res_orig, 0, 'idnum1');
        }
        else
        {
            $newptoe = r_fiel($tabla . '1', $idnum, 'ptoe');
            if (substr($newdocu, 0, 2) == 'FC')
            {
                $sql_ptoe = 'select * from ' . $tablad . '1 where status!="O" and status!="X" and ptoe!="" and ptoe is not null order by idnum1 desc limit 1';
                $res_ptoe = msql_query($sql_ptoe, $link_vcrx);
                $newptoe = @msql_result($res_ptoe, 0, 'ptoe');
                if ($newptoe == '')
                {
                    $newptoe = '001101';
                }
            }
            $newnumero = nume_docu($newdocu, $newptoe);
            $newidnum = clon_docu($docu, $idnum, $newdocu);

            $sql_updt = 'update ' . $tablad . '1 set ';
            $sql_updt .= 'ptoe="' . $newptoe . '",';
            $sql_updt .= 'ptov="' . $newptov . '",';
            $sql_updt .= 'numero="' . $newnumero . '",';
            $sql_updt .= 'fecha=now(),';
            $sql_updt .= 'claveacce=null,';
            $sql_updt .= 'autornum=null,';
            $sql_updt .= 'autorfec=null,';
            $sql_updt .= 'status="-" ';
            $sql_updt .= 'where idnum1="' . $newidnum . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);
        }

        $newclave = gen_claveacc($newdocu, $newidnum);

        if (msql_error($link_vcrx) == '')
        {
            $msgalert = '<msgalert style="display:none">';
            $msgalert .= 'Se GENERO ' . $newdocu . ' Numero :' . $newnumero;
            $msgalert .= '<msgalert>';

            echo '<result>';
            echo $msgalert;
            echo '</result>';
        }
        return $newidnum;
    }

    function val_tpro($enti)
    {
        include ('../_cfg/config.php');
        $tpro = r_fiel('enti', $enti, 'tpro');
        if ($tpro == '')
        {
            $sql_tpro = 'select * from comp12 where enti like ' . substr($enti, 0, 10) . '% and cair is not null and cair!=""';
            //     $res_tpro=msql_query($sql_tpro,$link_vcrx);
            //     $cair=@msql_query($res_tpro,0,'cair');
            //     $tpro='BIEN'
            if ($tpro == '')
            {
                $tpro = 'BIEN';
            }
            $sql_tpro = 'update enti0 set enti_tpro="' . $tpro . '" where enti_codigo="' . $enti . '"';
            $res_tpro = msql_query($sql_tpro, $link_vcrx);
        }

        return $tpro;
    }

    function val_zsub($enti)
    {
        include ('../_cfg/config.php');
        $zsub = r_fiel('enti', $enti, 'zsub');
        if ($zsub == '')
        {
            //     $sql_tpro='select * from comp12 where enti like '.substr($enti,0,10).'% and cair is not null and cair!=""';
            //     if($tpro==''){$tpro='BIEN';}
            //     $sql_tpro='update enti0 set enti_tpro="'.$tpro.'" where enti_codigo="'.$enti.'"';
            //     $res_tpro=msql_query($sql_tpro,$link_vcrx);
            $zsub = 'GENE-GENE';
            $sql_updt = 'update enti0 set enti_zsub="' . $zsub . '" where enti_codigo="' . $enti . '"';
            $res_updt = msql_query($sql_updt, $link_vcrx);
        }

        return $zsub;
    }

    function val_bcos1($docu, $idnum)
    {
        include ('../_cfg/config.php');
        $tabla = '';
        if (substr($docu, 0, 2) == 'CH')
        {
            $tabla = 'bcos';
            $sql_ch10 = 'select * from ' . $tabla . '1 where idnum1=' . $idnum . '';
            $res_ch10 = msql_query($sql_ch10, $link_vcrx);
            $ctab = @msql_result($res_ch10, 0, 'ctab');

            if ($ctab == '')
            {
                $sql_ch10 = 'select * from ' . $tabla . '1 where docu="' . $docu . '" and ctab is not null and ctab!="" and ctab!="-" order by fecha desc limit 1';
                $res_ch10 = msql_query($sql_ch10, $link_vcrx);
                //       echo msql_error($link_vcrx);
                $ctab = msql_result($res_ch10, 0, 'ctab');

                //       if($ctab==''){$ctab='B001';}
                $sql_ch10 = 'update ' . $tabla . '1 set ctab="' . $ctab . '" where idnum1=' . $idnum . ' ';
                $res_ch10 = msql_query($sql_ch10, $link_vcrx);
            }
        }

    }

    function val_ncre($docu, $idnum)
    {
        include ('../_cfg/config.php');
        $tabla = '';
        // 	if(substr($docu,0,2)=='NC')
        //   {
        //     $tabla='vtas';
        // 	  $sql_ncre='update '.$tabla.'1 set todocu="FC10" where idnum1='.$idnum.' and todocu like "FP10%"';
        // 	  $res_ncre=msql_query($sql_ncre,$link_vcrx);
        //   }
        // 	if(substr($docu,0,2)=='NP')
        //   {
        //     $tabla='comp';
        // 	  $sql_ncre='update '.$tabla.'1 set todocu="FP10" where idnum1='.$idnum.' and todocu like "FC10%"';
        // 	  $res_ncre=msql_query($sql_ncre,$link_vcrx);
        //   }
        

        
    }

    function sal_enti($enti, $fecha1='', $fecha2='', $cxcp='C', $posf = 0)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        if ($cxcp == '')
        {$cxcp = 'C';}
         
        if ($cxcp == 'C')
        {
            $tabla = 'cxcob';
        }
        if ($cxcp == 'P')
        {
            $tabla = 'cxpag';
        }

        $fecha0 = fecha_modu(substr($tabla, 0, 4));

        if ($fecha1 == '')
        {
            $fecha1 = $fecha0;
        }
        if ($fecha2 == '')
        {
            $fecha2 = $fechaa;
        }

        $sql_ctas = 'select ' . $tabla . '12.*,';
        $sql_ctas .= 'sum(total) as stotal, ';
        $sql_ctas .= 'sum(case when fecha<"' . $fecha1 . '" then total end) as saldoi, ';
        $sql_ctas .= 'sum(case when fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '" then tdebito end) as tdeb, ';
        $sql_ctas .= 'sum(case when fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '" then tcredito end) as tcre, ';

        $sql_ctas .= 'sum(case when docu like "AC%" then total end) as anticipo, ';
         
        $sql_ctas .= 'sum(case when (fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '")';
        if ($posf == 1)
        {
            if ($cxcp == 'C')
            {
                $sql_ctas .= ' or(docu like "ICH%" and fecha>"' . $fecha2 . '") ';
            }
            if ($cxcp == 'P')
            {
                $sql_ctas .= ' or(docu like "CH%" and fecha>"' . $fecha2 . '") ';
            }
        }
        $sql_ctas .= ' then tdebito end) as tdebpf, ';

         
        $sql_ctas .= 'sum(total) as saldo ';
        $sql_ctas .= 'from ' . $tabla . '12 ';
        $sql_ctas .= 'where status!="O"';
        $sql_ctas .= ' and fecha>="' . $fecha0 . '"';
        //   $sql_ctas.=' and fecha>="'.$fecha1.'"';
        $sql_ctas .= ' and fecha<="' . $fecha2 . '"';
        $sql_ctas .= ' and substring(enti,1,10) like "' . substr($enti, 0, 10) . '%"';
        $sql_ctas .= ' and docum!=""';
        if ($cxcp == 'C')
        {
            $sql_ctas .= ' and left(docum,2) in (' . $docxcob . ')';
        }
        if ($cxcp == 'P')
        {
            $sql_ctas .= ' and left(docum,2) in (' . $docxpag . ')';
        }
        $sql_ctas .= ' and (numer*1)>0';

        if ($posf == 1)
        {
            if ($cxcp == 'C')
            {
                $sql_ctas .= ' or(';
                $sql_ctas .= ' docu like "ICH%%"';
                $sql_ctas .= ' and substring(enti,1,10) like "' . substr($enti, 0, 10) . '%"';
                $sql_ctas .= ' )';
            }
            if ($cxcp == 'P')
            {
                $sql_ctas .= ' or(';
                $sql_ctas .= ' docu like "CH%%"';
                $sql_ctas .= ' and substring(enti,1,10) like "' . substr($enti, 0, 10) . '%"';
                $sql_ctas .= ' )';
            }

        }

        $res_ctas = msql_query($sql_ctas, $link_vcrx);

//           echo '<br>'.$sql_ctas;
        $saldo = array();
        $saldo[0] = msql_result($res_ctas, 0, 'enti_descri');
        $saldo[1] = msql_result($res_ctas, 0, 'saldoi');
        $saldo[2] = msql_result($res_ctas, 0, 'tdeb');
        $saldo[3] = msql_result($res_ctas, 0, 'tcre');
        $saldo[4] = msql_result($res_ctas, 0, 'saldo');
        $saldo[5] = msql_result($res_ctas, 0, 'anticipo');

        //   echo $sql_ctas;
        return $saldo;
    }

    function sal_docum($docu, $idnum, $fecha1, $fecha2)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');

        $tabla = r_fiel('docu', $docu, 'tabla');
        $sql_docu = 'select *, sum(total) as stotal from ' . $tabla . '12 where idnum1=' . $idnum;
        $res_docu = msql_query($sql_docu, $link_vcrx);

        $enti = @msql_result($res_docu, 0, 'enti');
        $ptoe = @msql_result($res_docu, 0, 'ptoe');
        $numero = @msql_result($res_docu, 0, 'numero');
        $total = @msql_result($res_docu, 0, 'stotal');
        $enti = substr($enti, 0, 10);

        $tabla = 'cxco';
        if (mb_stristr('FC.AC.NV.XC', substr($docu, 0, 2)))
        {
            $tabla = 'cxcob';
        }
        if (mb_stristr('FP.AP.XP', substr($docu, 0, 2)))
        {
            $tabla = 'cxpag';
        }

        $fecha0 = fecha_modu(substr($tabla, 0, 4));

        if ($fecha1 == '')
        {
            $fecha1 = $fecha0;
        }
        if ($fecha2 == '')
        {
            $fecha2 = $fechaa;
        }

        $sql_ctas = 'select ' . $tabla . '12.*,';
        $sql_ctas .= 'sum(total) as stotal, ';
        $sql_ctas .= 'sum(case when fecha<"' . $fecha1 . '" then total end) as saldoi, ';
        $sql_ctas .= 'sum(case when fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '" then tdebito end) as tdeb, ';
        $sql_ctas .= 'sum(case when fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '" then tcredito end) as tcre, ';
        $sql_ctas .= 'sum(total) as saldo ';
        $sql_ctas .= 'from ' . $tabla . '12 ';
        $sql_ctas .= 'where status!="O"';
        $sql_ctas .= ' and fecha>="' . $fecha0 . '"';
        $sql_ctas .= ' and fecha<="' . $fecha2 . '"';
        $sql_ctas .= ' and substring(enti,1,10) like "' . substr($enti, 0, 10) . '%"';
        $sql_ctas .= ' and docum= "' . $docu . '"';
        $sql_ctas .= ' and numer= "' . $numero . '"';
        $res_ctas = msql_query($sql_ctas, $link_vcrx);

        //   echo $sql_ctas;
        $saldo = array();
        $saldo[0] = msql_result($res_ctas, 0, 'enti_descri');
        $saldo[1] = msql_result($res_ctas, 0, 'saldoi');
        $saldo[2] = msql_result($res_ctas, 0, 'tdeb');
        $saldo[3] = msql_result($res_ctas, 0, 'tcre');
        $saldo[4] = msql_result($res_ctas, 0, 'saldo');

        return $saldo;
    }

    function sal_docu($docu, $idnum, $pabon = '', $pfecha = '')
    {

        if (!mb_stristr('FC.FP.NV.AP.AC.XC.XP.PR', substr($docu, 0, 2)))
        {
            return 0;
        }

        include ('../_cfg/config.php');
        include ('php_session.php');

        if (empty($pabon))
        {
            $pabon = 0;
        }
        if (empty($pfecha))
        {
            $pfecha = '2099-12-31';
        }
        //   echo '*/*/*'.$docu;
        $tabla = r_fiel('docu', $docu, 'tabla') . '';
        $sql_docu = 'select *, sum(total) as stotal from ' . $tabla . '12 where idnum1=' . $idnum;
        $res_docu = msql_query($sql_docu, $link_vcrx);

        $enti = @msql_result($res_docu, 0, 'enti');
        $ptoe = @msql_result($res_docu, 0, 'ptoe');
        $numero = @msql_result($res_docu, 0, 'numero');
        $total = @msql_result($res_docu, 0, 'stotal');
        $enti = substr($enti, 0, 10);
        $recar = 0;
        $abono = 0;
        $abono1 = 0;
        $abono2 = 0;
        $abono3 = 0;
        $abono4 = 0;
        $abono5 = 0;

        $sql_deta = '';
        $sql_deta .= 'select ';
        $sql_deta .= 'sum(abs(cant)) as abono, ';
//         $sql_deta .= 'sum(abs(cant*puni)) as abono2 ';
        $sql_deta .= 'sum(case when left(docu,2) in ("XC","XP") then abs(cant*puni)*-1 else abs(cant*puni) end) as abono2 ';
        $sql_deta .= 'from deta1,deta2 ';
        $sql_deta .= ' where ';
        $sql_deta .= ' idnum1=idnum2 ';
        $sql_deta .= ' and enti like "' . substr($enti,0,10) . '%"';
        $sql_deta .= ' and docu not like "AC10%"';
        $sql_deta .= ' and docu not like "AP10%"';
        $sql_deta .= ' and docu not like "PR%"';
        $sql_deta .= ' and docu not like "EC%"';
        $sql_deta .= ' and docu not like "F%"';
        // 	$sql_deta.=' and docu not like "X%"';
        $sql_deta .= ' and docum="' . $docu . '"';
        $sql_deta .= ' and ptoem="' . $ptoe . '"';
        $sql_deta .= ' and numer="' . $numero . '"';
        $sql_deta .= ' and fecha<="' . $pfecha . '"';
        $sql_deta .= ' and status!="O"';
        $sql_deta .= ' and status!="X"';

        $sql_nota = '';
        $sql_nota .= 'select sum(total) as abono from nota12';
        $sql_nota .= ' where ';
        $sql_nota .= ' idnum1=idnum2 ';
        $sql_nota .= ' and enti like "' . substr($enti,0,10) . '%"';
        $sql_nota .= ' and docu not like "PR%"';
        $sql_nota .= ' and docu not like "EC%"';
        $sql_nota .= ' and docu not like "F%"';
        $sql_nota .= ' and todocu="' . $docu . '"';
        $sql_nota .= ' and toptoe="' . $ptoe . '"';
        $sql_nota .= ' and tonume="' . $numero . '"';
        $sql_nota .= ' and fecha<="' . $pfecha . '"';
        $sql_nota .= ' and status!="O"';
        $sql_nota .= ' and status!="X"';

        $sql_abon = str_replace('deta', 'caja', $sql_deta);
        if ($pabon == 0 or $pabon == 1)
        {
            $res_abon = msql_query($sql_abon, $link_vcrx);
        }
        $abono1 = abs(@msql_result($res_abon, 0, 'abono'));

        $sql_abon = str_replace('deta', 'bcos', $sql_deta);
        if ($pabon == 0 or $pabon == 2)
        {
            $res_abon = msql_query($sql_abon, $link_vcrx);
        }
        $abono2 = abs(@msql_result($res_abon, 0, 'abono'));

        if (substr($docu, 0, 2) == 'FC')
        {
            $sql_abon = str_replace('deta', 'retc', $sql_deta);
            $sql_abon = str_replace('abs(cant)', 'abs(cant*puni/100)', $sql_abon);
            if ($pabon == 0 or $pabon == 3)
            {
                $res_abon = msql_query($sql_abon, $link_vcrx);
            }
            $abono3 = abs(@msql_result($res_abon, 0, 'abono'));

            $sql_abon = str_replace('nota', 'vtas', $sql_nota);
            if ($pabon == 0 or $pabon == 3)
            {
                $res_abon = msql_query($sql_abon, $link_vcrx);
            }
            $abono4 = abs(@msql_result($res_abon, 0, 'abono'));

            $sql_abon = str_replace('deta', 'dxco', $sql_deta);
            if ($pabon == 0 or $pabon == 3)
            {
                $res_abon = msql_query($sql_abon, $link_vcrx);
            }
            $abono5 = (@msql_result($res_abon, 0, 'abono2'));
//                       echo '<br>'.$sql_abon;
             
        }

        if (substr($docu, 0, 2) == 'FP')
        {
            $sql_abon = str_replace('deta', 'retp', $sql_deta);
            $sql_abon = str_replace('abs(cant)', 'abs(cant*puni/100)', $sql_abon);
            if ($pabon == 0 or $pabon == 3)
            {
                $res_abon = msql_query($sql_abon, $link_vcrx);
            }
            $abono3 = abs(@msql_result($res_abon, 0, 'abono'));

            $sql_abon = str_replace('nota', 'comp', $sql_nota);
            if ($pabon == 0 or $pabon == 3)
            {
                $res_abon = msql_query($sql_abon, $link_vcrx);
            }
            $abono4 = abs(@msql_result($res_abon, 0, 'abono'));

            $sql_abon = str_replace('deta', 'dxpa', $sql_deta);
            if ($pabon == 0 or $pabon == 3)
            {
                $res_abon = msql_query($sql_abon, $link_vcrx);
            }
            $abono5 = (@msql_result($res_abon, 0, 'abono2'));
//                       echo '<br>*/*/*'.$sql_abon;
            
        }
// echo '*/*/*'.$abono5;
        //      $saldo=($total-$abono1-$abono2-$abono3-$abono4)*(1.000000);
        $saldo = ($total - $abono1 - $abono2 - $abono3 - $abono4 - $abono5) * (1.000000);
        if ($pabon == 3)
        {
            $saldo = abs($abono3);
        }
        if ($pabon == 4)
        {
            $saldo = abs($abono4);
        }
        return $saldo;
    }

    function sal_ctas($ctas, $fecha1 = '', $fecha2 = '', $dtr1 = 1)
    {
        include ('../_cfg/config.php');
        include ('php_session.php');
        $fecha0 = fecha_modu('cont');

        if ($fecha1 == '')
        {
            $fecha1 = $fecha0;
        }
        if ($fecha2 == '')
        {
            $fecha2 = $fechaa;
        }

        //   echo $fecha2;
        $tabla = 'cont';
        $sql_ctas = 'select ' . $tabla . '12.*,';
        $sql_ctas .= 'sum(total) as stotal, ';
        $sql_ctas .= 'sum(case when fecha<"' . $fecha1 . '" then tcant end) as saldoi, ';
        $sql_ctas .= 'sum(case when fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '" then tdebito end) as tdeb, ';
        $sql_ctas .= 'sum(case when fecha>="' . $fecha1 . '" and fecha<="' . $fecha2 . '" then tcredito end) as tcre, ';
        $sql_ctas .= 'sum(tcant) as saldo ';
        $sql_ctas .= 'from ' . $tabla . '12 ';
        $sql_ctas .= 'where status!="O"';
        $sql_ctas .= ' and fecha>="' . $fecha0 . '"';
        $sql_ctas .= ' and fecha<="' . $fecha2 . '"';
        $sql_ctas .= ' and ctas like "' . $ctas . '"';
        //   if($dtr1==0)
        //   {$sql_ctas.='and docu not like "DTR%"';}
        //     explain_sql($sql_ctas);
        $res_ctas = msql_query($sql_ctas, $link_vcrx);

        $saldo = array();
        $saldo[0] = msql_result($res_ctas, 0, 'ctas_descri');
        $saldo[1] = msql_result($res_ctas, 0, 'saldoi');
        $saldo[2] = msql_result($res_ctas, 0, 'tdeb');
        $saldo[3] = msql_result($res_ctas, 0, 'tcre');
        $saldo[4] = msql_result($res_ctas, 0, 'saldo');

        //   $saldo=msql_result($res_ctas,0,'saldoi');
        return $saldo;
    }

}

?>
