<?php
include('fnc_msql.php');

function ctas_deta($pctas)
{
     $pctas=trim($pctas);
     $lctas=strlen($pctas);
     if($lctas<5){return false;}

     $link_data=msql_connect('','','',$cfg_empr);
//      $link_data=msql_connect();
     $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_data);
     if(msql_num_rows($res_ctas)==1)
     {
          $sql_ctas='select * from ctas0 where ctas_codigo<"'.$pctas.'" and length(trim(ctas_codigo))<'.$lctas.' and  ctas_status!="X" order by ctas_codigo desc';
          $res_ctas=msql_query($sql_ctas,$link_data);
          $cta_sup='';
          $cta_sup.=trim(msql_result($res_ctas,0,'ctas_codigo'));
          $cta_sup.='->';
          $cta_sup.=trim(msql_result($res_ctas,0,'ctas_descri'));
          return $cta_sup;
     }
     return ;
}


function esMovil()
{
	if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$_SERVER['HTTP_USER_AGENT'])||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($_SERVER['HTTP_USER_AGENT'],0,4)))
     {return true;}else{return false;}
}


function getBrowser()
{
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
     if(strpos($user_agent, 'MSIE') !== FALSE)return 'Internet explorer';
     elseif(strpos($user_agent, 'Edg') !== FALSE)return 'Microsoft Edge';
     elseif(strpos($user_agent, 'Trident') !== FALSE)return 'Internet explorer';
     elseif(strpos($user_agent, 'Opera Mini') !== FALSE)return "Opera Mini";
     elseif(strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR') !== FALSE)return "Opera";
     elseif(strpos($user_agent, 'Firefox') !== FALSE)return 'Mozilla Firefox';
     elseif(strpos($user_agent, 'Chrome') !== FALSE)return 'Google Chrome';
     elseif(strpos($user_agent, 'Safari') !== FALSE)return "Safari";
     else return 'No hemos podido detectar su navegador';
}

function getPlatform()
{
     $user_agent = $_SERVER['HTTP_USER_AGENT'];
     $plataformas = array(
      'Windows 10' => 'Windows NT 10.0+',
      'Windows 8.1' => 'Windows NT 6.3+',
      'Windows 8' => 'Windows NT 6.2+',
      'Windows 7' => 'Windows NT 6.1+',
      'Windows Vista' => 'Windows NT 6.0+',
      'Windows XP' => 'Windows NT 5.1+',
      'Windows 2003' => 'Windows NT 5.2+',
      'Windows' => 'Windows otros',
      'iPhone' => 'iPhone',
      'iPad' => 'iPad',
      'Mac OS X' => '(Mac OS X+)|(CFNetwork+)',
      'Mac otros' => 'Macintosh',
      'Android' => 'Android',
      'BlackBerry' => 'BlackBerry',
      'Linux' => 'Linux',
       );
     
        foreach($plataformas as $plataforma=>$pattern)
        {if (preg_match('/(?i)'.$pattern.'/', $user_agent))return $plataforma;}
        return 'Otras';
}

function trunc_real($val,$dec=2)
{
     while(substr($val,-2)=='00')
     {
          if(substr($val,-$dec-1,1)=='.'){break;}
          $val=substr($val,0,-1);
     }
     return $val;
}

function reso2file($reso,$name='')
{
     if(gettype($reso)!='resource' and gettype($reso)!='object'){return;}
     
     $type='xml';
     if(mb_stristr($name,'xml')){$type='xml';}
     if(mb_stristr($name,'html')){$type='html';}
     if(mb_stristr($name,'json')){$type='json';}
     if($name==$type or $name=='.'.$type){$name='';}
     
     if(empty($name)){$name=$type.'_'.date('Yms_His');}
	$file_name=$name.'.'.$type;
     
	$dom = new DOMDocument();
		$dom->encoding = 'utf-8';
		$dom->xmlVersion = '1.0';
		$dom->formatOutput = true;

          $xcont=0;
          $thead=array();
          $tfoot=array();
          $field_name=array();
          $field_type=array();
          $field_leng=array();
          $table='grid';
          $trow='row';
          $tcol='col';
          if($type=='html')
          {
               $table='table';
               $trow='tr';
               $tcol='td';
          }
     
          $root=$dom->appendChild($dom->createElement($name));
               $root->setAttribute('date',date('Y-m-d'));
               $root->setAttribute('time',date('H:i:s'));
     
     
          $style='';
          $style.='tr[name]:hover{background-color:lightblue !important;}; ';
//           $style.='td.align-r{text-align:right;}; ';
     
//           $style.='td[class].align-r{text-align:right;background-color:green;};';

//           $style.='td[td_date]{white-space:nowrap;text-align:center;}; ';
//           $style.='.td_date{white-space:nowrap;text-align:center;}; ';
          $root->appendChild($dom->createElement('style',$style));
     
          $grid=$root->appendChild($dom->createElement($table));
               $grid->setAttribute('name',$name);
//                $grid->setAttribute('class','fix_table');
     
          if($type=='html')
          {
               $grid->setAttribute('id',$name);
               $grid->setAttribute('width','99%');
               $grid->setAttribute('cellspacing','0');
               $grid->setAttribute('cellpadding','3');
//                $grid->setAttribute('border','1');
               $style='';
               $style.='border-collapse:collapse;';
               $style.='background-color:snow;';
               $style.='font-family:arial;';
               $grid->setAttribute('style',$style);
          }
     
          if($type=='xml')
          {
               $footg=$grid->appendChild($dom->createElement('tfoot'));
               $rowg=$grid->appendChild($dom->createElement('tbody'));
          }

          if($type=='html')
          {
               $caption='';
               $grid->appendChild($dom->createElement('caption',$caption));
               $colg=$grid->appendChild($dom->createElement('colgroup'));
               $headg=$grid->appendChild($dom->createElement('thead'));
               $footg=$grid->appendChild($dom->createElement('tfoot'));
               $rowg=$grid->appendChild($dom->createElement('tbody'));
                    $style='';
                    $style.='background-color:silver;';
                    $style.='border-top:2px solid;border-bottom:2px solid;';
                    $headg->setAttribute('style',$style);
                    $footg->setAttribute('style',$style);
                    $rowg->setAttribute('valign','top');
                    $rowg->setAttribute('style','overflow-y:auto;');
          }

     
          // validar totales
          for($xcol=0; $xcol<msql_num_fields($reso); $xcol++)
          {
               $field_name[$xcol]=msql_field_name($reso,$xcol);
               $field_type[$xcol]=msql_field_type($reso,$xcol);
               if(mb_stristr($field_name[$xcol],'__')){$field_name[$xcol]=str_replace('__','-',$field_name[$xcol]);}
               for($xrow=0; $xrow<msql_num_rows($reso); $xrow++)
               {
                    $value=msql_result($reso,$xrow,$xcol);
                    $value_leng=strlen($value);
//                     echo ' ==>'.$field_name[$xcol].'='.$value_leng;
                    if($value_leng>$field_leng[$xcol]){$field_leng[$xcol]=$value_leng;}
                    if(mb_stristr('int.real',$field_type[$xcol])){$value=$value*1;}
                    if(mb_stristr('int.real',$field_type[$xcol]) and $type=='xml'){$value=1;}
                    if(!empty($value)){$thead[$xcol]='1';break;}
               }
          }

          // llena detalle
          msql_data_seek($reso,0);
          for($xrow=0; $xrow<msql_num_rows($reso); $xrow++)
          {
               $asoc=msql_fetch_assoc($reso);
               $item_duni=$asoc['item_duni'];
               $item_dval=$asoc['item_dval'];
               $item_dpre=$asoc['item_dpre'];
               $item_dcos=$asoc['item_dcos'];
               $status=$asoc['status'];
               if($item_dval<2){$item_dval=2;}
               if($item_dpre<2){$item_dpre=2;}
               if($item_dcos<2){$item_dcos=2;}

//                     echo ' ==>'.$xrow.':'.$status.$item_dval;
               $style=''; 
               $class='';
               if(($xrow+1)%5==0){$style.='border-bottom:dotted 1px;'; } 
//                if(($xrow+1)%2==0){$style.='background-color:#f8f8f8;'; } 
//                if(($xrow+1)%2==0){$style.='background-color:gainsboro;'; } 
               if($xrow+1==msql_num_rows($reso)){$style.='border-bottom:solid 2px;'; } 
//                if($status=='O'){$style.='text-decoration:line-through;';}
//                if($status=='O'){$class.='linethrough ';}
               
               $row=$rowg->appendChild($dom->createElement($trow));
               if($type=='html')
               {
                    $row->setAttribute('name','');
                    if($status=='O'){$row->setAttribute('linethr','');}
                    if(!empty($style)){$row->setAttribute('style',$style);}
                    if(!empty($class)){$row->setAttribute('class',$class);}
                    
                    
                    // COLUMNA #linea
                    $col=$row->appendChild($dom->createElement($tcol,str_pad($xrow+1,strlen(msql_num_rows($reso)),'0',STR_PAD_LEFT)));
                    $style='';
                    $class='';
//                     $class.='align-c size80 ';
//                     $class.='size80 ';
//                     $style.='font-size:80%;';
//                     $col->setAttribute('class','align-c');
                    $col->setAttribute('align-c','');
                    $col->setAttribute('size80','');
                    if(!empty($class)){$col->setAttribute('class',$class);}
                    if(!empty($style)){$col->setAttribute('style',$style);}
               }
               
               
               for($xcol=0; $xcol<msql_num_fields($reso); $xcol++)
               {
                    $value=msql_result($reso,$xrow,$xcol);
                    if($type=='xml'){$tcol=$field_name[$xcol];}
                    if($field_type[$xcol]=='int'){$tfoot[$xcol]++;}
                    if($field_type[$xcol]=='real'){$tfoot[$xcol]+=$value;}

                    if($type=='xml' and !empty($thead[$xcol]))
                    {$col=$row->appendChild($dom->createElement($tcol,htmlspecialchars($value)));}

                    if($type=='html' and !empty($thead[$xcol]))
                    {
                         if(mb_stristr('puni.p_unit.p-unit.unit.punit.pvp',$field_name[$xcol]))
                         {$value=number_format(trunc_real($value,$item_dval),$item_dpre);}
                         
                         if(mb_stristr('cost',$field_name[$xcol]))
                         {$value=number_format(trunc_real($value,$item_dval),$item_dcos);}
                         
                         if(mb_stristr('cant.ingreso.egreso.saldound',$field_name[$xcol]))
                         {$value=number_format($value,$item_duni);}
                         
                         if(mb_stristr('puni.p-unit.unit.subt.subtiva0.subtiva.subtice.pvp.cost',$field_name[$xcol]))
                         {$value=number_format($value,$item_dval);}
                         
                         if(mb_stristr('debito.credito',$field_name[$xcol]))
                         {$value=number_format($value,2);}
                         
                         if(mb_stristr('total.saldo',$field_name[$xcol]))
                         {$value=number_format($value,2);}


                         $crea_value=true;
                         if(mb_stristr('numero',$field_name[$xcol]))
                         {
                              $ptoe=$asoc['ptoe'];
                              $col=$row->appendChild($dom->createElement($tcol));       
                              $div=$col->appendChild($dom->createElement('div',htmlspecialchars($ptoe.$value)));                           
//                                    $div->setAttribute('class','hide');
                                   $div->setAttribute('hide','');
                              
                              $href='';
                              $href='?prnt=1&docu='.$asoc['docu'].'&idnum='.$asoc['idnum1'].'&formato=';
                              $ref=$col->appendChild($dom->createElement('a',htmlspecialchars($value)));                           
                                   $ref->setAttribute('href',$href);
                                   $ref->setAttribute('target','_blank');
                              
                              $crea_value=false;
                         }

                         if($crea_value)
                         {$col=$row->appendChild($dom->createElement($tcol,htmlspecialchars($value)));}
//                          $col->setAttribute('id',rand());
//                          $col->setAttribute('name',$field_name[$xcol]);
                         $class='';
                         $style='';
//                          if(mb_stristr('puni.p-unit.punit.unit.pvp.cost',$field_name[$xcol])){$class.='border-l border-r ';}
//                          if(mb_stristr('idnum1.idnum2.idn.iddet.idd',$field_name[$xcol])){$class.='size80 ';}
//                          if(mb_stristr('tiva.tice.tirbp',$field_name[$xcol])){$class.='italic size80 ';}
//                          if(mb_stristr('ptoe.ptov.bode.caja.ctab',$field_name[$xcol])){$class.='size80 ';}
//                          if(mb_stristr('tdcto',$field_name[$xcol])){$class.='underline ';}
                         if(mb_stristr('idnum1.idnum2.idn.iddet.idd',$field_name[$xcol])){$col->setAttribute('size80','');}
                         if(mb_stristr('tiva.tice.tirbp',$field_name[$xcol])){$col->setAttribute('size80','');}
                         if(mb_stristr('tiva.tice.tirbp',$field_name[$xcol])){$col->setAttribute('italic','');}
                         if(mb_stristr('ptoe.ptov.bode.caja.ctab',$field_name[$xcol])){$col->setAttribute('size80','');}
                         if(mb_stristr('tdcto',$field_name[$xcol])){$col->setAttribute('underline','');}
//                          if(mb_stristr('total.saldo',$field_name[$xcol])){$class.='td_total ';}
//                          if($field_type[$xcol]=='date'){$class.='td_date ';}
//                          if($field_type[$xcol]=='datetime'){$class.='td_date ';}
//                          if($field_type[$xcol]=='int' and $field_leng[$xcol]<=2){$class.='align-c ';}
//                          if($field_type[$xcol]=='int' and $field_leng[$xcol]>2){$class.='align-r ';}
//                          if($field_type[$xcol]=='real'){$class.='align-r ';}
//                          if($field_type[$xcol]=='date' and $xrow==0){$class.='td_date ';}
                         
//                          if(mb_stristr('docu.numero.status.st',$field_name[$xcol])){$style.='text-align:center;';}
//                          if(mb_stristr('numero.status.st',$field_name[$xcol]) 
//                               or mb_stristr($field_name[$xcol],'XYZ'))
//                               {$class.='align-c ';}
                         if(mb_stristr('ptoe.numero.status.st',$field_name[$xcol])){$col->setAttribute('align-c','');}
//                          if($field_type[$xcol]=='string' and $field_leng[$xcol]<=4){$class.='align-c ';}
                         if($field_type[$xcol]=='string' and $field_leng[$xcol]<=4){$col->setAttribute('align-c','');}
                         if($field_type[$xcol]=='int' and $field_leng[$xcol]<=2){$col->setAttribute('align-c','');}
                         if($field_type[$xcol]=='int' and $field_leng[$xcol]>2){$col->setAttribute('align-r','');}
                         if($field_type[$xcol]=='real'){$col->setAttribute('align-r','');}
                         if($field_type[$xcol]=='date'){$col->setAttribute('td_date','');}
                         if($field_type[$xcol]=='datetime'){$col->setAttribute('td_date','');}
                         if(mb_stristr('total.saldo',$field_name[$xcol])){$col->setAttribute('td_total','');}
                         if(!empty($class)){$col->setAttribute('class',$class);}
                         if(!empty($style)){$col->setAttribute('style',$style);}
                    }
               }
          }

          if($type=='xml')
          {
               $rowf=$footg->appendChild($dom->createElement($trow));
               for($xcol=0; $xcol<msql_num_fields($reso); $xcol++)
               {
                    if(!empty($thead[$xcol]))
                    {$col=$rowf->appendChild($dom->createElement($field_name[$xcol],$tfoot[$xcol]));}
               }
          }

     
     
          // col head foot
          $xsort=0;
          if($type=='html')
          {
               $rowh=$headg->appendChild($dom->createElement($trow));
               $rowf=$footg->appendChild($dom->createElement($trow));
               
               $ccolg=$colg->appendChild($dom->createElement('col',''));
               $crowh=$rowh->appendChild($dom->createElement('th','L'));
               $crowf=$rowf->appendChild($dom->createElement('th'));

               $class='size80 ';
               $onclick='sortTable(this,'.$xsort++.'';
               if($field_type[$xcol]=='real'){$onclick.=',"N"';}
               $onclick.=');';
//                if(!empty($onclick))
               {$crowh->setAttribute('onclick',$onclick);}
               {$crowh->setAttribute('class',$class);}
               
               
               for($xcol=0; $xcol<msql_num_fields($reso); $xcol++)
               {
                    if(!empty($thead[$xcol]))
                    {
//                          echo ' ==>'.$field_name[$xcol].'-'.$field_type[$xcol];
                         // group col
                         $style='';
                         $class='';
//                               if(empty($thead[$xcol])){$class.='hide';}
//                               if(mb_stristr($field_name[$xcol],'total')){$style.='background-color:gainsboro;';}
//                               if(mb_stristr($field_name[$xcol],'saldo')){$style.='background-color:gainsboro;';}
                              if(mb_stristr('enti.item.ctas',$field_name[$xcol])){$style.='background-color:gainsboro;';}
//                               if(mb_stristr('total.saldo',$field_name[$xcol])){$style.='font-weight:bold; ';}
//                               if(mb_stristr('puni.p-unit.unit.punit.pvp.cost',$field_name[$xcol])){$class.='border-l border-r ';}
//                               if(mb_stristr('total.saldo',$field_name[$xcol])){$class.='td_total ';}
                         
//                               if($field_type[$xcol]=='date'){$class.='td_date ';}
//                               if($field_type[$xcol]=='real'){$class.='align-r ';}

                         $col=$colg->appendChild($dom->createElement('col',''));
                              $col->setAttribute('type',$field_type[$xcol]);
                              if(empty($thead[$xcol])){$col->setAttribute('hide','');}                         
                              if($field_type[$xcol]=='date'){$col->setAttribute('td_date','');}
                              if($field_type[$xcol]=='real'){$col->setAttribute('align-r','');}
                              if(mb_stristr('total.saldo',$field_name[$xcol])){$col->setAttribute('td_total','');}
                              if(mb_stristr('puni.p-unit.unit.punit.pvp.cost',$field_name[$xcol])){$col->setAttribute('border-l','');}
                              if(mb_stristr('puni.p-unit.unit.punit.pvp.cost',$field_name[$xcol])){$col->setAttribute('border-r','');}
                              if(!empty($class)){$col->setAttribute('class',$class);}
                              if(!empty($style)){$col->setAttribute('style',$style);}

//                               if(gettype($tfoot[$xcol])=='double')
//                               {$col->setAttribute('align','char');$col->setAttribute('char','.');}

                         
                         
                         $style='';
                         $class='';
                         $onclick='';
                         
                              if(mb_stristr('idnum1.idnum2.idn.iddet.idd',$field_name[$xcol])){$class.='size80 ';}
                              if(mb_stristr('tiva.tice.tirbp',$field_name[$xcol])){$class.='italic size80 ';}
                              if(mb_stristr('tdcto',$field_name[$xcol])){$class.='underline ';}
                              if($field_type[$xcol]=='date'){$class.='date';}
//                               if($field_type[$xcol]=='date'){$style.='white-space:nowrap';}
//                               if($field_type[$xcol]=='real'){$style.='text-align:right;';}
                                   $onclick.='sortTable(this,'.$xsort++.'';
                                   if($field_type[$xcol]=='real'){$onclick.=',"N"';}
                                   $onclick.=');';
                         
                         // group head
                         $val_fieldname=$field_name[$xcol];
                         $val_fieldname=strtoupper($val_fieldname);
                         $val_fieldname=str_replace('_','-',$val_fieldname);
                         $col=$rowh->appendChild($dom->createElement('th',$val_fieldname));
//                               $col->setAttribute('id',rand());
                              $col->setAttribute('name',$field_name[$xcol]);
                              if(!empty($onclick)){$col->setAttribute('onclick',$onclick);}
                              if(!empty($class)){$col->setAttribute('class',$class);}
                              if(!empty($style)){$col->setAttribute('style',$style);}
//                               if(!empty($style)){$col->setAttribute('style',$style);}
                         
//                          if(mb_stristr('docu.numero',$field_name[$xcol])){$style.='text-align:center;';}
                         $tfoot_val=$tfoot[$xcol];
                         if($field_type[$xcol]=='real'){$tfoot_val=number_format($tfoot_val,2);}
                         $col=$rowf->appendChild($dom->createElement('th',$tfoot_val));
                              $col->setAttribute('name',$field_name[$xcol]);
                              if(!empty($class)){$col->setAttribute('class',$class);}
                              if(!empty($style)){$col->setAttribute('style',$style);}
                    }
               }
          }
     

     if(!empty($file_name)){$dom->save($file_name);}
     return $dom->saveXML();
     
}


function calc_maes($query)
{
     $sql_fields='';
     if(mb_stristr($query,'enti'))
     {
          $sql_fields.='(datediff(curdate(),enti_fechanac) div 365) as enti_edad1,';
          $sql_fields.='(datediff(curdate(),enti_fechanac) mod 365)div 30 as enti_edad2,';
          $sql_fields.='(datediff(curdate(),enti_fechaini) div 365) as enti_anti1,';
          $sql_fields.='(datediff(curdate(),enti_fechaini) mod 365)div 30 as enti_anti2,';
          
          $sql_fields.='case ';
               $sql_fields.='when left(enti_codigo,2)>="01" and left(enti_codigo,2)<="24" and length(trim(enti_codigo))=10 then "C" ';
               $sql_fields.='when left(enti_codigo,2)>="01" and left(enti_codigo,2)<="24" and length(trim(enti_codigo))=13 then "R" ';
               $sql_fields.='when length(trim(enti_codigo))!=10 and length(trim(enti_codigo))!=13 and length(trim(enti_pasaporte))!=0 then "P" ';
               $sql_fields.='when length(trim(enti_codigo))!=10 and length(trim(enti_codigo))!=13 and length(trim(enti_idexterior))!=0 then "E" ';
               $sql_fields.='when left(enti_codigo,2)="99" and length(trim(enti_pasaporte))>0 then "P" ';
               $sql_fields.='when left(enti_codigo,2)="99" and length(trim(enti_idexterior))>0 then "E" ';
               $sql_fields.='when left(enti_codigo,2)="99" and length(trim(enti_pasaporte))=0 and length(trim(enti_idexterior))=0 then "F" ';
               $sql_fields.='when left(enti_codigo,1)="1"  and length(trim(enti_codigo))=6 then "P" ';
               $sql_fields.='else "-" end as enti_tipoid,';
          $sql_fields.='case ';
               $sql_fields.='when left(enti_codigo,2)>="01" and left(enti_codigo,2)<="24" and substr(enti_codigo,3,1)<="5" then "N" ';
               $sql_fields.='when left(enti_codigo,2)>="01" and left(enti_codigo,2)<="24" and substr(enti_codigo,3,1)="6" then "P" ';
               $sql_fields.='when left(enti_codigo,2)>="01" and left(enti_codigo,2)<="24" and substr(enti_codigo,3,1)="9" then "J" ';
               $sql_fields.='when left(enti_codigo,2)="99" and length(trim(enti_codigo))=10 then "F" ';
               $sql_fields.='when left(enti_codigo,2)="99" and length(trim(enti_codigo))=13 then "F" ';
               $sql_fields.='else "-" end as enti_tiporuc,';
          
          
          
     }
     
     if(mb_stristr($query,'item'))
     {
		 $sql_fields.='concat(';
		 $sql_fields.='char(substr(item_ean,1,1)+35),';
		 $sql_fields.='"!",';
		 $sql_fields.='char(substr(item_ean,2,1)+48),';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"0123")!=0 ';
			 $sql_fields.='then char(substr(item_ean,3,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,3,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"0478")!=0 ';
			 $sql_fields.='then char(substr(item_ean,4,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,4,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"0145")!=0 ';
			 $sql_fields.='then char(substr(item_ean,5,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,5,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"02567")!=0 ';
			 $sql_fields.='then char(substr(item_ean,6,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,6,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"03689")!=0 ';
			 $sql_fields.='then char(substr(item_ean,7,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,7,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='"-",';
		 $sql_fields.='char(substr(item_ean,8,1)+97,substr(item_ean,9,1)+97,substr(item_ean,10,1)+97,substr(item_ean,11,1)+97,substr(item_ean,12,1)+97,substr(item_ean,13,1)+97),"!")';
		 $sql_fields.=' as item_ean13bc, ';
          
		 $sql_fields.='concat(';
		 $sql_fields.='"!",';
		 $sql_fields.='char(substr(item_ean,1,1)+35),';
		 $sql_fields.='char(substr(item_ean,2,1)+48),';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"0123")!=0 ';
			 $sql_fields.='then char(substr(item_ean,3,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,3,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"0478")!=0 ';
			 $sql_fields.='then char(substr(item_ean,4,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,4,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='"-",';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"0145")!=0 ';
			 $sql_fields.='then char(substr(item_ean,5,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,5,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"02567")!=0 ';
			 $sql_fields.='then char(substr(item_ean,6,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,6,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='case ';
			 $sql_fields.='when locate(left(item_ean,1),"03689")!=0 ';
			 $sql_fields.='then char(substr(item_ean,7,1)+48) ';
			 $sql_fields.='else char(substr(item_ean,7,1)+65) ';
			 $sql_fields.='end, ';
		 $sql_fields.='char(substr(item_ean,8,1)+97),"!")';
		 $sql_fields.=' as item_ean8bc, ';
          
          
     }
     
     if(mb_stristr($query,'ctas'))
     {
//           $ctasuper=1;
//           if($ctasuper==1)
//           {
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then left(ctas,1) else left(ctas,2) end as ctan1,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then left(ctas,3) else left(ctas,4) end as ctan2,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then left(ctas,5) else left(ctas,6) end as ctan3,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then left(ctas,7) else left(ctas,8) end as ctan4,';
//                $sql_fields.='ctas as ctan5,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then ctan1.ctas_descri else ctan1b.ctas_descri end as descri1,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then ctan2.ctas_descri else ctan2b.ctas_descri end as descri2,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then ctan3.ctas_descri else ctan3b.ctas_descri end as descri3,';
//                $sql_fields.='case when left(ctas,1) in("1","2","3") then ctan4.ctas_descri else ctan4b.ctas_descri end as descri4,';
//                $sql_fields.='ctas00.ctas_descri as descri5,';
//           }
//           else
//           {
//                $sql_fields.='left(ctas,1) as ctan1,';
//                $sql_fields.='left(ctas,3) as ctan2,';
//                $sql_fields.='left(ctas,5) as ctan3,';
//                $sql_fields.='left(ctas,7) as ctan4,';
//                $sql_fields.='ctas as ctan5,';
//                $sql_fields.='ctan1.ctas_descri as descri1,';
//                $sql_fields.='ctan2.ctas_descri as descri2,';
//                $sql_fields.='ctan3.ctas_descri as descri3,';
//                $sql_fields.='ctan4.ctas_descri as descri4,';
//                $sql_fields.='ctas00.ctas_descri as descri5,';
//           }
     
     }
     
     
     if(!empty($sql_fields)){$sql_fields.='0 as end ';}
     return $sql_fields;
}

function calc_tran($tabla)
{
$xrnd=6;     
$sql_fields='';     
$sql_fields.='sum(cant) as cant_s,';
$sql_fields.='round(sum(case when status in("O","X") then 0 else cant*puni end),6) as subt,';

if(mb_stristr('vtas.clie.carr.comp.prov',$tabla))
{
     if(mb_stristr('vtas',$tabla)){$ldocu1='"FC"';}
     if(mb_stristr('clie',$tabla)){$ldocu1='"PC","PF"';}
     if(mb_stristr('carr',$tabla)){$ldocu1='"CA","LC"';}
     if(mb_stristr('comp',$tabla)){$ldocu1='"FP"';}
     if(mb_stristr('prov',$tabla)){$ldocu1='"PP"';}

     $sql_fields.='sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then 1 ';
     $sql_fields.='else -1 end)';
     $sql_fields.='as signo, ';
          
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni*dcto/100) ';
     $sql_fields.='else abs(cant*puni*dcto/100)*-1 end)';
     $sql_fields.=','.$xrnd.') as tdcto, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni*(1-dcto/100)*prop/100) ';
     $sql_fields.='else abs(cant*puni*(1-dcto/100)*prop/100)*-1 end)';
     $sql_fields.=','.$xrnd.') as tprop, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.')';
     $sql_fields.='then abs(cant*ssid) ';
     $sql_fields.='else abs(cant*ssid)*-1 end)';
     $sql_fields.=','.$xrnd.') as tssid, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then ((abs(cant*puni)*(1-dcto/100))+(abs(cant*puni)*(ice/100)))*if(iva=0,1,0) ';
     $sql_fields.='else ((abs(cant*puni)*(1-dcto/100))+(abs(cant*puni)*(ice/100)))*if(iva=0,1,0)*-1 end)';
     $sql_fields.=','.$xrnd.') as subtiva0, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then ((abs(cant*puni)*(1-dcto/100))+(abs(cant*puni)*(ice/100)))*if(iva!=0,1,0) ';
     $sql_fields.='else ((abs(cant*puni)*(1-dcto/100))+(abs(cant*puni)*(ice/100)))*if(iva!=0,1,0)*-1 end)';
     $sql_fields.=','.$xrnd.') as subtivax, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then (abs(cant*puni)*(1-dcto/100) +(abs(cant*puni)*(ice/100))) *(iva/100) ';
     $sql_fields.='else ((abs(cant*puni)*(1-dcto/100) +(abs(cant*puni)*(ice/100))) *(iva/100))*-1 end)';
     $sql_fields.=','.$xrnd.') as tiva, ';

     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni)*if(ice>0,1,0) ';
     $sql_fields.='else abs(cant*puni)*if(ice>0,1,0)*-1 end)';
     $sql_fields.=','.$xrnd.') as subtice, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni)*(ice/100) ';
     $sql_fields.='else abs(cant*puni)*(ice/100)*-1 end)';
     $sql_fields.=','.$xrnd.') as tice, ';

     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant)*if(irbp>0,1,0) ';
     $sql_fields.='else abs(cant)*if(irbp>0,1,0)*-1 end)';
     $sql_fields.=','.$xrnd.') as subtirbp, ';

     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*irbp) ';
     $sql_fields.='else abs(cant*irbp)*-1 end)';
     $sql_fields.=','.$xrnd.') as tirbp, ';

     if(mb_stristr('vtas.clie',$tabla))
     {
          $sql_fields.='round(sum(case ';
          $sql_fields.='when status="X" or status="O" then 0 ';
          $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
          $sql_fields.='then puni*(1+ice/100)*(1+iva/100)+irbp ';
          $sql_fields.='else 0 end)';
          $sql_fields.=','.$xrnd.') as pvp, ';

          $sql_fields.='round(sum(case ';
          $sql_fields.='when status="X" or status="O" then 0 ';
          $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
          $sql_fields.='then abs(cant*pcp1) ';
          $sql_fields.='else abs(cant*pcp1)*-1 end)';
          $sql_fields.=','.$xrnd.') as tpcp1, ';
     }
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then  (abs(cant*puni)*(1-dcto/100) +(abs(cant*puni)*(ice/100))) *(1+iva/100) +(cant*irbp) +(abs(cant*puni*(1-dcto/100))*prop/100) ';
     $sql_fields.='else ((abs(cant*puni)*(1-dcto/100) +(abs(cant*puni)*(ice/100))) *(1+iva/100) +(cant*irbp) +(abs(cant*puni*(1-dcto/100))*prop/100))*-1 end)';
     $sql_fields.=','.$xrnd.') as total, ';
     
}

if(mb_stristr('inve.prod',$tabla))
{
     if(mb_stristr('inve',$tabla)){$ldocu1='"IB"';}
     if(mb_stristr('prod',$tabla)){$ldocu1='"IP"';}
          
     $sql_fields.='sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then 1 ';
     $sql_fields.='else -1 end)';
     $sql_fields.='as signo, ';
          
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant) ';
     $sql_fields.='else 0 end)';
     $sql_fields.=','.$xrnd.') as ingreso, ';
          
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)not in('.$ldocu1.') ';
     $sql_fields.='then abs(cant) ';
     $sql_fields.='else 0 end)';
     $sql_fields.=','.$xrnd.') as egreso, ';
          
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant) ';
     $sql_fields.='else abs(cant)*-1 end)';
     $sql_fields.=','.$xrnd.') as saldound, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni) ';
     $sql_fields.='else 0 end)';
     $sql_fields.=','.$xrnd.') as debito, ';
          
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status in("O","X") then 0 ';
     $sql_fields.='when left(docu,2)not in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni) ';
     $sql_fields.='else 0 end)';
     $sql_fields.=','.$xrnd.') as credito, ';
          
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni) ';
     $sql_fields.='else abs(cant*puni)*-1 end)';
     $sql_fields.=','.$xrnd.') as saldo, ';
     
     $sql_fields.='round(sum(case ';
     $sql_fields.='when status="X" or status="O" then 0 ';
     $sql_fields.='when left(docu,2)in('.$ldocu1.') ';
     $sql_fields.='then abs(cant*puni) ';
     $sql_fields.='else abs(cant*puni)*-1 end)';
     $sql_fields.=','.$xrnd.') as total, ';
     
}

// extras
{
     $sql_fields.='count(distinct idnum1) as idnum_c,'; 
     $sql_fields.='max(concepto) as concepto_m,';
     $sql_fields.='max(detalle) as detalle_d,';
     $sql_fields.='max(length(concepto)) as concepto_l, ';
     $sql_fields.='max(length(detalle)) as detalle_l, ';
     
     $sql_fields.='date_format(fecha,"%Y-%m") as ames,';
     $sql_fields.='date_format(fecha,"%Y") as anio,';
     $sql_fields.='date_format(fecha,"%m") as mes,';
     $sql_fields.='date_format(fecha,"%v") as sema, ';
     $sql_fields.='date_format(fecha,"%d") as dia,';
     $sql_fields.='upper(date_format(fecha,"%b")) as mes_d,';
     $sql_fields.='upper(date_format(fecha,"%a")) as dia_d,';
     $sql_fields.='ceil(date_format(fecha,"%v")/4) as prdo, ';
     $sql_fields.='date_format(fecha,"%j") as doy, ';
     $sql_fields.='date_format(idate,"%T") as hora, ';
     
		if(mb_stristr('vtas.comp.clie.prov.prod.dxco.dxpa',$tabla))
		{
//       $sql_fields.='case when plazo is null or plazo=0 then 0 else 1 end as pagocredi,';
//       $sql_fields.='case when plazo is not null then adddate(fecha,plazo) else fecha end as vence,';
//       $sql_fields.='case when plazo is not null then date_format(adddate(fecha,plazo),"%d/%b/%y") else date_format(fecha,"%d/%b/%y") end as vencedmy,';
//       $sql_fields.='case when plazo is not null then date_format(adddate(fecha,plazo),"%a") else date_format(fecha,"%a") end as vencedian,';
//       $sql_fields.='case when plazo is not null then datediff(curdate(),adddate(fecha,plazo)) else datediff(curdate(),fecha) end as diasv,';
		}
     
     
}

$sql_fields.='status as stdocu ';

return $sql_fields;     
}


function data_maes($maes,$codigo,$link_data='')
{
     // retorna array asociaivo
//    if(empty($link_data)){$link_data=$_SESSION['link_data'];}
     $link_data=msql_connect('','','',$cfg_empr);     
//      include('../_cfg/config1.php');
//      include_once('func_gene.php');
//      $link_data=msql_connect('','','',$cfg_empr);
   
   $maes0=$maes.'0';
   
   $sql_data ='select * ';
   $sql_data.=' from '.$maes0;
   if($maes=='enti')
   {
      $join='zsub';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
   }
   if($maes=='item')
   {
      $join='lsub';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='mrca';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='clor';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='tlla';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='cair';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
   }
   $sql_data.=' where '.$maes.'_codigo="'.$codigo.'"';
   $res_data=msql_query($sql_data,$link_data);
   
   if(msql_num_rows($res_data)!=0)
   {
      $cfield=msql_num_fields($res_data);
      $data_maes=msql_fetch_assoc($res_data);
//       $data_maes=array();
//       for($idx=0; $idx<=$cfield; $idx++)
//       {
//          $field_name=msql_field_name($res_data,$idx);
//          $data_maes[str_replace($maes.'_','',$field_name)]=msql_result($res_data,0,$field_name);
//       }
   }
   
   return $data_maes;
}


function data_docu($modu,$docu,$idnum,$iddet)
{
//    if(empty($link_data)){$link_data=$_SESSION['link_data'];}
   $link_data=msql_connect('','','',$cfg_empr);
   
   $maes0=$maes.'0';
   
   $sql_data ='select * ';
   $sql_data.=' from '.$maes0;
   if($maes=='enti')
   {
      $join='zsub';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
   }
   if($maes=='item')
   {
      $join='lsub';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='mrca';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='clor';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='tlla';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
      $join='cair';
      $sql_data.=' left join '.$join.'0 on '.$maes.'_'.$join.'='.$join.'_codigo ';
   }
   $sql_data.=' where '.$maes.'_codigo="'.$codigo.'"';
   $res_data=msql_query($sql_data);
   
   if(msql_num_rows($res_data)!=0)
   {
      $cfield=msql_num_fields($res_data);
      $data_maes=msql_fetch_assoc($res_data);
   }
   
   return $data_maes;
}





?>