<?php 

    session_start();

    $cambio_status=false;
    $hay_rechazo = 0;
    $hay_rechazo_faltante = 0;

    $ventanilla = 1;
    $tipo_mensaje = 0;                                                  
    $_POST['fecha']=Date("Y-m-d");    
    $_POST['fechaven']=Date("Y-m-d");
    if (isset($_POST['ajax']) || isset($_POST['OpenChklsObs']) || $_POST['op'] == "distribucion" || isset($_POST['GuardarComentario_res_obs'])) {
		
		include_once ('conexion.inc.php');
		
    } else {
    
		include_once ('settings.php');
		
    }

    $sql = "SELECT ctg_tpt_accion, ctg_tpt_form, ctg_tpt_req_muestra, ctg_tpc_id FROM ctg_tipo_tramites WHERE ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}'";
    $result=$connection->Execute($sql);
    $req_mue=$result->fields["ctg_tpt_req_muestra"];
    $tpc_id=trim($result->fields["ctg_tpc_id"]);

    
    ///ACTUALIZO SAMPLE UNIT EN TODOS LOS CAMPOS
    if ($_POST['id']=="010410" || $_POST['id']=="040100" ){
        $sql="UPDATE ctg_muestras_transac  SET ctg_art_uni_med='".$_POST['size_unit']."' WHERE 
        ctg_numsol_id = '{$_POST['codigo']}' AND 
        ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
        ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
        ctg_arm_id = '{$_POST["ctg_arm_id"]}'";
        echo $sql."<br>"; 
        $result=$connection->Execute($sql);        
    }

	iniciarConexionVUS();

    if ($_POST['id']== '010402' || $_POST['id']== '010403') {
        $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
        vus_{$_POST['tipo']}_dessamp = '".$_POST['vus_qc_dessamp']."',
        vus_{$_POST['tipo']}_reqtest = '".$_POST['vus_qc_reqtest']."',
        vus_{$_POST['tipo']}_specif = '".$_POST['vus_qc_samp_specif']."',
        vus_{$_POST['tipo']}_sta = '2',
        vus_{$_POST['tipo']}_usr = '".$_SESSION['ADMusuario_id']."', 
        vus_{$_POST['tipo']}_dt =now()          
        WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
        $result=$connectionVUS->Execute($sql);
    }

    if (empty($_SESSION['dtb_vus'])) $_SESSION['dtb_vus'] = $_POST['session_vus'];
    if (empty($_SESSION['dtb_adm'])) $_SESSION['dtb_adm'] = $_POST['session_adm'];
    

    if ($_POST['id'] == "010104" || $_POST['id'] == "010110" || $_POST['id'] == "010111" ||  $_POST['id'] == "010204" || $_POST['id'] == "010404" || $_POST['id'] == "010411" ) //2015-12-30
        $_SESSION['dtb_vus'] = 1;

    if ($_POST['id'] == "030501" || $_POST['id'] == "030701" || $_POST['id'] == "030202" || $_POST['id'] == "030203" || $_POST['id'] == "030204" || $_POST['id'] == "0302041") //2015-12-30
        $_SESSION['dtb_vus'] = 1;

    if ($_POST['id'] == "0302A02" || $_POST['id'] == "0302A03" || $_POST['id'] == "0302A04" || $_POST['id'] == "0302A041") //2015-12-30
        $_SESSION['dtb_vus'] = 1;

    if ( $_POST['id'] == "0302B02" || $_POST['id'] == "0302B03" || $_POST['id'] == "0302B04" || $_POST['id'] == "0302B041") //2015-12-30
        $_SESSION['dtb_vus'] = 1;

    if ($_POST['id'] == "030503" || $_POST['id'] == "030703") { //2015-12-30
        $_SESSION['dtb_vus'] = 1;
        $_SESSION['dtb_adm'] = 1;
    }
    
    $dtb_vus = $_SESSION['dtb_vus']; //variable local util  
    /*
	$connectionADM1 = $connection;
	$connectionVUS1 = $connectionVUS;
	$usuario = $_SESSION['ADMusuario_id'];
  
    echo "($ip_ext)($ip_int)<br>";
    
    echo "({$_POST['tipo']})({$_POST['ctg_tpt_id']})({$_POST['codigo']})({$_POST['ctg_tpr_id']})<br>";	
    
    if ($ip_ext == $ip_int)
        local_download($_POST['tipo'],$_POST['ctg_tpt_id'],$_POST['codigo'],$_POST['ctg_tpr_id'],"");
    else
        ftp_download($_POST['tipo'],$_POST['ctg_tpt_id'],$_POST['codigo'],$_POST['ctg_tpr_id'],"");
    
    die();
    */
    echo "dtb vus ".$dtb_vus;
    
	if (strpos("***".$_POST['tabla'],"adm")) 
    	$_POST['tabla'] = $_POST['tabla'].$_POST['tipo'].$_SESSION['dtb_adm'];
	else
	    $_POST['tabla'] = $_POST['tabla'].$_POST['tipo'].$_SESSION['dtb_vus'];
	    
	    
    if (isset($_POST['GuardarComentario_res_obs'])) { 
	
		$res = array();
		
		switch($_POST['id']){
            // drugs
		case '010101':$etapa_inf=10; break;  //verificacion                 escribe 2 al estatus
		case '010102':$etapa_inf=1; break;  //verificacion                  escribe 2 al estatus
		case '010103':$etapa_inf=3; break;  //pre chequeo                   
		case '010104':$etapa_inf=4; break;  //recepcion de muestras
		case '010105':$etapa_inf=3; break;  //chequeo genera numero de admision
        // licensing
        case '010201':$etapa_inf=10; break;  //verificacion                 escribe 2 al estatus
        case '010202':$etapa_inf=1; break;  //verificacion                  escribe 2 al estatus
        case '010203':$etapa_inf=3; break;  //pre chequeo                   
        case '010205':$etapa_inf=3; break;  //chequeo genera numero de admision
        // QClab
        case '010401':$etapa_inf=10; break;  //verificacion                 escribe 2 al estatus
        case '010402':$etapa_inf=1; break;  //verificacion                  escribe 2 al estatus
        case '010403':$etapa_inf=3; break;  //pre chequeo                   
        case '010405':$etapa_inf=3; break;  //chequeo genera numero de admision
        case '010411':$etapa_inf=3; break;  //pre chequeo                   
		}
		$sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKinf\" SET 
        \"vus_{$_POST['tipo']}CHKi_res_obs\" = '{$_POST['res_obs']}',
        \"vus_{$_POST['tipo']}CHKi_sta\" = '2', 
        \"vus_{$_POST['tipo']}CHKi_usr\" = '{$_SESSION['ADMusuario_id']}', 
        \"vus_{$_POST['tipo']}CHKi_dt\" = now() WHERE         
        \"vus_{$_POST['tipo']}CHKi_numsol\" = '{$_POST['codigo']}' AND 
        \"vus_{$_POST['tipo']}CHKi_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
        \"vus_{$_POST['tipo']}CHKi_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
        \"vus_{$_POST['tipo']}CHKi_etapa\" = '{$etapa_inf}'";
		$result = $connectionVUS->Execute($sql);

        $res['sql'] = $sql;		    
        $res['Affected'] = $connectionVUS->Affected_Rows();
        $res['session_vus'] = $_POST['session_vus'];
		      
		echo json_encode($res);
    
		die();		
    }
		
    if (isset($_POST['OpenChklsObs'])) { //2015-02-17
    
		$res = array();

		$arr_label[315]='estatus';
		$arr_label[508]='dias';
		$arr_label[277]='fecha';
		$arr_label[4]='usuario';
		$arr_label[14]='comentarios';
		$arr_label[137]='edita';
		$arr_label[51]='no_data';
		$arr_label[498]='etapa';

		
		$arr_lang = "315,508,277,4,14,137,51,498";

		include('form_language.php');   
		
    
		$html = "<table width=100% cellspacing=1 cellpadding=0 class='light_grid ui-corner-top'>";

		$html .= "<thead>";

		//$html .= "<tr><td>{$arr_label['etapa']}</td><td>{$arr_label['estatus']}</td><td>{$arr_label['dias']}</td><td>{$arr_label['fecha']}</td><td>{$arr_label['usuario']}</td><td>{$arr_label['comentarios']}</td><td>{$arr_label['edita']}</td></tr>";

		$html .= "<tr>
			<td width=200>{$arr_label['etapa']}</td> <td width=50>{$arr_label['fecha']}</td><td width=100 >{$arr_label['usuario']}</td><td>{$arr_label['comentarios']}</td></tr>";
		
		$html .= "</thead>";
		$html .= "<tbody>";

        switch (substr($_POST['id'],0,4)) {
            case '0101':{
                $u = 1;         
                $str = "'010101','010102','010103','010105'";
            }
                break;
            case '0102':{
                $u = 1;         
                $str = "'010201','010202','010203','010205'";
            }
                 break;
             case '0104':{
                $u = 1;         
                $str = "'010401','010402','010403','010405','010406'";
            }
                 break;
            case '0302':{
                $u = 4;
                $str = "'030202','030203','030204','0302041','030205','030206','03020701','03020702','03020703'";
                $str .= ",'0302A02','0302A03','0302A04','0302A041','0302A05','0302A06','0302A0701','0302A0702'";
                $str .= ",'0302B02','0302B03','0302B04','0302B041','0302B05','0302B06','0302B0701','0302B0702'";
            }
                break;

            case '0301':{
                $u = 4;
                $str = "'030102','030103','030104','0301041','030105','030106','030107'";
            }
                break;
       }
		
		
        $sql = "SELECT * FROM \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\"  WHERE
        \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
        \"vus_{$_POST['tipo']}CHK_ttc_id\" = '{$_POST['cat_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_ttd_id\" = '{$_POST['doc_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_ttl_part\" = '{$_POST['part_id']}'";
        
        $res['sql'] = $sql;
        
        //echo $sql."<br>";
        $result2=$connectionVUS->Execute($sql);
        if (!$result2->EOF) {				
				$sql = "SELECT ctg_men_id, ctg_men_desc FROM ctg_menus WHERE ctg_men_id IN ($str) ORDER BY ctg_men_id";				
				$result3=$connection->Execute($sql);
				if (!$result3->EOF) {  
					while (!$result3->EOF) {
						$operador3 = $result3->fields;    
						$id = $operador3['ctg_men_id'];
						$arr_ids[] = $id;
						$arr_label[$id] = $operador3['ctg_men_desc'];
						$result3->MoveNext();
					}
				}
			
				$operador2 = $result2->fields;    

				for ($i=0;$i<count($arr_ids);$i++) {            
					$ii = ($i+$u)*6;
					//$html .= "<tr><td>{$arr_label[$arr_ids[$i]]}</td>";

					$html .= "<tr><td>".($arr_ids[$i] == $_POST['id'] ? "<b>" : "").$arr_label[$arr_ids[$i]].($arr_ids[$i] == $_POST['id'] ? "</b>" : "")."</td>";

											
					for ($j=0;$j<6;$j++) {					
						switch($j) {
						case 2:
							$operador2[$ii+$j] = date("d/m/Y",strtotime($operador2[$ii+$j]));
							break;
						case 3:
							$sql = "SELECT adm_usr_nombre FROM adm_usuarios WHERE adm_usr_ci = '{$operador2[$ii+$j]}'";				
							$result4=$connection->Execute($sql);
							if (!$result4->EOF) {
								$operador2[$ii+$j] = $result4->fields[0];
							}
							break;
						case 4:
							break;
						}
						if ($j >= 2 && $j <=4)
						$html .= "<td nowrap=true>".($arr_ids[$i] == $_POST['id'] ? "<b>" : "").$operador2[$ii+$j].($arr_ids[$i] == $_POST['id'] ? "</b>" : "")."</td>";
						//$html .= "<td>(".($ii+$j).")".$operador2[$ii+$j]."</td>";
					}
					$html .= "</tr>";
				}
	
        } else {
        			
			$html .= "<tr><td colspan=4 align=center>{$arr_label['no_data']}</td></tr>";        
        }
        
		$html .= "</tbody>";

		$html .= "</table>";
	
        $res['html'] = $html;		    
		      
		echo json_encode($res);
    
		die();
	}

    if (isset($_POST['ajax'])) { //2012-11-24 viene de watch_vus_tramites_docs.php cuando pierde el foco de los areatext

        switch($_POST['id']){
            // drugs
        case '010101':$campo=10; break;  //2015-10-14
        case '010102':$campo=1; break;  //verificacion                  escribe 2 al estatus
        case '010103':$campo=3; break;  //pre chequeo                   
        case '010105':$campo=3; break;  //chequeo genera numero de admision
        //company licences
        case '010201':$campo=10; break;  //2015-10-14
        case '010202':$campo=1; break;  //verificacion                  escribe 2 al estatus
        case '010203':$campo=3; break;  //pre chequeo                   
        case '010205':$campo=3; break;  //chequeo genera numero de admision
        //qc lab
        case '010401':$campo=10; break;  //2015-10-14
        case '010402':$campo=1; break;  //verificacion                  escribe 2 al estatus
        case '010403':$campo=3; break;  //pre chequeo                   
        case '010405':$campo=3; break;  //chequeo genera numero de admision
        // 
        case '030102'://Evaluacion 4
        case '030103'://Asesoria 5
        case '030104'://Calidad 6
        case '030105'://Coordinacion II 7 
        case '030106'://Junta revisoria 8
        case '030107'://comision tecnica 9
        // drugs
        case '030202'://Evaluacion 4
        case '030203'://Asesoria 5
        case '030204'://Calidad 6
        case '030206'://Junta revisoria 8
        case '030207'://comision tecnica 9
        //case '030208'://Resultado final  puede que tambien entre aca 2015-10-14
        //case '030209'://Coordinacion III  puede que tambien entre aca 2015-10-14
                        
                        $campo = intval(substr($_POST['id'],5,1)) + 2;
                        
                        break; //este viend de form_adm_control_etapa_evaluacion.php

        case '0302A02'://Evaluacion 4
        case '0302A03'://Asesoria 5
        case '0302A04'://Calidad 6
        case '0302A05'://Coordinacion II 7 
        case '0302A06'://Junta revisoria 8
        case '0302A07'://comision tecnica 9
        //case '0302A08'://Resultado final  puede que tambien entre aca 2015-10-14
        //case '0302A09'://Coordinacion III  puede que tambien entre aca 2015-10-14
                        
                        $campo = intval(substr($_POST['id'],6,1)) + 2;
                        
                        break; //este viend de form_adm_control_etapa_evaluacion.php

        case '0302B02'://Evaluacion 4
        case '0302B03'://Asesoria 5
        case '0302B04'://Calidad 6
        case '0302B05'://Coordinacion II 7 
        case '0302B06'://Junta revisoria 8
        case '0302B07'://comision tecnica 9
        //case '0302B08'://Resultado final  puede que tambien entre aca 2015-10-14
        //case '0302B09'://Coordinacion III  puede que tambien entre aca 2015-10-14
                        
                        $campo = intval(substr($_POST['id'],6,1)) + 2;
                        
                        break; //este viend de form_adm_control_etapa_evaluacion.php

        case '0302A041':
        case '0302B041':
        case '0302041'://Calidad 6
        case '0301041'://Calidad 6
            $campo = 10;
            break; //este viend de form_adm_control_etapa_evaluacion.php
        case '03020501'://LOQ
        case '03020502'://LOQ
            $campo = 8;
            break; //este viend de form_adm_control_etapa_evaluacion.php
        }                
        
		echo "(_POST['res']=".$_POST['res'].")";

        $res = intval($_POST['res']);

        /*for ($l=1;$l<10;$l++) { //ahora si es inteligente inicializa para los 4 checklist 1,2,3,4
            $res_st[$l] = '0'; 
            $res_dt[$l] = '1900-01-01 00:00:00'; 
            $res_ds[$l] = '0'; 
            $res_us[$l] = ''; 
            $res_obs[$l] = ''; 
            $res_aut[$l] = '0';
        }*/

        if ($campo > 3)
            $ds = 0;
        else
            $ds = $_POST['dias'];

        if($res==0) $aut='1'; else $aut='0';
        $new_res_st = $res;
        $new_res_dt = date("Y-m-d H:i:s");
        $new_res_ds = $ds;
        $new_res_us = $_SESSION['ADMusuario_id'];
        $new_res_obs = str_replace("#039;","'",$_POST['obs']); //$_POST['obs'];

        $new_res_aut = $aut;
        if (empty($_POST['res_obs'])) $new_res_aut='0';
        
        $cat_id = $_POST['cat_id'];
        $doc_id = $_POST['doc_id'];
        $part_id = $_POST['part_id'];
        $uni_id=substr($_POST['id'],4,2);

		$res = array();       
			                
        $sql = "SELECT  \"vus_{$_POST['tipo']}CHK_res{$campo}_st\", \"vus_{$_POST['tipo']}CHK_res{$campo}_obs\", \"vus_{$_POST['tipo']}CHK_res{$campo}_dt\", \"vus_{$_POST['tipo']}CHK_res{$campo}_us\", \"vus_{$_POST['tipo']}CHK_res{$campo}_ds\"
        FROM \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\"  WHERE                     
        \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_tec_id\" = '{$_SESSION['ADMusuario_id']}' AND 
        \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
        \"vus_{$_POST['tipo']}CHK_ttc_id\" = '$cat_id' AND 
        \"vus_{$_POST['tipo']}CHK_ttd_id\" = '$doc_id' AND 
        \"vus_{$_POST['tipo']}CHK_ttl_part\" = '$part_id'";
        echo "por aqui $sql<br>";
        $result2=$connectionVUS->Execute($sql);
        if (!$result2->EOF) {                            
            $operador2 = $result2->fields;    
            
            echo "(".$operador2[0].")";

            $sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" SET
            \"vus_{$_POST['tipo']}CHK_res{$campo}_st\" = '{$new_res_st}', 
            \"vus_{$_POST['tipo']}CHK_res{$campo}_dt\" = '{$new_res_dt}', 
            \"vus_{$_POST['tipo']}CHK_res{$campo}_ds\" = '{$new_res_ds}', 
            \"vus_{$_POST['tipo']}CHK_res{$campo}_us\" = '{$new_res_us}', 
            \"vus_{$_POST['tipo']}CHK_res{$campo}_obs\" = '{$new_res_obs}',
            \"vus_{$_POST['tipo']}CHK_res{$campo}_aut\" = '{$new_res_aut}',
            \"vus_{$_POST['tipo']}CHK_uni{$campo}_id\" = '{$uni_id}',
            \"vus_{$_POST['tipo']}CHK_sta\" = '2', 
            \"vus_{$_POST['tipo']}CHK_usr\" = '".$_SESSION['ADMusuario_id']."', 
            \"vus_{$_POST['tipo']}CHK_dt\" =now()										
            WHERE         
            \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
            \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
            \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
            \"vus_{$_POST['tipo']}CHK_tec_id\" = '{$_SESSION['ADMusuario_id']}' AND 
            \"vus_{$_POST['tipo']}CHK_ttc_id\" = '$cat_id' AND 
            \"vus_{$_POST['tipo']}CHK_ttd_id\" = '$doc_id' AND 
            \"vus_{$_POST['tipo']}CHK_ttl_part\" = '$part_id'";

        } else {
            $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" (
            \"vus_{$_POST['tipo']}CHK_numsol\",
            \"vus_{$_POST['tipo']}CHK_tpt_id\", 
            \"vus_{$_POST['tipo']}CHK_tpr_id\", 
            \"vus_{$_POST['tipo']}CHK_tec_id\", 
            \"vus_{$_POST['tipo']}CHK_ttc_id\", 
            \"vus_{$_POST['tipo']}CHK_ttd_id\", 
            \"vus_{$_POST['tipo']}CHK_ttl_part\", 
            \"vus_{$_POST['tipo']}CHK_res{$campo}_st\",\"vus_{$_POST['tipo']}CHK_res{$campo}_dt\",\"vus_{$_POST['tipo']}CHK_res{$campo}_ds\",\"vus_{$_POST['tipo']}CHK_res{$campo}_us\",\"vus_{$_POST['tipo']}CHK_res{$campo}_obs\", \"vus_{$_POST['tipo']}CHK_res{$campo}_aut\",            
            \"vus_{$_POST['tipo']}CHK_uni{$campo}_id\", 
            \"vus_{$_POST['tipo']}CHK_sta\", 
            \"vus_{$_POST['tipo']}CHK_usr\", 
            \"vus_{$_POST['tipo']}CHK_dt\"
            ) VALUES (
            '{$_POST['codigo']}',
            '{$_POST['ctg_tpt_id']}',
            '{$_POST['ctg_tpr_id']}',
            '{$_SESSION['ADMusuario_id']}',
            '$cat_id',
            '$doc_id',
            '$part_id',
            '{$new_res_st}','{$new_res_dt}','{$new_res_ds}','{$new_res_us}','{$new_res_obs}','{$new_res_aut}', 
            '{$uni_id}',
            '1',
            '".$_SESSION['ADMusuario_id']."',
            now());";
                                 
        }
        echo "<br>".$sql;
        $result2=$connectionVUS->Execute($sql);
        
        $res['sql'] = $sql;		    
        $res['affected'] = $connectionVUS->Affected_Rows();		    
        $res['error'] = $connectionVUS->ErrorMsg();	
		      
		echo json_encode($res);
		
        die();
   
    }

    switch($_POST['id']){    

    case '040100':
    case '010410': //distribucion de muestras watch_vus_tramites_asignacion.php


            function ctg_muestras_transac($cant_sal, $POST, $ctg_esa_id, $connection, $datos_grabados){

                $sql="UPDATE ctg_muestras_transac SET
                ctg_art_cant_sal = ctg_art_cant_sal+{$cant_sal},
                ctg_art_saldo = ctg_art_cant_ent - (ctg_art_cant_sal+{$cant_sal}),
                ctg_art_sta = '2', 
                ctg_art_usr = '".$_SESSION['ADMusuario_id']."', 
                ctg_art_dt =now()           
                WHERE ctg_numsol_id = '{$POST['codigo']}' 
                AND ctg_tpt_id = '{$POST['ctg_tpt_id']}' 
                AND ctg_tpr_id = '{$POST['ctg_tpr_id']}' 
                AND ctg_arm_id = '{$POST["ctg_arm_id"]}' 
                AND ctg_esa_id IN ($ctg_esa_id)"; 
                echo $sql;
                $result=$connection->Execute($sql);
                if ($connection->Affected_Rows() > 0)
                    $info = $datos_grabados;
                $error = $connection->ErrorMsg();                                        
                echo "<br> update <br>".$sql."<br>[".$error."]<br>[".$info."]<br>";
            }


            function ctg_muestras_inven($cant_sal, $POST, $connection, $datos_grabados){

                $sql="UPDATE ctg_muestras_inven SET                        
                ctg_ari_cant_sal = ctg_ari_cant_sal+{$cant_sal},
                ctg_ari_cant_saldo = ctg_ari_cant_ent - (ctg_ari_cant_sal+{$cant_sal}),
                ctg_ari_sta = '2', 
                ctg_ari_usr = '".$_SESSION['ADMusuario_id']."', 
                ctg_ari_dt =now()           
                WHERE ctg_numsol_id = '{$POST['codigo']}' 
                AND ctg_tpt_id = '{$POST['ctg_tpt_id']}' 
                AND ctg_tpr_id = '{$POST['ctg_tpr_id']}' 
                AND ctg_arm_id = '{$POST["ctg_arm_id"]}'";
                $result=$connection->Execute($sql);
                $error = $connection->ErrorMsg();   
                if ($connection->Affected_Rows() > 0)
                    $info = $datos_grabados;
                echo $sql."<br>[".$error."]<br>[".$info."]<br>";
            }

            if ($_POST['op'] == "borra_distribucion") {

                iniciarConexionVUS();

                $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} 
                SET 
                vus_{$_POST['tipo']}_dist".($_POST['id'] == '010410' ? '1':'2')." = '0' 
                WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' 
                AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' 
                AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                /*
                if ($_POST['id'] == '010410'){
                    $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
                    vus_{$_POST['tipo']}_dist1 = '0' WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                } else {
                    $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
                    vus_{$_POST['tipo']}_dist2 = '0' WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                }
                */
                echo $sql."<br>";
                //die();
                $result=$connectionVUS->Execute($sql);

				/* borrar ensayos */
                $sql="DELETE FROM lab_control_pa_ensayos WHERE 
                lab_coe_numsol = '{$_POST['codigo']}' 
                AND lab_coe_tpr_id = '{$_POST['ctg_tpr_id']}' 
                AND lab_coe_tpt_id = '{$_POST['ctg_tpt_id']}' 
                AND lab_coe_arm_id = '{$_POST["ctg_arm_id"]}' 
                AND lab_coe_esa_id = '{$_POST['ctg_esa_id_del']}'";
                $result = $connection->Execute ( $sql );
                if ($connection->Affected_Rows() > 0) $info = $arr_label['datos_borrados'];
                $error = $connection->ErrorMsg();	
                echo "<br>transac ".$sql."<br>[".$error."]  [".$info."] (".$connection->Affected_Rows().")<br><br>";

				/* borrar tecnicos */
                $sql="DELETE FROM lab_control_pa_tecnicos WHERE 
                lab_cot_numsol = '{$_POST['codigo']}' 
                AND lab_cot_tpr_id = '{$_POST['ctg_tpr_id']}' 
                AND lab_cot_tpt_id = '{$_POST['ctg_tpt_id']}' 
                AND lab_cot_arm_id = '{$_POST["ctg_arm_id"]}' 
                AND lab_cot_esa_id = '{$_POST['ctg_esa_id_del']}'";
                $result = $connection->Execute ( $sql );
                if ($connection->Affected_Rows() > 0) $info = $arr_label['datos_borrados'];
                $error = $connection->ErrorMsg();	
                echo "<br>transac ".$sql."<br>[".$error."]  [".$info."] (".$connection->Affected_Rows().")<br><br>";

                $sql="SELECT ctg_art_cant_ent, ctg_art_cant_sal, ctg_art_saldo FROM ctg_muestras_transac WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                AND ctg_esa_id = '{$_POST['ctg_esa_id_del']}'";
                echo $sql."<br>";
                $result=$connection->Execute($sql);
                if (!$result->EOF) {
                    $operador = $result->fields;
                    $cant_sal=$operador['ctg_art_cant_ent'];
					//if($_POST['id']=='040100')
                      //{ $cant_sal=$operador['ctg_art_cant_sal']; }
                }

				if($_POST['id']=='040100'){
                    /*
                    $sql="UPDATE ctg_muestras_transac SET
                    ctg_art_cant_sal = ctg_art_cant_sal-{$cant_sal},
                    ctg_art_saldo = ctg_art_cant_ent - (ctg_art_cant_sal-{$cant_sal}),
                    ctg_art_sta = '2', 
                    ctg_art_usr = '".$_SESSION['ADMusuario_id']."', 
                    ctg_art_dt =now()			
                    WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                    AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                    AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                    AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                    AND ctg_esa_id IN (".AdmNivelSubStr().")";*/

                    ctg_muestras_transac(-$cant_sal,$_POST,AdmNivelSubStr(), $connection, $arr_label['datos_borrados']);

				} else {

                    ctg_muestras_transac(-$cant_sal,$_POST,"'0106{$_POST['ctg_tpr_id']}'", $connection, $arr_label['datos_borrados']);

                    /*
                    $sql="UPDATE ctg_muestras_transac SET
                    ctg_art_cant_sal = ctg_art_cant_sal-{$cant_sal},
                    ctg_art_saldo = ctg_art_cant_ent - (ctg_art_cant_sal-{$cant_sal}),                    
                    ctg_art_sta = '2', 
                    ctg_art_usr = '".$_SESSION['ADMusuario_id']."', 
                    ctg_art_dt =now()			
                    WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                    AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                    AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                    AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                    AND ctg_esa_id = '0106{$_POST['ctg_tpr_id']}'";
                    */
				}


                $sql="DELETE FROM ctg_muestras_transac WHERE ctg_numsol_id='{$_POST['codigo']}' 
                AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                AND ctg_esa_id = '{$_POST['ctg_esa_id_del']}'";
                $result = $connection->Execute ( $sql );
                if ($connection->Affected_Rows() > 0)
                    $info = $arr_label['datos_borrados'];
                $error = $connection->ErrorMsg();	
                echo "<br>transac ".$sql."<br>[".$error."]  [".$info."] (".$connection->Affected_Rows().")<br>";
                
                if ($error == "") {

                    if($_POST['id'] == '010410'){ //primer nivel

                        //$new_saldo =  $_POST['ctg_ari_cant_saldo'] + $cant_sal;
                        //ctg_ari_cant_saldo = '{$new_saldo}',
                        /*
                        $sql="UPDATE ctg_muestras_inven SET
                        ctg_ari_cant_sal = ctg_ari_cant_sal-{$cant_sal},
                        ctg_ari_cant_saldo = ctg_ari_cant_ent - (ctg_ari_cant_sal-{$cant_sal}),
                        ctg_ari_sta = '2', 
                        ctg_ari_usr = '".$_SESSION['ADMusuario_id']."', 
                        ctg_ari_dt = now()			
                        WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                        AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                        AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                        AND ctg_arm_id = '{$_POST["ctg_arm_id"]}'";
                        */
                        
                        ctg_muestras_inven(-$cant_sal, $_POST, $connection, $arr_label['datos_borrados']);
    									
                    }
									
                    if ($error == "") {
                        $sql = "DELETE FROM lab_control_{$_POST['tipo']} WHERE lab_con_numsol = '{$_POST['codigo']}' 
                        AND lab_con_tpt_id = '{$_POST['ctg_tpt_id']}' 
                        AND lab_con_tpr_id = '{$_POST['ctg_tpr_id']}' 
                        AND lab_con_arm_id = '{$_POST["ctg_arm_id"]}' 
                        AND lab_con_esa_id = '{$_POST['ctg_esa_id_del']}'";
                        $result = $connection->Execute ( $sql );
                        if ($connection->Affected_Rows() > 0)
                            $info = $arr_label['datos_borrados'];
                        $error = $connection->ErrorMsg();	
                        echo "<br>lab ".$sql."<br>[".$error."]  [".$info."] (".$connection->Affected_Rows().")<br>";
                    }
                }


                if($_POST['id']=='040100'){
                    /////regresar el id lab vus_tramites
                    echo "<br><br>regresar el id lab vus_tramites<br>";
                    $sql="SELECT ctg_art_cant_ent, ctg_art_cant_sal FROM ctg_muestras_transac WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                    AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                    AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                    AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                    AND ctg_esa_id IN (".AdmNivelSubStr().")";
                    echo $sql."<br><br>";
                    $result=$connection->Execute($sql);
                    if (!$result->EOF) {
                        $operador = $result->fields;
                        if($operador['ctg_art_cant_sal']=='' || $operador['ctg_art_cant_sal']=='0'){
                            iniciarConexionVUS();
                            $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
                            vus_{$_POST['tipo']}_lab_est = '1',
                            vus_{$_POST['tipo']}_sta = '2', 
                            vus_{$_POST['tipo']}_usr = '".$_SESSION['ADMusuario_id']."', 
                            vus_{$_POST['tipo']}_dt =now()			
                            WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' 
                            AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' 
                            AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                            echo $sql."<br>";
                            $result=$connectionVUS->Execute($sql);
                        }
                    }
                }

            }
            
            
            if ($_POST['op'] == "graba_distribucion") {

                $arr_label[1427]='distrib_muestra';
                $arr_lang = "1427";
                include ('form_language.php');  

                //$_POST['ctg_art_cant_sal'] = clean_num ($_POST['ctg_art_cant_sal']);

                iniciarConexionVUS();

                $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} 
                SET 
                vus_{$_POST['tipo']}_dist".($_POST['id'] == '010410' ? '1':'2')." = '1', 
                vus_{$_POST['tipo']}_dessamp = '{$_POST['vus_qc_dessamp']}'
                WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' 
                AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' 
                AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";

                 echo $sql."<br>";
                //die();
                $result=$connectionVUS->Execute($sql);

                $sql="INSERT INTO lab_control_{$_POST['tipo']} (   
                lab_con_numsol,
                lab_con_tpt_id,
                lab_con_tpr_id,
                lab_con_arm_id,
                lab_con_esa_id,
                lab_con_asi_dt,	
                lab_con_asi_mue, 
                lab_con_asi_usr,
                lab_con_asi_obs,
                lab_con_ini_dt,
                lab_con_exp_dt,
                lab_con_fin_dt,
                lab_con_res1,
                lab_con_res2,
                lab_con_res3,
                lab_con_res4,
	            lab_con_sta,
                lab_con_usr,
                lab_con_dt
                ) VALUES (    
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',                   
                '{$_POST['ctg_tpr_id']}',
                '".$_POST["ctg_arm_id"]."',
                '".$_POST['ctg_esa_id']."',
                '1900-01-01 00:00:00',
                '".$_POST['ctg_art_cant_sal']."',
                '',
                '".$_POST['res_obs']."',
                '1900-01-01 00:00:00',
                '1900-01-01',
                '1900-01-01 00:00:00',                			
                '0',
                '0',
                '0',
                '0',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";     
                        echo $sql;
                $result=$connection->Execute($sql);
                $error = $connection->ErrorMsg();	
                if ($connection->Affected_Rows() == 1)
                $info = $arr_label['datos_grabados'];                                         

                 echo $sql."<br>[".$error."]<br>[".$info."]<br>";
                 
                 if ($error == ""){
                    
                    $sql="SELECT * FROM ctg_muestras_transac WHERE 
                    ctg_numsol_id = '{$_POST['codigo']}' 
                    AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                    AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                    AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                    AND ctg_esa_id = '{$_POST['ctg_esa_id']}'";
                    echo $sql."<br>";
                    $id_corr = 0;
                    $result=$connection->Execute($sql);
                    if (!$result->EOF) {
                      	$operador = $result->fields;
                        $id_corr = $operador['ctg_art_id'];
                    }
                    $id_corr++;
                              
	                if($_POST['id']=='040100') //segundo nivel
                    {
                        //$sal=$_POST['ctg_art_cant_sal']; 
                        //$ent=0; 
                        //$saldo=0; 
                        $ent=$_POST['ctg_art_cant_sal']; 
                        $saldo=$_POST['ctg_art_cant_sal']; 
                        $sal=0; 

                    }
	                else
                        {
                        $ent=$_POST['ctg_art_cant_sal']; 
                        $saldo=$_POST['ctg_art_cant_sal']; 
                        $sal=0; 
                        }
                                     
                    $sql="INSERT INTO ctg_muestras_transac (
                    ctg_numsol_id, 
                    ctg_tpr_id, 	
                    ctg_tpt_id,
                    ctg_arm_id,
                    ctg_esa_id,
                    ctg_art_id,
                    ctg_art_opeusr,
                    ctg_art_opedt,
                    ctg_art_tpoope,
                    ctg_art_motivo,
                    ctg_art_cant_ent,
                    ctg_art_cant_sal,
                    ctg_art_saldo,
                    ctg_art_uni_med,
                    ctg_art_test_samp,
                    ctg_art_rete_samp,                   
                    ctg_art_sta,
                    ctg_art_usr,
                    ctg_art_dt
                    ) VALUES (    
                    '{$_POST['codigo']}',
                    '{$_POST['ctg_tpr_id']}',
                    '{$_POST['ctg_tpt_id']}',                   
                    '{$_POST["ctg_arm_id"]}',
                    '{$_POST['ctg_esa_id']}',
                    '{$id_corr}',
                    '".$_SESSION['ADMusuario_id']."',
                    now(),
                    '2',
                    '".$arr_label['distrib_muestra']."',
                    '".$ent."',
                    '".$sal."',
                    '".$saldo."',
                    '".$_POST["size_unit"]."',
                    '{$_POST["ctg_art_test_samp"]}',
                    '{$_POST["ctg_art_rete_samp"]}',
                    '1',
                    '".$_SESSION['ADMusuario_id']."',
                    now());";          
                    echo $sql;
                    $result=$connection->Execute($sql);
                    $error = $connection->ErrorMsg();	
                    if ($connection->Affected_Rows() == 1)
                        $info = $arr_label['datos_grabados'];             

                    echo $sql."<br>[".$error."]<br>[".$info."]<br>";

                    echo "before (".$_POST['id'].")<br>";
                    
                    if($_POST['id'] == '040100'){ //segundo nivel
                        /*
                        $sql="UPDATE ctg_muestras_transac SET
                        ctg_art_cant_sal = ctg_art_cant_sal+{$_POST['ctg_art_cant_sal']},
                        ctg_art_saldo = ctg_art_cant_ent - (ctg_art_cant_sal+{$_POST['ctg_art_cant_sal']}),
                        ctg_art_sta = '2', 
                        ctg_art_usr = '".$_SESSION['ADMusuario_id']."', 
                        ctg_art_dt =now()			
                        WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                        AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                        AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                        AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                        AND ctg_esa_id IN (".AdmNivelSubStr().")";*/

                        ctg_muestras_transac($_POST['ctg_art_cant_sal'], $_POST,AdmNivelSubStr(), $connection, $arr_label['datos_grabados']);

                    }else{

                        ctg_muestras_transac($_POST['ctg_art_cant_sal'], $_POST,"'0106{$_POST['ctg_tpr_id']}'", $connection, $arr_label['datos_grabados']);
                        /*
                        $sql="UPDATE ctg_muestras_transac SET
                        ctg_art_cant_sal = ctg_art_cant_sal+{$_POST['ctg_art_cant_sal']},
                        ctg_art_saldo = ctg_art_cant_ent - (ctg_art_cant_sal+{$_POST['ctg_art_cant_sal']}),
                        ctg_art_sta = '2', 
                        ctg_art_usr = '".$_SESSION['ADMusuario_id']."', 
                        ctg_art_dt =now()			
                        WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                        AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                        AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                        AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                        AND ctg_esa_id='0106{$_POST['ctg_tpr_id']}'";
                        */
					}
                    /*$result=$connection->Execute($sql);
                    $error = $connection->ErrorMsg();	
                    if ($connection->Affected_Rows() == 1) $info = $arr_label['datos_grabados'];
                    echo $sql."<br>[".$error."]<br>[".$info."]<br>";*/

                    if($_POST['id'] == '010410'){ //primer nivel

                        //$new_saldo =  $_POST['ctg_ari_cant_saldo']-$_POST['ctg_art_cant_sal'];
                        //echo "saldos:[".$_POST['ctg_ari_cant_saldo']."] salida:[".$_POST['ctg_art_cant_sal']."] new saldo:[$new_saldo]<br>";
                        //ctg_ari_cant_saldo = '".$new_saldo."',

                        /*
                        $sql="UPDATE ctg_muestras_inven SET                        
                        ctg_ari_cant_sal = ctg_ari_cant_sal+{$_POST['ctg_art_cant_sal']},
                        ctg_ari_cant_saldo = ctg_ari_cant_ent - (ctg_ari_cant_sal+{$_POST['ctg_art_cant_sal']}),
                        ctg_ari_sta = '2', 
                        ctg_ari_usr = '".$_SESSION['ADMusuario_id']."', 
                        ctg_ari_dt =now()			
                        WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                        AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
                        AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                        AND ctg_arm_id = '{$_POST["ctg_arm_id"]}'";
                        */
                        ctg_muestras_inven($_POST['ctg_art_cant_sal'], $_POST, $connection, $arr_label['datos_grabados']);
	                }
                   
                }        

                if($_POST['id'] == '040100'){ //segundo nivel
                    /////crear el id lab vus_tramites
                    echo "<br><br>crear el id lab vus_tramites<br>";
                    $sql="SELECT ctg_art_cant_ent, ctg_art_cant_sal FROM ctg_muestras_transac WHERE ctg_numsol_id = '{$_POST['codigo']}' 
                    AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' 
			        AND ctg_tpr_id = '{$_POST['ctg_tpr_id']}' 
                    AND ctg_arm_id = '{$_POST["ctg_arm_id"]}' 
                    AND ctg_esa_id IN (".AdmNivelSubStr().")";
	                $result=$connection->Execute($sql);
	                if (!$result->EOF) {
	                $operador = $result->fields;
		                if(intval($operador['ctg_art_cant_sal']) != 0){
			                iniciarConexionVUS();
			                $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
			                vus_{$_POST['tipo']}_lab_est = '2',
			                vus_{$_POST['tipo']}_sta = '2', 
			                vus_{$_POST['tipo']}_usr = '".$_SESSION['ADMusuario_id']."', 
			                vus_{$_POST['tipo']}_dt =now()			
			                WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' 
                            AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' 
                            AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
			                echo $sql."<br>";
			                $result=$connectionVUS->Execute($sql);
		                }
	                }
                }
                   
            }    

            break; 

    case '03020103'://asignacion de procesos
            // UPDATE ESTATUS DE ASSESOR ASIGNADOS
            iniciarConexionVUS();
            $sql="UPDATE \"vus_tramites_{$_POST['tipo']}_ESTATUS\" SET
            \"vus_{$_POST['tipo']}EST_steps\" = '1'
            WHERE         
            vus_{$_POST['tipo']}EST_numsol = '{$_POST['codigo']}' AND 
            vus_{$_POST['tipo']}EST_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
            vus_{$_POST['tipo']}EST_tpr_id = '{$_POST['ctg_tpr_id']}' AND
            vus_{$_POST['tipo']}EST_tts_id = '5' ";
            $result=$connectionVUS->Execute($sql);
            break;

    case '030501':  //re asignacion de procesos
    case '03020102'://asignacion de procesos
    case '0302A0102'://asignacion de procesos
    case '0302B0102'://asignacion de procesos
        //if ($_POST['op'] == "graba_asignacion"){ //ya no porque le graba_load lo hace todo!!! y saca a pantalla de listado
            if ($_POST['op'] == "distribucion"){ 
                echo "ENTRANDO A DONDE SE DEBE <br>";
                if ($_POST['id']!='030501') {
                    $arr_label[554]='falta_distribucion';
                    $arr_lang = "554";
                    include ('form_language.php');   

                    /*
                                $sql="SELECT ctg_tpt_req_muestra FROM ctg_tipo_tramites WHERE ctg_tpt_id='{$_POST['ctg_tpt_id']}' AND ctg_tpr_id='{$_POST['ctg_tpr_id']}'";
                                $result = $connection->Execute ($sql);
                                if ($result->fields[0] != "") {
                                    if($result->fields[0]=='1'){
                    */                  
                    /*
                                    }else{                    
                                        $reqmue='no';
                                    }
                                }
                    */
                    //esta es la respuesta ajax que se introdujo para aprovechar el codigo 
                    //if ($_POST['op'] == "distribucion"){ //viene de la tabla para validar si tiene distribucion 2012-09-08                        
                        //ob_clean();   //limpiar buffer para respuesta ajax             

                        $sql="SELECT * FROM lab_control_{$_POST['tipo']}  WHERE 
                        lab_con_numsol = '{$_POST['codigo']}' AND 
                        lab_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                        lab_con_tpt_id = '{$_POST['ctg_tpt_id']}'";
                        //echo $sql."<br>";
                        $result = $connection->Execute ($sql);
                        if ($result->fields[0] != "") { 
                            $reqmue='no'; 
                        } else { 
                            $reqmue='si'; 
                        }

                    if($reqmue == 'no') 
                        echo "ok";
                    else
                        echo $arr_label['falta_distribucion'];            
                    die();            

                }
            }
            
            iniciarConexionVUS();
            // UPDATE ESTATUS DE STEPS ASIGNADOS
            $sql="UPDATE \"vus_tramites_{$_POST['tipo']}_ESTATUS\" SET
            \"vus_{$_POST['tipo']}EST_steps\" = '1',
            \"vus_{$_POST['tipo']}EST_evals\" = '1'
            WHERE         
            vus_{$_POST['tipo']}EST_numsol = '{$_POST['codigo']}' AND 
            vus_{$_POST['tipo']}EST_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
            vus_{$_POST['tipo']}EST_tpr_id = '{$_POST['ctg_tpr_id']}' AND
            vus_{$_POST['tipo']}EST_tts_id = '5' ";
            echo $sql."<br>";
            $result=$connectionVUS->Execute($sql);

            // UPDATE ESTATUS DE STEPS ASIGNADOS
            $sql="UPDATE vus_tramites_{$_POST['tipo']}1 SET
            vus_{$_POST['tipo']}_est_id = '8'
            WHERE         
            vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND 
            vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
            vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
            echo $sql."<br>";
            $result=$connectionVUS->Execute($sql);

            //if($reqmue=='no') {
     
                $sql="DELETE FROM adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']}_etapas WHERE adm_coe_numsol = '{$_POST['codigo']}' AND adm_coe_tpr_id = '{$_POST['ctg_tpr_id']}' AND adm_coe_tpt_id = '{$_POST['ctg_tpt_id']}'";
                $result = $connection->Execute ($sql);

                $error = $connection->ErrorMsg();	
                if ($connection->Affected_Rows() > 0)
                    $info = $arr_label['datos_borrados']."(".$connection->Affected_Rows().")";                               
                echo $sql."<br>[".$error."]<br>[".$info."]<br>";    
                //aqui estaba el delte del adm control y el insert del mismo y se traslado a watch_vus_tramites_op.php en elm omento de admitir        
      
                $c = 0;
                $dias = 0;
                $fecha = date("Y-m-d");
                $fecha_ant = $fecha;
                $etapa = "";

				$q = explode(",",$_POST['str_check']);
				$x=count($q);	
				$r=0;
				while($r<$x) {
                    $sql="SELECT * FROM ctg_tipo_tramites_etapas WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND ctg_tte_id='".$q[$r]."' ORDER BY ctg_tte_id";
                    
                    $result = $connection->Execute ($sql);
                    if (! $result->EOF) {
                       //$fecha = date("Y-m-d");
                        while (!$result->EOF) {
                            $operador = $result->fields;
                            $fecha = date("Y-m-d");

                            $inipro_dt = $fecha;
                            $fecha = suma_fechas($fecha,$operador['ctg_tte_duracion']);
                            $c++;
                            $finpro_dt = $fecha;
                            $status = "0"; 
                            list($usr_tec) = explode(",",$operador["ctg_tte_usrs"]);                                    
                            if (empty($usr_tec)) $usr_tec = "''"; 
                            if ($c == 1)  {
                                //$usr_tec = "'".$_SESSION['ADMusuario_id']."'"; 
                            	//$inipro_dt = date("Y-m-d H:i:s"); $finpro_dt = date("Y-m-d H:i:s"); $status = "4";  $etapa = $operador['ctg_tte_id']; 
                          	}
                            $dias += $operador['ctg_tte_duracion'];
                            $sql1="INSERT INTO adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']}_etapas (        
                            adm_coe_numsol, 	
                            adm_coe_tpt_id, 	
                            adm_coe_tpr_id, 	
                            adm_coe_tpe_id, 	
                            adm_coe_tpe_orden, 	
                            adm_coe_esa_id, 	
                            adm_coe_tec_id, 	
                            adm_coe_inipro_dt, 	
                            adm_coe_dura, 	
                            adm_coe_finpro,	
                            adm_coe_inicio, 	
                            adm_coe_fin, 	
                            adm_coe_bol,
                            adm_coe_bolespres, 	
                            adm_coe_bolresdt, 	
                            adm_coe_res_dt, 	
                            adm_coe_status, 	
                            adm_coe_obs, 	
                            adm_coe_docgen, 	
                            adm_coe_docgen_ubi, 	
                            adm_coe_sta, 	
                            adm_coe_usr, 	
                            adm_coe_dt 	
                            ) VALUES (    
                            '{$_POST['codigo']}',
                            '{$_POST['ctg_tpt_id']}',                   
                            '{$_POST['ctg_tpr_id']}',
                            '".$operador['ctg_tte_id']."',
                            '$c',
                            '01{$_POST['ctg_tpr_id']}',
                            '',
                            '".$fecha_ant."',
                            '".intval($operador['ctg_tte_duracion'])."',
                            '".$fecha."',
                            '".$fecha_ant."',			
                            '".$fecha."',
                            '0',
                            '0',
                            '1900-01-01',
                            '1900-01-01',
                            '$status',
                            '".$_POST['res_obs']."',
                            '',
                            '',
                            '1',
                            '".$_SESSION['ADMusuario_id']."',
                            now()
                            );";     
                            $result1=$connection->Execute($sql1);
                            $error = $connection->ErrorMsg();	
                            if ($connection->Affected_Rows() == 1)
                                $info = $arr_label['datos_grabados'];
                                echo $sql1."<br>[".$error."]<br>[".$info."]<br>";                   
                            
                            $fecha_ant = $fecha;
                            //$fecha=$fecha_ant;
                            $result->MoveNext();
							if ($r == 0) {
							}	
				
                        }
                    }
					$r++;
                }
                //// add 05,06,07,08,09
                // $c = 0;
                // $dias = 0;
                // $fecha = date("Y-m-d");
                // $fecha_ant = $fecha;
                $etapa = "";

                $sql="SELECT * FROM ctg_tipo_tramites_etapas WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND ctg_tte_id>='05' ORDER BY ctg_tte_id";
                echo $sql."<br>";
                
                $result = $connection->Execute ($sql);
                if (! $result->EOF) {
                    //$fecha = date("Y-m-d");
                    while (!$result->EOF) {
                        $operador = $result->fields;
                        $inipro_dt = $fecha;
                        $fecha = suma_fechas($fecha,$operador['ctg_tte_duracion']);
                        $c++;
                        $finpro_dt = $fecha;
                        $status = "0"; 
                        list($usr_tec) = explode(",",$operador["ctg_tte_usrs"]);                                    
                        if (empty($usr_tec)) $usr_tec = "''"; 
                        if ($c == 1)  {
                            //$usr_tec = "'".$_SESSION['ADMusuario_id']."'"; 
                            //$inipro_dt = date("Y-m-d H:i:s"); $finpro_dt = date("Y-m-d H:i:s"); $status = "4";  $etapa = $operador['ctg_tte_id']; 
                        }
                        $dias += $operador['ctg_tte_duracion'];
                        $sql1="INSERT INTO adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']}_etapas (        
                        adm_coe_numsol, 	
                        adm_coe_tpt_id, 	
                        adm_coe_tpr_id, 	
                        adm_coe_tpe_id, 	
                        adm_coe_tpe_orden, 	
                        adm_coe_esa_id, 	
                        adm_coe_tec_id, 	
                        adm_coe_inipro_dt, 	
                        adm_coe_dura, 	
                        adm_coe_finpro,	
                        adm_coe_inicio, 	
                        adm_coe_fin, 	
                        adm_coe_bol,
                        adm_coe_bolespres, 	
                        adm_coe_bolresdt, 	
                        adm_coe_res_dt, 	
                        adm_coe_status, 	
                        adm_coe_obs, 	
                        adm_coe_docgen, 	
                        adm_coe_docgen_ubi, 	
                        adm_coe_sta, 	
                        adm_coe_usr, 	
                        adm_coe_dt 	
                        ) VALUES (    
                        '{$_POST['codigo']}',
                        '{$_POST['ctg_tpt_id']}',                   
                        '{$_POST['ctg_tpr_id']}',
                        '".$operador['ctg_tte_id']."',
                        '$c',
                        '01{$_POST['ctg_tpr_id']}',
                        'MASTER',
                        '".$fecha_ant."',
                        '".intval($operador['ctg_tte_duracion'])."',
                        '".$fecha."',
                        '".$fecha_ant."',			
                        '".$fecha."',
                        '0',
                        '0',
                        '1900-01-01',
                        '1900-01-01',
                        '$status',
                        '".$_POST['res_obs']."',
                        '',
                        '',
                        '1',
                        '".$_SESSION['ADMusuario_id']."',
                        now()
                        );";     
                        $result1=$connection->Execute($sql1);
                        $error = $connection->ErrorMsg();	
                        if ($connection->Affected_Rows() == 1)
                            $info = $arr_label['datos_grabados'];
                            echo $sql1."<br>[".$error."]<br>[".$info."]<br>";                   
                        
                        $fecha_ant = $fecha;
                        //$fecha=$fecha_ant;
                        $result->MoveNext();
                        if ($r == 0) {
                        }	
            
                    }
                }
                /////
                echo "error ({$error})<br>";
                if ($error == "") {
	
					$sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
					vus_{$_POST['tipo']}_etasig = '1',
                    vus_{$_POST['tipo']}_est_id = '8',
					vus_{$_POST['tipo']}_sta = '2', 
					vus_{$_POST['tipo']}_usr = '{$_SESSION['ADMusuario_id']}', 
					vus_{$_POST['tipo']}_dt =now()			
					WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
					echo $sql."<br>";
					$result=$connectionVUS->Execute($sql);
							
                    //aca finaliza la etapa inicial 01 automaticamente al asignar las etapas
                    $sql="UPDATE adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']} SET
                    adm_con_dura = '$dias',
                    adm_con_final_espe = '$fecha',
                    adm_con_estatus = '0',
                    adm_con_etapa = '$etapa',
                    adm_con_obs = '".$_POST['res_obs']."',                                
                    adm_con_dt = now()                                
                    WHERE adm_con_numsol = '{$_POST['codigo']}' AND adm_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                    adm_con_tpt_id = '{$_POST['ctg_tpt_id']}'";// AND ctg_esa_id = '".$_POST['ctg_esa_id']."'";
                    $result = $connection->Execute ( $sql );
                                
                    $error = $connection->ErrorMsg();	
                    if ($connection->Affected_Rows() == 1)
                        $info = $arr_label['datos_grabados'];
                       
                    echo $sql."<br>[".$error."]<br>[".$info."]<br>";                 
                     
                    
                    if ($error == "") {   
                        
                        iniciarConexionVUS();
                        $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}_ESTATUS\" (
                            \"vus_{$_POST['tipo']}EST_numsol\",
                            \"vus_{$_POST['tipo']}EST_tpt_id\", 
                            \"vus_{$_POST['tipo']}EST_tpr_id\", 
                            \"vus_{$_POST['tipo']}EST_tts_id\", 							
                            \"vus_{$_POST['tipo']}EST_estatus_dt\", 
                            \"vus_{$_POST['tipo']}EST_obs\", 

                            \"vus_{$_POST['tipo']}EST_usr_id\", 
                            \"vus_{$_POST['tipo']}EST_sta\",
                            \"vus_{$_POST['tipo']}EST_usr\",
                            \"vus_{$_POST['tipo']}EST_dt\"
                            ) VALUES (
                            '{$_POST['codigo']}',
                            '{$_POST['ctg_tpt_id']}',
                            '{$_POST['ctg_tpr_id']}',
                            '8',
                            now(),
                            '".$_POST['res_obs']."',

                            '".$_SESSION['ADMusuario_id']."',
                            '1',
                            '".$_SESSION['ADMusuario_id']."',
                            now());";            

                            $result=$connectionVUS->Execute($sql);
                    }  
                }   
                
                                                                              
            //} else $info = $arr_label['falta_distribucion'];
                    
                    
            break;  


    case '030701'://re asignacion de procesos
    case '03010102'://asignacion de procesos company licences

                $sqldel="DELETE FROM adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']}_etapas WHERE adm_coe_numsol = '{$_POST['codigo']}' AND adm_coe_tpr_id = '{$_POST['ctg_tpr_id']}' AND adm_coe_tpt_id = '{$_POST['ctg_tpt_id']}'";
                echo $sqldel;
                $result = $connection->Execute ($sqldel);
                $error = $connection->ErrorMsg();   
                if ($connection->Affected_Rows() > 0)
                    $info = $arr_label['datos_borrados']."(".$connection->Affected_Rows().")";                               
                echo $sqldel."<br>[".$error."]<br>[".$info."]<br>";    
                //aqui estaba el delte del adm control y el insert del mismo y se traslado a watch_vus_tramites_op.php en elm omento de admitir        
      
                $c = 0;
                $dias = 0;
                $fecha = date("Y-m-d");
                $fecha_ant = $fecha;
                $etapa = "";

                $q = explode(",",$_POST['str_check']);
                $x=count($q);   
                $r=0;
                while($r<$x) {
                    $sql="SELECT * FROM ctg_tipo_tramites_etapas WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND ctg_tte_id='".$q[$r]."' ORDER BY ctg_tte_id";
                    
                    $result = $connection->Execute ($sql);
                    if (! $result->EOF) {
                       //$fecha = date("Y-m-d");
                        while (!$result->EOF) {
                            $operador = $result->fields;
                            $inipro_dt = $fecha;
                            $fecha = suma_fechas($fecha,$operador['ctg_tte_duracion']);
                            $c++;
                            $finpro_dt = $fecha;
                            $status = "0"; 
                            list($usr_tec) = explode(",",$operador["ctg_tte_usrs"]);                                    
                            if (empty($usr_tec)) $usr_tec = "''"; 
                            
                            if ($c == 1)  {
                                //$usr_tec = "'".$_SESSION['ADMusuario_id']."'"; 
                                //$inipro_dt = date("Y-m-d H:i:s"); $finpro_dt = date("Y-m-d H:i:s"); $status = "4";  $etapa = $operador['ctg_tte_id']; 
                            }
                            $dias += $operador['ctg_tte_duracion'];
                            $sql1="INSERT INTO adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']}_etapas (        
                            adm_coe_numsol,     
                            adm_coe_tpt_id,     
                            adm_coe_tpr_id,     
                            adm_coe_tpe_id,     
                            adm_coe_tpe_orden,  
                            adm_coe_esa_id,     
                            adm_coe_tec_id,     
                            adm_coe_inipro_dt,  
                            adm_coe_dura,   
                            adm_coe_finpro, 
                            adm_coe_inicio,     
                            adm_coe_fin,    
                            adm_coe_bol,    
                            adm_coe_bolespres,  
                            adm_coe_bolresdt,   
                            adm_coe_res_dt,     
                            adm_coe_status,     
                            adm_coe_obs,    
                            adm_coe_docgen,     
                            adm_coe_docgen_ubi,     
                            adm_coe_sta,    
                            adm_coe_usr,    
                            adm_coe_dt  
                            ) VALUES (    
                            '{$_POST['codigo']}',
                            '{$_POST['ctg_tpt_id']}',                   
                            '{$_POST['ctg_tpr_id']}',
                            '".$operador['ctg_tte_id']."',
                            '$c',
                            '01{$_POST['ctg_tpr_id']}',
                            $usr_tec,
                            '".$fecha_ant."',
                            '".intval($operador['ctg_tte_duracion'])."',
                            '".$fecha."',
                            '".$fecha_ant."',           
                            '".$fecha."',
                            '0',
                            '0',
                            '1900-01-01',
                            '1900-01-01',
                            '$status',
                            '".$_POST['res_obs']."',
                            '',
                            '',
                            '1',
                            '".$_SESSION['ADMusuario_id']."',
                            now());";     
                            $result1=$connection->Execute($sql1);
                            $error = $connection->ErrorMsg();   
                            if ($connection->Affected_Rows() == 1)
                                $info = $arr_label['datos_grabados'];
                                echo $sql1."<br>[".$error."]<br>[".$info."]<br>";                   
                            
                            $fecha_ant = $fecha;
                            //$fecha=$fecha_ant;
                            $result->MoveNext();
                            if ($r == 0) {
                            }   
                
                        }
                    }
                    $r++;
                }

                if ($error == "") {
                    $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
                    vus_{$_POST['tipo']}_etasig = '1',
                    vus_{$_POST['tipo']}_sta = '2', 
                    vus_{$_POST['tipo']}_usr = '{$_SESSION['ADMusuario_id']}', 
                    vus_{$_POST['tipo']}_dt =now()          
                    WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                    echo $sql."<br>";
                    $result=$connectionVUS->Execute($sql);
                            
                    //aca finaliza la etapa inicial 01 automaticamente al asignar las etapas
                    $sql="UPDATE adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']} SET
                    adm_con_dura = '$dias',
                    adm_con_final_espe = '$fecha',
                    adm_con_estatus = '0',
                    adm_con_etapa = '$etapa',
                    adm_con_obs = '".$_POST['res_obs']."',                                
                    adm_con_dt = now()                                
                    WHERE adm_con_numsol = '{$_POST['codigo']}' AND adm_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                    adm_con_tpt_id = '{$_POST['ctg_tpt_id']}'";// AND ctg_esa_id = '".$_POST['ctg_esa_id']."'";
                    $result = $connection->Execute ( $sql );
                                
                    $error = $connection->ErrorMsg();   
                    if ($connection->Affected_Rows() == 1)
                        $info = $arr_label['datos_grabados'];
                       
                    echo $sql."<br>[".$error."]<br>[".$info."]<br>";                 
                     
                    
                    if ($error == "") {   
                        
                        iniciarConexionVUS();

                        $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}_ESTATUS\" (
                        \"vus_{$_POST['tipo']}EST_numsol\",
                        \"vus_{$_POST['tipo']}EST_tpt_id\", 
                        \"vus_{$_POST['tipo']}EST_tpr_id\", 
                        \"vus_{$_POST['tipo']}EST_tts_id\",                             
                        \"vus_{$_POST['tipo']}EST_estatus_dt\", 
                        \"vus_{$_POST['tipo']}EST_obs\", 

                        \"vus_{$_POST['tipo']}EST_usr_id\", 
                        \"vus_{$_POST['tipo']}EST_sta\",
                        \"vus_{$_POST['tipo']}EST_usr\",
                        \"vus_{$_POST['tipo']}EST_dt\"
                        ) VALUES (
                        '{$_POST['codigo']}',
                        '{$_POST['ctg_tpt_id']}',
                        '{$_POST['ctg_tpr_id']}',
                        '8',
                        now(),
                        '".$_POST['res_obs']."',

                        '".$_SESSION['ADMusuario_id']."',
                        '1',
                        '".$_SESSION['ADMusuario_id']."',
                        now());";            

                        $result=$connectionVUS->Execute($sql);
                    }  
                }   
            break;  

    case '030503':	//re asignacion de procesos
    case '030703':  //re asignacion de procesos
            
            /*
      
            $sql="DELETE FROM adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']}_etapas WHERE adm_coe_numsol = '{$_POST['codigo']}' AND adm_coe_tpr_id = '{$_POST['ctg_tpr_id']}' AND adm_coe_tpt_id = '{$_POST['ctg_tpt_id']}'";
            $result = $connection->Execute ( $sql );

            $error = $connection->ErrorMsg();	
            if ($connection->Affected_Rows() > 0)
                $info = $arr_label['datos_borrados']."(".$connection->Affected_Rows().")";                               
            echo $sql."<br>[".$error."]<br>[".$info."]<br>";    
            //aqui estaba el delte del adm control y el insert del mismo y se traslado a watch_vus_tramites_op.php en elm omento de admitir        
  
            $c = 0;
            $dias = 0;
            $fecha = date("Y-m-d H:i:s");
            $fecha_ant = $fecha;
            $etapa = "";
            */

            echo "<pre>";
            //print_r($_POST);
            echo "</pre>";

			$q = explode(",",$_POST['str_check']);
			$x=count($q);	
			$r=0;
			while($r<$x) {
	      
	            $sql="UPDATE adm_control_{$_POST['tipo']}_etapas SET 
	            adm_coe_status = 5,
	            adm_coe_sta	= '2',
	            adm_coe_usr	= '".$_SESSION['ADMusuario_id']."',                        
	            adm_coe_dt = now()
	            WHERE 
	            	adm_coe_numsol = '{$_POST['codigo']}' AND 
	            	adm_coe_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
	            	adm_coe_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
	            	adm_coe_tpe_id = '".$q[$r]."'"; 
	            $result = $connection->Execute ( $sql );
                $error = $connection->ErrorMsg();	
	            echo "Affected=".$connection->Affected_Rows()."<br>";
	            //if ($connection->Affected_Rows() > 0)
	                //$info = $arr_label['datos_borrados']."(".$connection->Affected_Rows().")";                               
				$r++;
            }
            
            if (empty($error))
	            $info = $arr_label['datos_grabados'];

            break;  

    
    case '010109'://asignacion de procesos
    case '010209'://asignacion de procesos company licences
    case '010409'://asignacion de procesos company licences
            
            iniciarConexionVUS();
			$sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
			vus_{$_POST['tipo']}_est_id = '".$_POST['tts_id']."',
			vus_{$_POST['tipo']}_sta = '2', 
			vus_{$_POST['tipo']}_usr = '".$_SESSION['ADMusuario_id']."', 
			vus_{$_POST['tipo']}_dt =now()			
			WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
			
			$result=$connectionVUS->Execute($sql);
			$error =$connectionVUS->ErrorMsg();	
			if ($connectionVUS->Affected_Rows() == 1) $info = $arr_label['datos_grabados'];    

			echo $sql."<br>[".$error."]<br>[".$info."]<br>";    
		
			$arr_label[368]='se_cambio_status';
			$arr_label[574]='estatus_actual';
			$arr_label[1008]='estatus_ant';

			$arr_label[10]='tipo_producto';
			$arr_label[54]='tipo_tramite';
			$arr_label[317]='tramite_no';
			$arr_label[84]='nombre_producto';
			$arr_label[14]='comentarios';

            $arr_lang = "368,574,1008,10,54,317,84,14";
            include ('form_language.php');   
		
            $comments = ""; 
	
	        if (!empty($_POST['res_obs'])) 
                $comments .= "<u><br>".$arr_label['comentarios']."</u><br><br>".nl2br($_POST['res_obs'])."<br><br>"; 
            
             
			//$comments .= "<u>".$arr_label['se_cambio_status']."</u><br>".$arr_label['estatus_actual']." \"".$_POST['tts_desc_actual']."\" <br>".
			//$arr_label['estatus_ant']." \"".$_POST['tts_desc_ant']."\"<br>";
			/*
            $body = "<u>".$arr_label['informacion_tramite']."</u><br>".$arr_label['estimado']." ".$_POST['nombre'].":<br>";
            $body .= "<table><tr><td colspan=2><u>".$arr_label['informacion_general']."</u>";
            $body .= "<tr><td>".$arr_label['tipo_producto']."  :<td>".$_POST['ctg_tpr_desc']." (".$_POST['titulo_anterior'].")";
            $body .= "<tr><td>".$arr_label['tipo_tramite']."   :<td>".$_POST['ctg_tpt_desc'];
            */

            $body = "Laos.";
            /*
            $body = $arr_label['tramite_no']." : ".$_POST['codigo']."<br>";
            $body .= $arr_label['nombre_producto']." : ".$_POST['nomprod']."<br>";
            //$body .= "<br><br>".$fisico.$muestras.$texto."<br>".$comments."<br><br>"; //.$tabla_faltantes;
            $body .= "<br><br>".$soporte."<br>";  */

            $subject = $arr_label['se_cambio_status']." ".$arr_label['tramite_no']." ".$_POST['codigo']; 
            $headers = "From: $soporte <$company_email3>\nReply-To: $soporte  <$company_email3>\nContent-Type: text/html; charset=UTF-8";        

            /* en linea 2466 se envia el email, ya no es necesario aca, solo arma el body
            $content = email_tpl($_POST['titulo_anterior'], $body,"../");  //2013-08-07                                                  

	        $send = mail($_POST['email'], $subject, $content, $headers);
            
            insert_email($_POST['tipo'],$_POST['codigo'],$_POST['ctg_tpt_id'],$_POST['ctg_tpr_id'],$_POST['nomprod'],$_POST['email'],$subject,$body,$send,$_POST['id']);
            if ($send) 
                $info .= "<br>".$arr_label['envio_correo']." ".$_POST['email']." ".$arr_label['satisfactorio']; 
		    else 
		        $info .= "<br>".$arr_label['no_envio_correo']." ".$_POST['email']; 
            */
        break;
    default:
    iniciarConexionVUS();

    $_POST['catalogo_prefijo1'] = $_POST['catalogo_prefijo'];

	if (strpos("***".$_POST['tabla'],"adm"))     	
    	$_POST['catalogo_prefijo'] = $_POST['catalogo_prefijo'];
	else
		$_POST['catalogo_prefijo'] = $_POST['catalogo_prefijo'].$_POST['tipo']."_";

    echo "<br>tabla=(".$_POST['tabla'].")catalogo_prefijo=(".$_POST['catalogo_prefijo'].")</br>";//2012-11-29

    echo "[".$_POST['id']."][".$_POST['vus_est_id']."]";

    echo "res_st ".$_POST['res_st'];
    $est_id = $_POST['vus_est_id'];


    switch($_POST['id']){
    //case '010101':$campo=10;        $est_id_new = 1;break;  //verificacion     escribe 2 al estatus
    //case '010102':$campo=1;         $est_id_new = 2;break;  //verificacion      escribe 2 al estatus
    // company licences
    case '010201':$campo=10;        $est_id_new = 1;break;  //verificacion     escribe 2 al estatus
    case '010202':$campo=1;         $est_id_new = 2;break;  //verificacion      escribe 2 al estatus
    // qc lab
    case '010401':$campo=10;        $est_id_new = 1;break;  //verificacion     escribe 2 al estatus
    case '010101':
        $campo=10;
        if (intval($_POST['res_st']) == 3)
            $est_id_new = 7;
        else
            if (intval($_POST['res_st']) == 1)
                 $est_id_new = 5;
            else
                 $est_id_new = 1;
        break;  //pre chequeo                   

    case '010102': 
        $campo = 1;
        if (intval($_POST['res_st']) == 3)
            $est_id_new = 7;
        else
            if (intval($_POST['res_st']) == 1)
                 $est_id_new = 5;
            else
                 $est_id_new = 1;
        break;  //pre chequeo                   

    case '010103':
    case '010203':
        $campo=3;
		if (intval($_POST['res_st']) == 3)
			$est_id_new = 7;
		else
            if (intval($_POST['res_st']) == 1)
			     $est_id_new = 5;
            else
                 $est_id_new = 1;
		break;  //pre chequeo                   
    case '010402':
        $est_id_new = 1;
        $campo=2;
        if (intval($_POST['res_st']) == 2)
            $est_id_new = 7;
        else
            if (intval($_POST['res_st']) == 1)
                $est_id_new = 2;
        break;  //pre chequeo
 
     case '010403':
        $campo=3;
        $est_id_new = 2;
        if (intval($_POST['res_st']) == 2)
            $est_id_new = 7;
        else
            if (intval($_POST['res_st']) == 1)
                 $est_id_new = 5;
       break;  //pre chequeo                   

    case '010411':
        $est_id_new = 5;
        $campo=3;
        if (intval($_POST['res_st']) == 2 )
            $est_id_new = 7;
        else
            if (intval($_POST['res_st']) == 1)
                $est_id_new = 5;
        break;  //pre chequeo

    case '010104':                  $est_id_new = 6;break;  //recepcion expediente fisico
    case '010111':                  $est_id_new = 6;break;  //recepcion muestras para analisis 
    case '010110':$campo=3;         $est_id_new = 5;break;  //recepcion expediente fisico
    case '010105':$campo=3;         $est_id_new = 5;break;  //chequeo genera numero de admision
    case '010106':
    // company licences
    case '010204':                  $est_id_new = 6;break;  //recepcion expediente fisico
    case '010205':$campo=3;         $est_id_new = 5;break;  //chequeo genera numero de admision
    case '010206':                  $est_id_new = 10;break;  //recepcion muestras para analisis 
    // qc lab
    case '010404':                  $est_id_new = 6;break;  //recepcion expediente fisico
    case '010405':$campo=3;         $est_id_new = 5;break;  //chequeo genera numero de admision
    case '010406':                  $est_id_new = 10;break;  //recepcion muestras para analisis 
    case '010410':                  $est_id_new = 6;break;  //recepcion muestras para analisis 
//      case '010107':          $est_id_new = 8;break;  //envio de resultados FINAL AUN NO PROGRAMADO
    case '030509':                  $est_id_new = 7;break;  //rechazo
//      case '010109':          $est_id_new = 7;break;  //cambio de estatus para supervisor AUN NO PROGRAMADO
    case '030709':                  $est_id_new = 7;break;  //rechazo
    }

    $etapa_inf = $campo;

    switch($_POST['id']){
    //company licensing
    case '030102'://Evaluacion
    case '030103'://Asesoria
    case '030104'://Calidad
    case '030105'://Coordinacion II
    case '030106'://Junta revisoria
    case '030107'://comision tecnica
    case '030108'://Resultado final  puede que tambien entre aca
    case '030109'://Coordinacion III  puede que tambien entre aca
    // drugs
    case '030202'://Evaluacion
    case '030203'://Asesoria
    case '030204'://Calidad
    case '030205'://Coordinacion II
    case '030206'://Junta revisoria
    case '030207'://comision tecnica
    case '030208'://Resultado final  puede que tambien entre aca
    case '030209'://Coordinacion III  puede que tambien entre aca
            $etapa_inf = substr($_POST['id'],4,2);   
                echo "etapa inf ({$etapa_inf})";
            $ventanilla = 0;
            echo "000000000000000000";
			$campo = intval(substr($_POST['id'],5,1)) + 2;

            break; //este viend de form_adm_control_etapa_evaluacion.php

    case '0302A02'://Evaluacion
    case '0302A03'://Asesoria
    case '0302A04'://Calidad
    case '0302A05'://Coordinacion II
    case '0302A06'://Junta revisoria
    case '0302A07'://comision tecnica
    case '0302A08'://Resultado final  puede que tambien entre aca
    case '0302A09'://Coordinacion III  puede que tambien entre aca
            $etapa_inf = substr($_POST['id'],5,2);   
            $ventanilla = 0;
            echo "000000000000000000";
            $campo = intval(substr($_POST['id'],6,1)) + 2;

            break; //este viend de form_adm_control_etapa_evaluacion.php

    case '0302B02'://Evaluacion
    case '0302B03'://Asesoria
    case '0302B04'://Calidad
    case '0302B05'://Coordinacion II
    case '0302B06'://Junta revisoria
    case '0302B07'://comision tecnica
    case '0302B08'://Resultado final  puede que tambien entre aca
    case '0302B09'://Coordinacion III  puede que tambien entre aca
            $etapa_inf = substr($_POST['id'],5,2);   
            $ventanilla = 0;
            echo "000000000000000000";
            $campo = intval(substr($_POST['id'],6,1)) + 2;

            break; //este viend de form_adm_control_etapa_evaluacion.php

    case '0301041':
    case '0302041':
    case '0302A041':
    case '0302B041'://Calidad
            $etapa_inf = '10';   
            $ventanilla = 0;
            echo "000000000000000000";
			$campo = 10;
            break; //este viend de form_adm_control_etapa_evaluacion.php
    case '03020501':
    case '03020502':
            $etapa_inf = '8';   
            $ventanilla = 0;
            echo "000000000000000000";
            $campo = 10;
            break; //este viend de form_adm_control_etapa_evaluacion.php
            
    default :/*
            //OBTENER LEYENDAS DE ESTATUS ANTERIOR Y ACTUAL     esto se movio hata abajo justo antes de mandar el email	
          	$i=0;
            $sql="SELECT ctg_tts_id,ctg_tts_desc FROM ctg_tipo_tramites_estatus WHERE ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND  ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND (ctg_tts_id In ('".$est_id."','".$est_id_new."'))";
            //echo $sql."<br>";
            $result = $connection->Execute ($sql);
            if (! $result->EOF) {
                while (!$result->EOF) {
                     $i++;
                     $des[$i] = $result->fields[1];
                     $result->MoveNext();
                }
            }
            
            $dias_proc = 0;
            //OBTENER FECHA DE ESTATUS ANTERIOR
            $sql="SELECT * FROM \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}"_ESTATUS\" WHERE 
            \"vus_{$_POST['tipo']}EST_numsol\" = '{$_POST['codigo']}' AND 
            \"vus_{$_POST['tipo']}EST_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
            \"vus_{$_POST['tipo']}EST_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
            \"vus_{$_POST['tipo']}EST_tts_id\" = '".$est_id."'"; 
            echo $sql."<br>";
            $result = $connectionVUS->Execute ($sql);
            if (! $result->EOF) {
                $operador = $result->fields;
                list($fecha,$hora) = explode(" ",$operador["vus_{$_POST['tipo']}EST_estatus_dt"]);
        //        echo $operador["vus_{$_POST['tipo']}EST_estatus_dt"]."*".$fecha."***";
                $dias_proc = resta_fechas($fecha,date("d-m-Y"));
            }
                    

            $subject = $company." ".$arr_label['no'].". {$_POST['codigo']} ".$des[2]; 
                  

            $comments = "<u>".$arr_label['se_cambio_status']."</u><br>".
            $arr_label['estatus_actual']." \"".$des[1]."\" ".fecha_usr($fecha)."<br>".
            $arr_label['estatus_anterior']." \"".$des[2]."\"<br>".
            $arr_label['dias_proceso']." ".$dias_proc;
            */
            break;
    }
    
    switch($_POST['id']){            
    case '010101':    //recepcion muestras para analisis
    case '010102':    //recepcion muestras para analisis
    case '010103':    //recepcion muestras para analisis
    case '010203':    //recepcion muestras para analisis
    case '010403':    //recepcion muestras para analisis
    case '010104':    //recepcion muestras
    case '010110':    //habilita documentos por problemas de impresion
    case '010107':    //envio de resultados FINAL
    // company licences
    case '010204':    //recepcion expediente fisico
    case '010207':    //envio de resultados FINAL
    // qc lab
    case '010401'://verificacion
    case '010402'://verificacion
    case '010403'://pre chequeo
    case '010405'://chequeo admision
    case '010407':    //envio de resultados FINAL

    case '030509':    //rechazo
    case '030709':    //rechazo
    case '010101'://verificacion
    case '010102'://verificacion
    case '010103'://pre chequeo
    case '010105'://chequeo admision
    // company licences    
    case '010201'://verificacion
    case '010202'://verificacion
    case '010203'://pre chequeo
    case '010205'://chequeo admision
    //
    case '030102'://Evaluacion
    case '030103'://Asesoria
    case '030104'://Calidad
    case '0301041'://Calidad
    case '030105'://Coordinacion II
    case '030106'://Junta revisoria
    case '030107'://comision tecnica    
    // drugs
    case '030202'://Evaluacion
    case '030203'://Asesoria
    case '030204'://Calidad
    case '0302041'://Calidad
    case '030205'://Coordinacion II
    case '030206'://Junta revisoria
    case '03020701'://comision tecnica    
    case '03020702'://comision tecnica    
    case '03020703'://comision tecnica    

    case '0302A02'://Evaluacion
    case '0302A03'://Asesoria
    case '0302A04'://Calidad
    case '0302A041'://Calidad
    case '0302A05'://Coordinacion II
    case '0302A06'://Junta revisoria
    case '0302A0701'://comision tecnica    
    case '0302A0702'://comision tecnica    

    case '0302B02'://Evaluacion
    case '0302B03'://Asesoria
    case '0302B04'://Calidad
    case '0302B041'://Calidad
    case '0302B05'://Coordinacion II
    case '0302B06'://Junta revisoria
    case '0302B0701'://comision tecnica    
    case '0302B0702'://comision tecnica    


        if ($_POST['id']=="010104"){
            if ($_POST['res_st']=='1'){
                $faltante_str .= $_POST['catalogo_prefijo']."samrec = '1', ";
                $faltante_str .= $_POST['catalogo_prefijo']."samrec_dt = now(), ";    
                echo "faltante str (".$faltante_str.")";    
                $est_id_new = 6;
                $hay_rechazo = 0;
            } else {
                $est_id_new = 7;
                $hay_rechazo = 1;

                $input_dt=fecha_srv($_POST['input_dt']);
                $faltante_str .= $_POST['catalogo_prefijo']."samrec = '2', ";
                $faltante_str .= $_POST['catalogo_prefijo']."samrec_dt = now(), ";                
                echo "faltante str (".$faltante_str.")";

                $sql="UPDATE vus_tramites_{$_POST['tipo']}2 SET
                $faltante_str
                vus_{$_POST['tipo']}_est_id ='10',
                vus_{$_POST['tipo']}_est_dt = now(),
                vus_{$_POST['tipo']}_sta ='2',
                vus_{$_POST['tipo']}_usr ='".$_SESSION['ADMusuario_id']."',
                vus_{$_POST['tipo']}_dt =now()
                WHERE         
                vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND 
                vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
                vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}' ";
                // echo "<br>".$sql;
                $result=$connectionVUS->Execute($sql);

                //aca finaliza la etapa inicial 01 automaticamente al asignar las etapas
                $sql="UPDATE adm_control_{$_POST['tipo']}1 SET
                adm_con_rf_status = '3',
                adm_con_rf_dt = now(),
                adm_con_rf_usr = '".$_SESSION['ADMusuario_id']."',
                adm_con_rf_obs = '".$_POST['obs']."',                                
                adm_con_prnlst = '1'
                WHERE adm_con_numsol = '{$_POST['codigo']}' AND adm_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                adm_con_tpt_id = '{$_POST['ctg_tpt_id']}'";
                // echo "<br>".$sql;
                $result = $connection->Execute ( $sql );
                $error = $connection->ErrorMsg();	

                $info = $arr_label['datos_grabados'];                

            }
        }

        $faltante_str = $_POST['catalogo_prefijo']."est_id = '".$est_id_new."', ";

        $cambio_status = true;

        if ( $est_id_new==6 ) {

                if ($_POST['id'] == '010104' || $_POST['id'] == '010204' || $_POST['id'] == '010404'){ //recepcion muestras para analisis               
 
                    $arr_label[653]='ingreso_muestra';
                    $arr_lang = "653";
                    include ('form_language.php');  
                    /*
                    $muestras = "<style>th,td {padding: 0px 4px 0px 4px;}</style>
                    <table border=1 cellspacing=0 cellpadding=0>";
                    */

                    ob_start();
                    include("watch_vus_tramites_muestras.php");			
                    $muestras .= ob_get_contents();
                    ob_end_clean();

                    //$muestras .= "</table>";
        
                    $sql="SELECT * FROM ctg_muestras_archivo WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND ctg_arm_parent = '0'";
                    echo $sql."<br>";
                    $_POST["ctg_arm_id"] = "";
                    $result=$connection->Execute($sql);
                    if (!$result->EOF) {
                            $operador = $result->fields;
                            $_POST["ctg_arm_id"] = $operador['ctg_arm_id'];
                    }

                    $sql="INSERT INTO ctg_muestras_inven (                
                    ctg_numsol_id,
                    ctg_tpr_id,
                    ctg_tpt_id,
                    ctg_arm_id,
                    ctg_ari_crea,
                    ctg_ari_desc,
                    ctg_ari_cant_ent,
                    ctg_ari_cant_sal,
                    ctg_ari_cant_saldo,
                    ctg_ari_sta,
                    ctg_ari_usr,
                    ctg_ari_dt 
                    ) VALUES (    
                    '{$_POST['codigo']}',
                    '{$_POST['ctg_tpr_id']}',
                    '{$_POST['ctg_tpt_id']}',                   
                    '".$_POST["ctg_arm_id"]."',
                    now(),
                    '".$_POST['MUE_desc']."',
                    '".$_POST['MUE_cant']."',
                    '0',
                    '".$_POST['MUE_cant']."',
                    '1',
                    '".$_SESSION['ADMusuario_id']."',
                    now());";
					echo $sql;
                    $result=$connection->Execute($sql);
                    $error = $connection->ErrorMsg();	
                    if ($connection->Affected_Rows() == 1)
                        $info = $arr_label['datos_grabados'];                                         
                         
                    echo $sql."<br>[".$error."]<br>[".$info."]<br>";
    
    
                    $sql="SELECT * FROM ctg_muestras_transac WHERE 
                    ctg_numsol_id = '{$_POST['codigo']}' AND 
                    ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND
                    ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND  
                    ctg_arm_id = '".$_POST["ctg_arm_id"]."' AND 
                    ctg_esa_id = '0106{$_POST['ctg_tpr_id']}'";
                    echo $sql."<br>";
                    $_POST['ctg_art_id'] = 0;
                    $result=$connection->Execute($sql);
                    if (!$result->EOF) {
                            $operador = $result->fields;
                            $_POST['ctg_art_id'] = $operador['ctg_art_id'];
                    }
                    $_POST['ctg_art_id']++;
                             
                    $sql="INSERT INTO ctg_muestras_transac (                
                    ctg_numsol_id, 
                    ctg_tpr_id, 	
                    ctg_tpt_id,
                    ctg_arm_id,
                    ctg_esa_id,
                    ctg_art_id,
                    ctg_art_opeusr,
                    ctg_art_opedt,
                    ctg_art_tpoope,
                    ctg_art_motivo,
                    ctg_art_cant_ent,
                    ctg_art_cant_sal,
                    ctg_art_saldo,
                    ctg_art_sta,
                    ctg_art_usr,
                    ctg_art_dt
                    ) VALUES (    
                    '{$_POST['codigo']}',
                    '{$_POST['ctg_tpr_id']}',
                    '{$_POST['ctg_tpt_id']}',                   
                    '".$_POST["ctg_arm_id"]."',
                    '0106{$_POST['ctg_tpr_id']}',
                    '".$_POST['ctg_art_id']."',
                    '".$_SESSION['ADMusuario_id']."',
                    now(),
                    '1',
                    '".$arr_label['ingreso_muestra']."',
                    '".$_POST['MUE_cant']."',
                    '0',
                    '".$_POST['MUE_cant']."',
                    '1',
                    '".$_SESSION['ADMusuario_id']."',
                    now());";          
                    echo $sql;
                    $result=$connection->Execute($sql);
                    $error = $connection->ErrorMsg();	
                    if ($connection->Affected_Rows() == 1)
                        $info = $arr_label['datos_grabados'];    
                        
                    echo $sql."<br>[".$error."]<br>[".$info."]<br>";
                }					                
    	}
        
        ob_start();

        echo "///////////////////////////////////////////////////////////////////////////////////////////////////////<br>";
        echo "///////////////////////////".date("d/m/Y h:i:s")."////////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// numsol = ".$_POST['codigo']."///////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// menu = ".$_POST['id']."///////////////////////////////////////////////////////////////////////////<br>";

        echo "//////////////////////////// est id new = ".$est_id_new."///////////////////////////////////////////////<br>";

        echo "<br>****************************************************  ".$_POST['id']."<br>";
        echo "<br>res_st -----------".$_POST['res_st']."--------<br>";
        echo "<br>dtb_vus -----------(".$_SESSION['dtb_vus'].")--------<br>";

        $_POST['numfal'] = 0;


        /******************************************************* NUEVO ARCHIVO INF ********************************************************************************************/
        $sql="SELECT * FROM \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKinf\" WHERE         
            \"vus_{$_POST['tipo']}CHKi_numsol\" = '{$_POST['codigo']}' AND 
            \"vus_{$_POST['tipo']}CHKi_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
            \"vus_{$_POST['tipo']}CHKi_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
            \"vus_{$_POST['tipo']}CHKi_etapa\" = '".$etapa_inf."'";
        echo $sql."<br>";	

        $result=$connectionVUS->Execute($sql);
        $error = $connectionVUS->ErrorMsg();
        if (!$result->EOF) {
        
                $sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKinf\" SET
                \"vus_{$_POST['tipo']}CHKi_res_st\" = '".intval($_POST['res_st'])."', 
                \"vus_{$_POST['tipo']}CHKi_res_ds\" = '".intval($_POST['res_ds'])."', 
                \"vus_{$_POST['tipo']}CHKi_res_dt\" = now(), 
                \"vus_{$_POST['tipo']}CHKi_res_us\" = '".$_SESSION['ADMusuario_id']."', 
                \"vus_{$_POST['tipo']}CHKi_res_obs\" = '".$_POST['res_obs']."',
                \"vus_{$_POST['tipo']}CHKi_sta\" = '2', 
                \"vus_{$_POST['tipo']}CHKi_usr\" = '".$_SESSION['ADMusuario_id']."', 
                \"vus_{$_POST['tipo']}CHKi_dt\" =now()										
                WHERE         
                \"vus_{$_POST['tipo']}CHKi_numsol\" = '{$_POST['codigo']}' AND 
                \"vus_{$_POST['tipo']}CHKi_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                \"vus_{$_POST['tipo']}CHKi_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
                \"vus_{$_POST['tipo']}CHKi_etapa\" = '".$etapa_inf."'";
                
        } else {

                $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKinf\" (
                \"vus_{$_POST['tipo']}CHKi_numsol\",
                \"vus_{$_POST['tipo']}CHKi_tpt_id\", 
                \"vus_{$_POST['tipo']}CHKi_tpr_id\", 
                \"vus_{$_POST['tipo']}CHKi_etapa\", 
                \"vus_{$_POST['tipo']}CHKi_res_st\", 
                \"vus_{$_POST['tipo']}CHKi_res_ds\", 
                \"vus_{$_POST['tipo']}CHKi_res_dt\", 
                \"vus_{$_POST['tipo']}CHKi_res_us\", 
                \"vus_{$_POST['tipo']}CHKi_res_obs\",
                \"vus_{$_POST['tipo']}CHKi_sta\", 
                \"vus_{$_POST['tipo']}CHKi_usr\", 
                \"vus_{$_POST['tipo']}CHKi_dt\"
                ) VALUES (
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',
                '{$_POST['ctg_tpr_id']}',
                '".$etapa_inf."',
                '".intval($_POST['res_st'])."',
                '".intval($_POST['res_ds'])."',
                now(),
                '".$_SESSION['ADMusuario_id']."',
                '".$_POST['res_obs']."',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";
        }
        echo "VER ESTE ".$sql."<br>";

        $result=$connectionVUS->Execute($sql);
        $error = $connectionVUS->ErrorMsg();	

        if ($connectionVUS->Affected_Rows() == 1){ 
            $info = $arr_label['datos_grabados'];  
            
            echo $sql."<br>[".$error."]<br>[".$info."]<br>";	
            $arr_label[220]='categoria';
            $arr_label[316]='doc_nombre';
            $arr_label[14]='comentarios';
            $arr_label[324]='parte';
            $arr_label[1183]='comentarios_neg';
            $arr_lang = "220, 316, 14, 324, 1183";
            include ('form_language.php');  

            include_once('tabla_docs_html.php');

            if ($ventanilla == 1 && $_POST['id']!='010110') {//todos menos los de evaluacion
                switch (substr($_POST['id'],0,4)) {
                    case '0101':
                    case '0102':

        				if (intval($_POST['res_st']) == 2 ) { //2015-02-16
        		         	echo "entro a actualizar el numfal del vus <br>";
        					$sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
        					vus_{$_POST['tipo']}_numfal = COALESCE(vus_{$_POST['tipo']}_numfal,0) + 1,
        					vus_{$_POST['tipo']}_sta = '2', 
        					vus_{$_POST['tipo']}_usr = '".$_SESSION['ADMusuario_id']."',
        					vus_{$_POST['tipo']}_dt =now()
        					WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
        					echo $sql."<br>";
        					$result=$connectionVUS->Execute($sql);
                            // ACTUALIZO TODOS LOS DOCUMENTOS QUE TIENEN COMENTARIOS PARA QUE PUEDAN SUBIRSE DESDE EL MODULO DE USER
                            echo "ACTUALIZO TODOS LOS DOCUMENTOS QUE TIENEN COMENTARIOS PARA QUE PUEDAN SUBIRSE DESDE EL MODULO DE USER<br>";
                            $sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" SET
                            \"vus_{$_POST['tipo']}CHK_res{$campo}_aut\" = '1'
                            WHERE         
                            \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
                            \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                            \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND
                            \"!empty(vus_{$_POST['tipo']}CHK_res{$campo}_obs)\"
                            ";
                            echo "<br>$sql<br>";
                            $result2=$connectionVUS->Execute($sql);
                        }
    		        
                        $vus_usr_id = 0;
        				$_POST['numfal'] = 0;
        		        
        		        $sql="SELECT vus_{$_POST['tipo']}_numfal, vus_{$_POST['tipo']}_usr_id FROM vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} 
        		        WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
        		        echo $sql."<br>";
                        $result=$connectionVUS->Execute($sql);
                        if (!$result->EOF) {
                                $_POST['numfal'] = $result->fields[0];//2014-08-12
                                $vus_usr_id = $result->fields[1];
                        }
                    
        		        $faltante = $_POST['numfal'];
                        $tabla_faltantes .= "</table>";	
                        $error = trim($error);
                        echo "[$c][".$_POST['num_total']."] faltantes en mensaje=[$faltante]<br>";
                        //if ($c != $_POST['num_total'] || $_POST['res_st'] == "2" || $faltante > $adm_cnf_numfal) {//PASA DE ESTATUS
                        echo "estatus ".$_POST['res_st'];
                        if (intval($_POST['res_st']) == 2) {//PASA DE ESTATUS
                        	echo "entro para ver el rechazo <br>";

                            $hay_rechazo = 1;

                            $cambio_status = false;
                            $faltante_str = $_POST['catalogo_prefijo']."faltante = '1',"; //tiene faltante
                            //$faltante_str = ""; esto era para que no le ponga faltante y me la deje en mi pantalla pruebas	           
                            $tipo_mensaje = 1;

                            //if ($campo == 3 || $faltante >= $adm_cnf_numfal) { 2017-10-28
                            if ($faltante > $adm_cnf_numfal) {
                                $hay_rechazo_faltante = 1;
                                $cambio_status = true;
                                $est_id_new = 7;
                                //$faltante_str = $_POST['catalogo_prefijo']."faltante = '0',".$_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";//quita el faltante
                                $faltante_str = $_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                            }
                            echo "<br>hay rechazo faltante (".$hay_rechazo_faltante.")<br>";
                            if ($c == 0) 
                                $comments = "no tiene ni una sola respuesta de los documentos, avisar si sale este texto 09/12/2014";//creo que esto nunca deberia suceder pero por si acaso
                            else
                                $comments = $tabla_faltantes;
                                
                            if ($c == $_POST['num_total'] && intval($_POST['res_st']) == 2) 
                                $comments = "";
                            
                        }

                        if (intval($_POST['res_st']) == 3) {//rechaza desde 010105 //2018-01-09
                            $hay_rechazo=1;
                            $est_id_new = 7;
                            $cambio_status = true;
                            $faltante_str = $_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                            $tipo_mensaje = 0;	                                                
                            if ($campo == 3) { //2018-01-09		
        						$dtb_vus = 1;
                            }                    
                        } 
                        //if ($c == $_POST['num_total'] && $_POST['res_st'] == "1") {//PASA DE ESTATUS
                        if (intval($_POST['res_st']) == 1) {//PASA DE ESTATUS

                            $cambio_status = true;
                            $faltante_str = $_POST['catalogo_prefijo']."faltante = '0',".$_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";//quita el faltante
                            $tipo_mensaje = 0;	                                                
                            
                            if ($campo == 3) {//    case '010105':$campo=3; $est_id_new = 5;break;  //chequeo genera numero de admision
                            	//PROCESO DE ADMISION PARA ADM Y PARA VUS    						
        						/* se paso hasta abajo cuando ya hizo el update y ejecuto los triggers
        						$connectionADM1 = $connection;
        						$connectionVUS1 = $connectionVUS;
        						$usuario = $_SESSION['ADMusuario_id'];
        						include("admitir_tramite.php");
        						*/
        						$dtb_vus = 1;
                            }                            
                        }
                        break;
                    case  "0104" :
                        switch (intval($_POST['res_st'])) {
                            case 1:
                                $cambio_status = true;
                                $faltante_str = $_POST['catalogo_prefijo']."faltante = '0',".$_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                                $tipo_mensaje = 0;
                                if ($campo == 3)
                                    $dtb_vus = 1;
                                break;
                            case 2:
                                $hay_rechazo=1;
                                $cambio_status = true;
                                $faltante_str = $_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                                $tipo_mensaje = 0;
                                if ($campo == 3) 
                                    $dtb_vus = 1;
                            case 4:
                                $cambio_status = false;
                                $faltante_str = $_POST['catalogo_prefijo']."faltante = '0',".$_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                                $tipo_mensaje = 0;
                                if ($campo == 3)
                                    $dtb_vus = 1;

                                $sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" SET
                                \"vus_{$_POST['tipo']}CHK_res{$campo}_obs\" = '{$new_res_obs}',
                                \"vus_{$_POST['tipo']}CHK_res{$campo}_aut\" = '1',
                                \"vus_{$_POST['tipo']}CHK_sta\" = '2', 
                                \"vus_{$_POST['tipo']}CHK_usr\" = '".$_SESSION['ADMusuario_id']."', 
                                \"vus_{$_POST['tipo']}CHK_dt\" =now()                                       
                                WHERE         
                                \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
                                \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                                \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' ";
                        
                                echo "$sql<br>";
                                $result2=$connectionVUS->Execute($sql);

                        }
                      break;
                }

            } else {
                echo "entro a marcar la solicitud para que puedan editarla <br>";

                $hay_rechazo=1;
                $tipo_mensaje = 1;                
                $dias=30;
                $faltante_str = $_POST['catalogo_prefijo']."faltante = '1',"; //tiene faltante

                echo "ACTUALIZO TODOS LOS DOCUMENTOS  PARA QUE PUEDAN SUBIRSE DESDE EL MODULO DE USER<br>";

                $sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" SET
                \"vus_{$_POST['tipo']}CHK_res{$campo}_aut\" = '1'
                WHERE         
                \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
                \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}'
                ";
                //                \"vus_{$_POST['tipo']}CHK_res{$campo}_obs\" <> "" }'

                echo "<br>$sql<br>";
                $result2=$connectionVUS->Execute($sql);

                $vus_usr_id = 0;                       
                $sql="SELECT vus_{$_POST['tipo']}_numfal, vus_{$_POST['tipo']}_usr_id FROM vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} 
                WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                echo $sql."<br>";
                $result=$connectionVUS->Execute($sql);
                if (!$result->EOF) {
                        $_POST['numfal'] = $result->fields[0];//2014-08-12
                        $vus_usr_id = $result->fields[1];
                }

            }

        }

        /// insert document for unspecified additional documents

        if ( (substr($_POST['id'],0,4)=='0101' || substr($_POST['id'],0,4)=='0102' ) && intval($_POST['res_st'])==2) {

            $sql="SELECT * FROM \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_DOCs\" WHERE         
                \"vus_{$_POST['tipo']}DOC_numsol\" = '{$_POST['codigo']}' AND 
                \"vus_{$_POST['tipo']}DOC_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                \"vus_{$_POST['tipo']}DOC_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
                \"vus_{$_POST['tipo']}DOC_ttc_id\" = 'ADM' AND 
                \"vus_{$_POST['tipo']}DOC_ttd_id\" = 'UADDI' ";
            echo "UADDI 1 ".$sql."<br>";   
            $result=$connectionVUS->Execute($sql);
            if ($result->EOF) {

                $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_DOCs\" (
                \"vus_{$_POST['tipo']}DOC_numsol\",
                \"vus_{$_POST['tipo']}DOC_tpt_id\", 
                \"vus_{$_POST['tipo']}DOC_tpr_id\", 
                \"vus_{$_POST['tipo']}DOC_ttc_id\", 
                \"vus_{$_POST['tipo']}DOC_ttd_id\", 
                \"vus_{$_POST['tipo']}DOC_ttd_part\",

                \"vus_{$_POST['tipo']}DOC_doc_name\",
                \"vus_{$_POST['tipo']}DOC_doc_desc\",
                \"vus_{$_POST['tipo']}DOC_docubi\",

                \"vus_{$_POST['tipo']}DOC_sta\", 
                \"vus_{$_POST['tipo']}DOC_usr\", 
                \"vus_{$_POST['tipo']}DOC_dt\"
                ) VALUES (
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',
                '{$_POST['ctg_tpr_id']}',
                'ADM',
                'UADDI',
                '1',
                'NO DOCUMENT',
                '',
                '',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";
                echo "UADDI 1 ".$sql."<br>";   
                $result=$connectionVUS->Execute($sql);
            } 

            $sql="SELECT * FROM \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" WHERE         
                \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
                \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND 
                \"vus_{$_POST['tipo']}CHK_ttc_id\" = 'ADM' AND 
                \"vus_{$_POST['tipo']}CHK_ttd_id\" = 'UADDI' ";
            echo "UADDI 2 ".$sql."<br>";   
            $result=$connectionVUS->Execute($sql);
            if ($result->EOF) {

                $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" (
                \"vus_{$_POST['tipo']}CHK_numsol\",
                \"vus_{$_POST['tipo']}CHK_tpt_id\", 
                \"vus_{$_POST['tipo']}CHK_tpr_id\", 
                \"vus_{$_POST['tipo']}CHK_tec_id\", 
                \"vus_{$_POST['tipo']}CHK_ttc_id\", 
                \"vus_{$_POST['tipo']}CHK_ttd_id\", 
                \"vus_{$_POST['tipo']}CHK_ttl_part\", 
                \"vus_{$_POST['tipo']}CHK_res3_aut\", 
                \"vus_{$_POST['tipo']}CHK_res3_obs\",
                \"vus_{$_POST['tipo']}CHK_sta\", 
                \"vus_{$_POST['tipo']}CHK_usr\", 
                \"vus_{$_POST['tipo']}CHK_dt\"
                ) VALUES (
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',
                '{$_POST['ctg_tpr_id']}',
                '".$_SESSION['ADMusuario_id']."',
                'ADM',
                'UADDI',
                '1',
                '1',
                '{$_POST['res_obs']}',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";
            } else {
                $sql="UPDATE \"vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']}_CHKl\" SET
                \"vus_{$_POST['tipo']}CHK_res3_aut\" = '1',
                \"vus_{$_POST['tipo']}CHK_res3_obs\" = '{$_POST['res_obs']}'
                WHERE         
                \"vus_{$_POST['tipo']}CHK_numsol\" = '{$_POST['codigo']}' AND 
                \"vus_{$_POST['tipo']}CHK_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                \"vus_{$_POST['tipo']}CHK_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND
                \"vus_{$_POST['tipo']}CHK_ttc_id\" = 'ADM' AND 
                \"vus_{$_POST['tipo']}CHK_ttd_id\" = 'UADDI' AND 
                \"vus_{$_POST['tipo']}CHK_ttl_part\" = '1'

                ";                    
            }
            echo "UADDI 2 ".$sql."<br>";   
            $result=$connectionVUS->Execute($sql);

        }

        //2017-10-22
        if (($_POST['id'] == "010101" || $_POST['id'] == "010102" || $_POST['id'] == "010103" || $_POST['id'] == "010203" || $_POST['id'] == "010403") &&  $est_id_new == 5 ){
            echo "GENERO CODIGO INTERNO <br>";
            $sql="SELECT 
            Extract(month from current_date) as mes, 
            Extract(dow from current_date) as dia,
            cast(to_char(current_timestamp, 'HH24MISS') as integer) as hora,
            cast(to_char(current_timestamp, 'HH24MISS') as integer) + 240870 as hrs,
            'FDD' || 
            chr(cast( Extract(month from current_date) as integer)+ 64) || 
            cast(cast(Extract(dow from current_date) as integer) + 1 as text) || 
            cast(cast(to_char(current_timestamp, 'HH24MISS') as integer) + 240870 as text) as adm_con_codidoc";
            $adm_con_codidoc = "";
            echo $sql."<br>";               
            $result=$connection->Execute($sql);
            if (!$result->EOF) {
                $adm_con_codidoc = $result->fields['adm_con_codidoc'].$_POST['codigo'];
            }
                
            $faltante_str .= $_POST['catalogo_prefijo']."codidoc = '$adm_con_codidoc',";

            if ($_POST['tipo']=="qc"){
                if ($_POST['fectest']==''){
                    $dias=90;
                    $_POST['fectest']=date("Y-m-d", strtotime("$s + $dias days"));
                    $_POST['fectest']=fecha_usr($_POST['fectest']);
                }

                $faltante_str .= $_POST['catalogo_prefijo']."pur_id = '".$_POST['purpose']."',";
                $faltante_str .= $_POST['catalogo_prefijo']."prior = '".$_POST['ace_st']."',";
                $faltante_str .= $_POST['catalogo_prefijo']."test_exp_dt = '".fecha_usr($_POST['fectest'])."',";
                
                if ($_POST['id'] == "010403") 
                    $faltante_str .= $_POST['catalogo_prefijo']."samrec_dt = '".date("Y-m-d")."',";
            }

            file_put_contents("hhh.txt",$sql."\n".$faltante_str);
        }
        break;
    case '010411':    //QCL reiterations

        ob_start();

        echo "///////////////////////////////////////////////////////////////////////////////////////////////////////<br>";
        echo "///////////////////////////".date("d/m/Y h:i:s")."////////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// numsol = ".$_POST['codigo']."///////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// menu = ".$_POST['id']."///////////////////////////////////////////////////////////////////////////<br>";

        echo "<br>****************************************************  ".$_POST['id']."<br>";
        echo "<br>-----------".$_POST['res_st']."--------";
        /******************************************************* NUEVO ARCHIVO INF ********************************************************************************************/
            
        echo $sql."<br>[".$error."]<br>[".$info."]<br>";    
        $arr_label[220]='categoria';
        $arr_label[316]='doc_nombre';
        $arr_label[14]='comentarios';
        $arr_label[324]='parte';
        $arr_label[1183]='comentarios_neg';
        $arr_lang = "220, 316, 14, 324, 1183";
        include ('form_language.php');  
        $cambio_status = false;

        if ($ventanilla == 1) {//todos menos los de evaluacion

            if ( substr($_POST['id'],0,4)=="0104" ) {
                if (intval($_POST['res_st']) == 2 ) {//rechaza para qcl
                    $hay_rechazo=1;
                    $faltante_str = $_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                    $tipo_mensaje = 0;
                    if ($campo == 3) 
                        $dtb_vus = 1;
                }

                if (intval($_POST['res_st']) == 1 ) {//PASA DE ESTATUS
                    $hay_rechazo=0;
                    $faltante_str = $_POST['catalogo_prefijo']."req_mue = '1',".$_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
                    $tipo_mensaje = 0;
                    if ($campo == 3)
                        $dtb_vus = 1;
                }
            }
        }
            $info = $arr_label['datos_grabados'];  

        break;
    case '010106':    //recepcion de fisico
    case '010206':    //recepcion de fisico
    case '010406':{

        echo "///////////////////////////////////////////////////////////////////////////////////////////////////////<br>";
        echo "///////////////////////////".date("d/m/Y h:i:s")."////////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// numsol = ".$_POST['codigo']."///////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// menu = ".$_POST['id']."///////////////////////////////////////////////////////////////////////////<br>";
        echo "//////////////////////////// res st = ".$_POST['res_st']."///////////////////////////////////////////////////////////////////////////<br>";

        echo "//////////////////////////// est id new = ".$est_id_new."///////////////////////////////////////////////<br>";

        echo "<br>****************************************************  ".$_POST['id']."<br>";
        echo "<br>res_st -----------".$_POST['res_st']."--------<br>";
        echo "<br>dtb_vus -----------(".$_SESSION['dtb_vus'].")--------<br>";

        $cambio_status = false;
        echo "VOY A ENTRAR";
        if ( $_POST['res_st']=='1'){
            echo "resultado 1<br>";

            $input_dt=fecha_srv($_POST['input_dt']);
            $faltante_str .= $_POST['catalogo_prefijo']."fisrec = '1', ";
            $faltante_str .= $_POST['catalogo_prefijo']."fisrec_dt = now(), ";                
            echo "faltante str (".$faltante_str.")";

            echo "update ctg_archivo_fisico y transac<br>";

            //echo "cantidad a".$_POST['FIS_cant'];
            if ($_POST['FIS_cant']==''){
                $_POST['FIS_cant']='0';
            }
            if ($_POST['cds_cant']==''){
                $_POST['cds_cant']='0';
            }                
            if ($_POST['cds']==''){
                $_POST['cds']='0';
            }
            //echo "cantidad b".$_POST['FIS_cant'];
            // if ( $_POST['id'] == '010106' || $_POST['id'] == '010206' || $_POST['id'] == '010406')  { //recepcion expediente fisico
    
                $sql="SELECT * FROM ctg_archivo_fisico WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND ctg_arf_parent = '0'";
                echo $sql."<br>";
                $_POST["ctg_arf_id"] = "";
                $result=$connection->Execute($sql);
                if (!$result->EOF) {
                        $operador = $result->fields;
                        $_POST["ctg_arf_id"] = $operador['ctg_arf_id'];
                }
                $sql="INSERT INTO ctg_archivo_inven (
                ctg_numsol_id,
                ctg_tpr_id,
                ctg_tpt_id,
                ctg_arf_id,
                ctg_afi_crea,
                ctg_afi_desc,
                ctg_afi_cant_ent,
                ctg_afi_cant_sal,
                ctg_afi_cant_saldo,                    
                ctg_afi_cds,
                ctg_afi_cds_ent,
                ctg_afi_cds_sal,
                ctg_afi_cds_saldo,
                ctg_afi_sta,
                ctg_afi_usr,
                ctg_afi_dt 
                ) VALUES (    
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpr_id']}',
                '{$_POST['ctg_tpt_id']}',                   
                '".$_POST["ctg_arf_id"]."',
                now(),
                '".$_POST['FIS_desc']."',
                '".$_POST['FIS_cant']."',
                '0',
                '".$_POST['FIS_cant']."',
                '".$_POST['cds']."',
                '".intval($_POST['cds_cant'])."',
                '0',
                '".intval($_POST['cds_cant'])."',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";
                $result=$connection->Execute($sql);
                $error = $connection->ErrorMsg();	
                if ($connection->Affected_Rows() == 1)
                    $info = $arr_label['datos_grabados'];                                         

                echo $sql."<br>[".$error."]<br>[".$info."]<br>";

                $sql="SELECT * FROM ctg_archivo_transac WHERE 
                ctg_numsol_id = '{$_POST['codigo']}' AND 
                ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND
                ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND            
                ctg_arf_id = '".$_POST["ctg_arf_id"]."' AND 
                ctg_esa_id = '0106{$_POST['ctg_tpr_id']}'";
                echo $sql."<br>";
                $_POST['ctg_aft_id'] = 0;
                $result=$connection->Execute($sql);
                if (!$result->EOF) {
                        $operador = $result->fields;
                        $_POST['ctg_aft_id'] = $operador['ctg_aft_id'];
                }
                $_POST['ctg_aft_id']++;

                if ($_POST['cds'] == '1') $motivo = $arr_label['cds']; else $motivo = ""; 
                            
                $sql="INSERT INTO ctg_archivo_transac (                
                ctg_numsol_id, 
                ctg_tpr_id, 	
                ctg_tpt_id,
                ctg_arf_id,
                ctg_esa_id,
                ctg_aft_id,
                ctg_aft_opeusr,
                ctg_aft_opedt,
                ctg_aft_tpoope,
                ctg_aft_motivo,
                ctg_aft_cant_ent,
                ctg_aft_cant_sal,
                ctg_aft_sta,
                ctg_aft_usr,
                ctg_aft_dt
                ) VALUES (    
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpr_id']}',
                '{$_POST['ctg_tpt_id']}',                   
                '".$_POST["ctg_arf_id"]."',
                '0106{$_POST['ctg_tpr_id']}',
                '".$_POST['ctg_aft_id']."',
                '".$_SESSION['ADMusuario_id']."',
                now(),
                '1',
                '".$arr_label['ingreso_fisico']." ".$motivo."',
                '".$_POST['FIS_cant']."',
                '0',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";          

                $result=$connection->Execute($sql);
                $error = $connection->ErrorMsg();	

                if ($_POST['id'] == '010106' || $_POST['id'] == '010206' || $_POST['id'] == '010406'){ //recepcion muestras para analisis               
                    // UPDATE FECHA DE RECEPCION DE DOSSIER FISICO
                    $sql="UPDATE vus_tramites_{$_POST['tipo']}_dates SET
                    vus_{$_POST['tipo']}_dat_dt05 = now()
                    WHERE         
                    vus_{$_POST['tipo']}_dat_numsol = '{$_POST['codigo']}' AND 
                    vus_{$_POST['tipo']}_dat_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
                    vus_{$_POST['tipo']}_dat_tpr_id = '{$_POST['ctg_tpr_id']}' ";
                    $result=$connectionVUS->Execute($sql);

                    // UPDATE ESTATUS DE DOSSIER RECIBIDO
                    $sql="UPDATE \"vus_tramites_{$_POST['tipo']}_ESTATUS\" SET
                    \"vus_{$_POST['tipo']}EST_dosrec\" = '1' 
                    WHERE 
                    \"vus_{$_POST['tipo']}EST_numsol\" = '{$_POST['codigo']}' AND 
                    \"vus_{$_POST['tipo']}EST_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                    \"vus_{$_POST['tipo']}EST_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND
                    \"vus_{$_POST['tipo']}EST_tts_id\" = '5' ";
                    echo "<br>sql ".$sql;
                    $result=$connectionVUS->Execute($sql);

                }	

                $sql="UPDATE vus_tramites_{$_POST['tipo']}2 SET
                $faltante_str
                ".$_POST['catalogo_prefijo']."sta = '2', 
                ".$_POST['catalogo_prefijo']."usr = '".$_SESSION['ADMusuario_id']."', 
                ".$_POST['catalogo_prefijo']."dt  = now()		
                WHERE 
                ".$_POST['catalogo_prefijo']."numsol = '{$_POST['codigo']}' AND 
                ".$_POST['catalogo_prefijo']."tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                ".$_POST['catalogo_prefijo']."tpt_id = '{$_POST['ctg_tpt_id']}' ";
                echo "VER ESTE <br>".$sql;
                $result=$connectionVUS->Execute($sql);

                //aca finaliza la etapa inicial 01 automaticamente al asignar las etapas
                $sql="UPDATE adm_control_{$_POST['tipo']}1 SET
                adm_con_prnlst = '1',
                adm_con_dt = now(),
                adm_con_sta='2'
                WHERE adm_con_numsol = '{$_POST['codigo']}' AND adm_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                adm_con_tpt_id = '{$_POST['ctg_tpt_id']}'";
                echo "<br>".$sql;
                $result = $connection->Execute ( $sql );

                $info = $arr_label['datos_grabados'];    

                echo $sql."<br>[".$error."]<br>[".$info."]<br>";
            // }		

        } else {
            echo "resultado 2<br>";
                $input_dt=fecha_srv($_POST['input_dt']);
                $faltante_str .= $_POST['catalogo_prefijo']."fisrec = '2', ";
                $faltante_str .= $_POST['catalogo_prefijo']."fisrec_dt = now(), ";                
                echo "faltante str (".$faltante_str.")";

                $sql="UPDATE vus_tramites_{$_POST['tipo']}2 SET
                $faltante_str
                vus_{$_POST['tipo']}_est_id ='10',
                vus_{$_POST['tipo']}_est_dt = now(),
                vus_{$_POST['tipo']}_sta ='2',
                vus_{$_POST['tipo']}_usr ='".$_SESSION['ADMusuario_id']."',
                vus_{$_POST['tipo']}_dt =now()
                WHERE         
                vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND 
                vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
                vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}' ";
                // echo "<br>".$sql;
                $result=$connectionVUS->Execute($sql);

                //aca finaliza la etapa inicial 01 automaticamente al asignar las etapas
                $sql="UPDATE adm_control_{$_POST['tipo']}1 SET
                adm_con_rf_status = '3',
                adm_con_rf_dt = now(),
                adm_con_rf_usr = '".$_SESSION['ADMusuario_id']."',
                adm_con_rf_obs = '".$_POST['obs']."',                                
                adm_con_prnlst = '1'
                WHERE adm_con_numsol = '{$_POST['codigo']}' AND adm_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                adm_con_tpt_id = '{$_POST['ctg_tpt_id']}'";
                // echo "<br>".$sql;
                $result = $connection->Execute ( $sql );
                $error = $connection->ErrorMsg();	

                $info = $arr_label['datos_grabados'];
        }
        
        $faltante_str="";
        break;
        }

    case '010111':{

            echo "///////////////////////////////////////////////////////////////////////////////////////////////////////<br>";
            echo "///////////////////////////".date("d/m/Y h:i:s")."////////////////////////////////////////////////////////////////////////////<br>";
            echo "//////////////////////////// numsol = ".$_POST['codigo']."///////////////////////////////////////////////////////////////////////////<br>";
            echo "//////////////////////////// menu = ".$_POST['id']."///////////////////////////////////////////////////////////////////////////<br>";
            echo "//////////////////////////// res st = ".$_POST['res_st']."///////////////////////////////////////////////////////////////////////////<br>";
    
            echo "//////////////////////////// est id new = ".$est_id_new."///////////////////////////////////////////////<br>";
    
            echo "<br>****************************************************  ".$_POST['id']."<br>";
            echo "<br>dtb_vus -----------(".$_SESSION['dtb_vus'].")--------<br>";
    
            $cambio_status = false;
            echo "VOY A ENTRAR";
            if ( $_POST['res_st']=='1'){
                echo "FACTURADO SI <br>";

                $input_dt=fecha_srv($_POST['input_dt']);
                $faltante_str .= $_POST['catalogo_prefijo']."fac = '1', ";
                echo "faltante str (".$faltante_str.")";
                // $faltante_str .= $_POST['catalogo_prefijo']."fac = '1', ".$_POST['catalogo_prefijo']."est_id = '".$est_id_new."',";
    
                $sql="UPDATE vus_tramites_{$_POST['tipo']}_dates SET
                vus_{$_POST['tipo']}_dat_dt20 = now()
                WHERE         
                vus_{$_POST['tipo']}_dat_numsol = '{$_POST['codigo']}' AND 
                vus_{$_POST['tipo']}_dat_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
                vus_{$_POST['tipo']}_dat_tpr_id = '{$_POST['ctg_tpr_id']}' ";
                $result=$connectionVUS->Execute($sql);

                // UPDATE ESTATUS DE DOSSIER RECIBIDO
                $sql="UPDATE \"vus_tramites_{$_POST['tipo']}_PAGOs\" SET
                \"vus_{$_POST['tipo']}EST_fact_sn\" = '1', 
                \"vus_{$_POST['tipo']}EST_fact_dt\" = now()
                WHERE 
                \"vus_{$_POST['tipo']}EST_numsol\" = '{$_POST['codigo']}' AND 
                \"vus_{$_POST['tipo']}EST_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND 
                \"vus_{$_POST['tipo']}EST_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND
                \"vus_{$_POST['tipo']}EST_tts_id\" = '5' ";
                echo "<br>sql ".$sql;
                $result=$connectionVUS->Execute($sql);

                $dtb_vus='';
                $sql="SELECT vus_{$_POST['tipo']}_numsol FROM  vus_tramites_{$_POST['tipo']}1 WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' ";
                echo "<br>".$sql;

                $result = $connectionVUS->Execute($sql);
                if (!$result->EOF) {
                    $dtb_vus='1';
                }
                $sql="UPDATE vus_tramites_{$_POST['tipo']}{$dtb_vus} SET
                $faltante_str
                ".$_POST['catalogo_prefijo']."sta = '2', 
                ".$_POST['catalogo_prefijo']."usr = '".$_SESSION['ADMusuario_id']."', 
                ".$_POST['catalogo_prefijo']."dt  = now()		
                WHERE 
                ".$_POST['catalogo_prefijo']."numsol = '{$_POST['codigo']}' AND 
                ".$_POST['catalogo_prefijo']."tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                ".$_POST['catalogo_prefijo']."tpt_id = '{$_POST['ctg_tpt_id']}' ";
                echo "<br>".$sql;
                $result=$connectionVUS->Execute($sql);

            }
            $faltante_str="";
            break;
            }
    
    }


	$comments = "";

    $arr_label[576]='dias_proceso';
    $arr_label[368]='se_cambio_status';
    $arr_label[574]='estatus_actual';
    $arr_label[575]='estatus_anterior';
    $arr_label[502]="resultado";
    $arr_label[10]='tipo_producto';
    $arr_label[54]='tipo_tramite';
    $arr_label[317]='tramite_no';
    $arr_label[84]='nombre_producto';
    $arr_label[690]='nombre_company';
    $arr_label[1377]='faltante';
	$arr_label[505]='no_conforme';    
	$arr_label[323]='conforme';  
	$arr_label[14]='comentarios';  
	$arr_label[1237] = 'saludo_faltante';
	$arr_label[1238] = 'saludo_faltante1';
	$arr_label[1239] = 'saludo_faltante2';

    $arr_label[1342] = 'model10_part1';
    $arr_label[1343] = 'model10_part2';
    $arr_label[1344] = 'model10_part3';
    $arr_label[1345] = 'model10_part4';
    $arr_label[1346] = 'model10_part5';

    $arr_label[1347] = 'model9_part1';
    $arr_label[1877] = 'model9_part11';
    $arr_label[1878] = 'model9_part12';
    $arr_label[1880] = 'model9_part12b';
    $arr_label[1904] = 'model9_part13';
    $arr_label[1879] = 'model9_part14';
    $arr_label[1348] = 'model9_part2';
    $arr_label[1349] = 'model9_part3';
    $arr_label[1350] = 'model9_part4';
    
    $arr_label[1351] = 'model12_part1';
    $arr_label[1352] = 'model12_part2';
    $arr_label[1353] = 'model12_part3';

    $arr_label[1374] = 'model11_part1';
    $arr_label[1882] = 'model11_part11';
    $arr_label[1352] = 'model11_part2';
    $arr_label[1533] = 'model11_part3';

    $arr_label[1529] = 'model11a_part1';
    $arr_label[1530] = 'model11a_part2';
    $arr_label[1531] = 'model11a_part3';
    $arr_label[1532] = 'model11a_part4';

    $arr_label[1356] = 'model13_part1';
    $arr_label[1357] = 'model13_part2';

    $arr_label[1358] = 'model131_part1';
    $arr_label[1880] = 'model132_part11';

    $arr_label[1541] = 'model14_part1';
    $arr_label[1542] = 'model14_part2';
    $arr_label[1543] = 'model14_part3';
    $arr_label[1544] = 'model14_subject';

    $arr_label[1447] = 'subject_1';
    $arr_label[1448] = 'subject_2';

    $arr_label[1455] = 'modelQ_reqsta';

    $arr_label[1456] = 'modelQ1_part1';
    $arr_label[1457] = 'modelQ1_part2';
    $arr_label[1458] = 'modelQ1_part3';

    $arr_label[1459] = 'modelQ2_part1';
    $arr_label[1460] = 'modelQ2_part2';
    $arr_label[1477] = 'modelQ2_part3';
    $arr_label[1461] = 'modelQ2_part4';

    $arr_label[1462] = 'modelQ3_part1';
    $arr_label[1463] = 'modelQ3_part2';
    $arr_label[1464] = 'modelQ3_part3';
    $arr_label[1465] = 'modelQ3_part4';
    $arr_label[1466] = 'modelQ3_part5';
    $arr_label[1467] = 'modelQ3_part6';

    $arr_label[1468] = 'modelQ4_part1';
    $arr_label[1469] = 'modelQ4_part2';
    $arr_label[1470] = 'modelQ4_part3';

    $arr_label[1471] = 'modelQ5_part1';
    $arr_label[1472] = 'modelQ5_part2';
    $arr_label[1473] = 'modelQ5_part3';
    $arr_label[1474] = 'modelQ5_part4';

    $arr_label[1475] = 'modelQ6_part1';
    $arr_label[1476] = 'modelQ6_part2';

    $arr_label[1496] = 'modelQ7_part1';
    $arr_label[1497] = 'modelQ7_part2';
    $arr_label[1498] = 'modelQ7_part3';
    $arr_label[1499] = 'modelQ7_part4';
    $arr_label[1500] = 'modelQ7_part5';
    $arr_label[1501] = 'modelQ7_part6';
    $arr_label[1502] = 'modelQ7_part7';

    $arr_label[1503] = 'modelQ8_part1';
    $arr_label[1504] = 'modelQ8_part2';
    $arr_label[1505] = 'modelQ8_part3';
    $arr_label[1506] = 'modelQ8_part4';

    $arr_label[1537] = 'modelQ9_part1';
    $arr_label[1837] = 'subject_status';

    $arr_label[1876] = 'muestra_rechazada';
    $arr_label[1905] = 'muestra_rechazada2';

    $arr_label[1885] = 'model15_part1';
    $arr_label[1886] = 'model15_part2';
    $arr_label[1887] = 'model15_part3';
    $arr_label[1888] = 'model15_subject';

    $arr_label[1902] = 'model16_subject';
    $arr_label[1903] = 'model16_part1';

    $arr_lang = "576,368,574,575,502,10,54,317,84,690, 367,505,323,14,1237,1238, 1239, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350,1351,1352,1353,1354,1355,1356,1357,1358,1377,1447,1448,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477,1496,1497,1498,1499,1500,1501,1502,1503,1504,1505,1506,1529,1530,1531,1532,1533,1537,1541,1542,1543,1544,1837,1374, 1876,1882,1885,1886,1887,1888, 1877,1878,1879,1880,1902,1903,1904,1905";

    include ('form_language.php');   

    //OBTENER LEYENDAS DE ESTATUS ANTERIOR Y ACTUAL     
    $sql="SELECT ctg_tts_id,ctg_tts_desc FROM ctg_tipo_tramites_estatus WHERE ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND  ctg_tpr_id = '{$_POST['ctg_tpr_id']}' AND (ctg_tts_id In ('".$est_id."','".$est_id_new."'))";
    echo $sql."<br>";

    $result = $connection->Execute ($sql);
    if (! $result->EOF) {
        while (!$result->EOF) {
             $des[] = $result->fields[1];
             $result->MoveNext();
        }
    }
    $subject = $arr_label['subject_status'].". ".$_POST['codigo']; 

    if ( substr($_POST['id'],0,4) != '0104' ) {
        if ($tipo_mensaje == 1) 
            if ($faltante==1) {
                $subject .= " ".$arr_label['faltante'];
                $subject2 .= " ".$arr_label['faltante'];
            }
    }

    if ($hay_rechazo == 1 && $est_id_new == 7) {
        switch (substr($_POST['id'],0,4)) {
            // case '0101':
            // case '0102':
            //     $subject=$arr_label['subject_1']." ".$arr_label['no'].". ".$_POST['codigo']; 
            //     break;
            // case '0301':
            // case '0302':
            //     $subject=$arr_label['subject_2']." ".$arr_label['no'].". ".$_POST['codigo']; 
            //     break;
            case '0101':
                $subject=$arr_label['subject_2']." ".$arr_label['no'].". ".$_POST['codigo']; 
                break;
            case '0104':
                case '0104':
                switch ($_POST['id']) {
                    case "010402":
                        $subject=$arr_label['modelQ2_part4']." ".$arr_label['no'].". ".$_POST['codigo']; 
                        break;
                    case "010402":
                        $subject=$arr_label['modelQ5_part4']." ".$arr_label['no'].". ".$_POST['codigo'];                    
                        break;
                    case "010411":
                        $subject=$arr_label['modelQ8_part4']." ".$arr_label['no'].". ".$_POST['codigo'];
                        break;
                }
    	        
				break;
        }
    }

    echo "(campo=$campo)(res_obs={$_POST['res_obs']})(cambio_estatus=$cambio_status)<br>";
    echo "<br> subject ".$subject."<br>";

    if(($_POST['id']=='010101' || $_POST['id']=='010102' || $_POST['id']=='010104' || $_POST['id']=='010103' || $_POST['id']=='010105' || $_POST['id']=='010204' || $_POST['id']=='010203' || $_POST['id']=='010205' || $_POST['id']=='010403') && $est_id_new == 5 && intval($_POST['res_st']) == 1){  //traido aqui desde admitir_tramite.php

        $sql="SELECT ctg_tpt_req_formula, ctg_tpt_sigadm FROM ctg_tipo_tramites WHERE ctg_tpt_id = '{$_POST['ctg_tpt_id']}' AND  ctg_tpr_id = '{$_POST['ctg_tpr_id']}'";    
        $result = $connection->Execute ($sql);
        if (!$result->EOF) {
            $operador = $result->fields;        
            $ctg_tpt_sigadm = $operador['ctg_tpt_sigadm'];    
        }
            
        $sql="SELECT ctg_tpr_coradm FROM ctg_tipo_productos WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}'";
        // echo$sql."<br>";
        $numadmi = 0;
        $result=$connection->Execute($sql);
        if (!$result->EOF) {
                $operador = $result->fields;
                $numadmi = intval($operador['ctg_tpr_coradm']);
                $numadmi2 = intval($operador['ctg_tpr_coradm']);
        }
        $numadmi++;
        $numadmi2++;

        $len = strlen($numadmi);
        $nsecuencia='';
        if ($len<=1)
            $nsecuencia='0000'.strval($numadmi);
        else
            if ($len <=2)
                $nsecuencia='000'.strval($numadmi);
            else
                if ($len <=3)
                    $nsecuencia='00'.strval($numadmi);
                else
                    if ($len <=4)
                        $nsecuencia='0'.strval($numadmi);
                    else
                        $nsecuencia=strval($numadmi);

        $year= date("Y");
        $numadmi =$year.$nsecuencia;
        
        $sql="UPDATE ctg_tipo_productos SET ctg_tpr_coradm='".$numadmi2."', ctg_tpr_sta = '2', ctg_tpr_usr = '".$_SESSION['ADMusuario_id']."', ctg_tpr_dt = now() WHERE ctg_tpr_id = '{$_POST['ctg_tpr_id']}'";
        $result = $connection->Execute ( $sql );
        
        echo "(numadmi=$numadmi)(ctg_tpt_sigadm=$ctg_tpt_sigadm)(tipo={$_POST['tipo']})(y=".date("y").")";

        //$numadmi = strtoupper($_POST['tipo']) . "-" . date("y") . "-" . sprintf("%05d",$numadmi);                
        $numadmi = sprintf("%05d",$numadmi);                
        if (!empty($ctg_tpt_sigadm))
            $numadmi = $ctg_tpt_sigadm . "-" . $numadmi;

        echo "(numadmi=$numadmi)(INFORMACION($faltante_str)<br>";

	    if (!empty($faltante_str)) {
            $faltante_str .= $_POST['catalogo_prefijo']."numadmi = '".$numadmi."',
                           ".$_POST['catalogo_prefijo']."fecadmi = '".date("Y-m-d")."',
                           ".$_POST['catalogo_prefijo']."usradmi_id = '".$_SESSION['ADMusuario_id']."',";
	    }
    
    }
    
    if ($ventanilla == 1) {//todos menos los de evaluacion
		$texto = "";
		if (intval($_POST['res_st']) == 1) {
			$texto = "(No hay texto en emails db) catalogo = [".$_POST['id']."]";
			
			$sql="SELECT ctg_ema_obs FROM ctg_emails WHERE (ctg_tpr_id = '{$_POST['ctg_tpr_id']}') AND (ctg_ema_id = '".$_POST['id']."')";
			$result = $connection->Execute ($sql);
			if (!$result->EOF) 
				$texto = "<br>".$result->fields[0];
		}
    
        $table_info .= "<table>";
        $table_info .= "Fecha: ".date("d-m-Y")."<br><br>";
        $table_info .= "<tr><td>".$arr_label['estimado'];
        $table_info .= "<tr><td colspan=2>".$_POST['nombre'];
        $table_info .= "<tr><td colspan=2><br>";

        if  (substr($_POST['id'],0,4)=='0102' || substr($_POST['id'],0,4)=='0301' || substr($_POST['id'],0,4)=='0307'){
            $table_info .= "<tr><td>".$arr_label['nombre_company'].":<td>".$_POST['nomprod'];            
        } else {
            $table_info .= "<tr><td>".$arr_label['nombre_producto'].":<td>".$_POST['nomprod'];//.", ".$_POST['forma'].", ".$_POST['strength'].", ".str_replace("#039;","'",$_POST['presenta'])
        }
        $body = "";
        $table_info .= "<tr><td>".$arr_label['tramite_no']."     :<td>".$_POST['codigo'];
        $table_info .= "</table>";

        if ($hay_rechazo == 1 && $est_id_new == 7) {  /// ESTE ES EL RECHAZO AUTOMATICO

				$body = $table_info;
                switch($_POST['id']){
                case '010101':
                case '010102':
                case '010103':
                case '010104':
                    // company licences
                case '010201':
                case '010202':
                case '010203':

                    // UPDATE FECHA DE NOT-RECEIVABLE
                    $sql="UPDATE vus_tramites_{$_POST['tipo']}_dates SET
                    vus_{$_POST['tipo']}_dat_dt03 = now()
                    WHERE         
                    vus_{$_POST['tipo']}_dat_numsol = '{$_POST['codigo']}' AND 
                    vus_{$_POST['tipo']}_dat_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
                    vus_{$_POST['tipo']}_dat_tpr_id = '{$_POST['ctg_tpr_id']}' ";
                    $result=$connectionVUS->Execute($sql);

                    if ($_POST['id']=="010104") {
                        // $body .= "<br>".$arr_label['model12_part1']."<br><br>".$arr_label['model12_part2']."<br><br>".$arr_label['model12_part3']."<br><br>";
                        // $body .= "<br>".$arr_label['muestra_rechazada']."<br><br>";
                        switch ($_POST['ctg_tpr_id']) {
                            case '02':
                                switch ($tpc_id) {
                                    case 'A':
                                    case 'B':
                                    case 'C2': // CON BIOEQUIVALENCIA
                                        $body .= "<br>".$arr_label['muestra_rechazada2']."<br><br>";
                                        break;

                                    case 'C1':
                                        $body .= "<br>".$arr_label['muestra_rechazada']."<br><br>";
                                        break;

                                    default:
                                        $body .= "<br>".$arr_label['muestra_rechazada']."<br><br>";
                                        break;
                                }
                                break;
                            case '06':

                                switch ($tpc_id) {
                                    case 'A1':
                                    case 'A2':
                                    case 'B1':
                                    case 'B2':
                                        $body .= "<br>".$arr_label['muestra_rechazada2']."<br><br>";
                                        break;

                                    case 'C':
                                        $body .= "<br>".$arr_label['muestra_rechazada']."<br><br>";
                                        break;

                                    default:
                                        $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                        break;
                                }
                                break;

                            default:
                                $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                break;
                        }
                        
                    } else {

                        $body .= "<br>".$arr_label['model11_part11'];
                        if (!empty($_POST['res_obs']))
                            $body .= "<br><br><b>".nl2br($_POST['res_obs'])."</b><br><br>";
                        else
                            $body .= "..................<br><br>";
                        break;                            

                    }
                    break;
                // qclab
                case '010401':
                case '010402':{
                    $body .= "<br>".$arr_label['modelQ2_part1']." ".$arr_label['modelQ2_part2']."<br>";
                    if (!empty($_POST['res_obs']))
                        $body .= "<b>".nl2br($_POST['res_obs'])."</b>";
                    else
                        $body .= "..................<br><br>";

                    $body .= "<br><br>".$arr_label['modelQ_reqsta']."<b>".$arr_label['modelQ2_part4']."</b><br><br>";
                    }
                    break;
                case '010403':
                    $subject = $arr_label['modelQ5_part4']." ".$arr_label['no'].". ".$_POST['codigo']; 

                    $body .= "<br>".$arr_label['modelQ5_part1']." ".$arr_label['modelQ5_part2']."<br>";
                    if (!empty($_POST['res_obs']))
                        $body .= "<b>".nl2br($_POST['res_obs'])."</b><br><br>";
                    else
                        $body .= "................<br><br>";

                    $body .= "<br>".$arr_label['modelQ5_part3']."<b>".$arr_label['modelQ5_part4']."</b>";               	
                	
                    break;
                case '010411':
                    $body .= "<br>".$arr_label['modelQ8_part1']." ".$arr_label['modelQ8_part2']." ".$arr_label['modelQ8_part3']."<br><br>";

                    $body .= "<br>".$arr_label['modelQ5_part3']."<b>".$arr_label['modelQ8_part4']."</b>";
                    
                    break;
                case '010104':
                case '010106':
                // company licences
                case '010204':
                case '010206':
                // qc lab
                case '010404':
                case '010406':
                    $body .= "<br>".$arr_label['model12_part1']."<br><br>".$arr_label['model12_part2']."<br><br>".$arr_label['model12_part3'];
                    break;
                case '030509':
                case '030709':
                    $body .= "<br><br>".$_POST['res_obs']."<br><br>";
                    break;
				}

		} else {
                $body = $table_info;
                //$subject = $arr_label['subject_status'];
                switch($_POST['id']){
                // company licences
                case '010201':
                case '010202':

                        switch($_POST['res_st']){

                        case 1: //aqui la fecha es la del sistema mas 2 meses
                            
                            $body .= "<br>".$arr_label['model9_part1']." <br>".$arr_label['model9_part2']."".$arr_label['model9_part3']."<br>".$arr_label['model9_part4'];
                            
                            break;

                        case 2: // aqui la fecha es la de vencimiento del faltante, o sea la fecha del sistema + los dias que le dara el evaluador en days for response

                            // UPDATE FECHA DE NOT-RECEIVABLE
                            $sql="UPDATE vus_tramites_{$_POST['tipo']}_dates SET
                            vus_{$_POST['tipo']}_dat_dt02 = now()
                            WHERE         
                            vus_{$_POST['tipo']}_dat_numsol = '{$_POST['codigo']}' AND 
                            vus_{$_POST['tipo']}_dat_tpt_id = '{$_POST['ctg_tpt_id']}' AND 
                            vus_{$_POST['tipo']}_dat_tpr_id = '{$_POST['ctg_tpr_id']}' ";
                            $result=$connectionVUS->Execute($sql);
                            $dias = intval($_POST['res_ds']);                    
                            if ($dias > 0)
                                $_POST['fechaven'] = suma_fechas($_POST['fecha'],$dias);//recibe en formato d-m-Y y retorna Y-m-d

                            $body .= "<br>".$arr_label['model10_part1']." ".fecha_usr($_POST['fechaven'])."</b> ".$arr_label['model10_part2']."<br><br>".$arr_label['model10_part4']."<br>";

                            if (!empty($_POST['res_obs']))
                                $body .= nl2br($_POST['res_obs']);

                            $body .= "<br>".$tabla_docs_obs; //2013-03-12

                            $body .= "<br>".$arr_label['model10_part3']."<br>";
                            
                            break;
                        case 4: //aqui le texto para envio de informarcion de los tests que se van a hacer
                            
                            $body .= "<br>".$arr_label['model9_part1']." <br>".$arr_label['model9_part2']."".$arr_label['model9_part3']."<br>".$arr_label['model9_part4'];
                            
                            $body .= nl2br($_POST['res_obs']);
                            
                            break;

                        }
                        break;                
                case '010101':
                case '010102':
                case '010103':
                case '010203':
                    switch(intval($_POST['res_st'])){
                        case 1:  //aqui la fecha es la del sistema mas 2 meses
                            if ($req_mue =='1'){
                                $dias_m=$_POST['mue_ds'];
                                $_POST['fechaven'] = suma_fechas($_POST['fecha'],$dias_m);//recibe en formato d-m-Y y retorna Y-m-d

                                switch ($_POST['ctg_tpr_id']) {
                                    case '02':
                                        switch ($tpc_id) {
                                            case 'A':
                                            case 'B':
                                            case 'SI':
                                            case 'C2': // CON BIOEQUIVALENCIA
                                                $body .= "<br>".$arr_label['model9_part1']." ".$arr_label['model9_part11']." ".fecha_usr($_POST['fechaven'])." ".$arr_label['model9_part14']."<br>".$arr_label['model9_part13']."<br><br>";
                                                break;

                                            case 'C1':
                                                $body .= "<br>".$arr_label['model9_part1']." ".$arr_label['model9_part12']." ".fecha_usr($_POST['fechaven'])." ".$arr_label['model9_part14']."<br>".$arr_label['model9_part13']."<br><br>";
                                                break;
    
                                            default:
                                                $body .= "<br>".$arr_label['model9_part1'].".<br><br>";
                                            break;
                                        }
                                        break;
                                    case '06':

                                        switch ($tpc_id) {
                                            case 'A1':
                                            case 'A2':
                                            case 'B1':
                                            case 'B2':
                                                $body .= "<br>".$arr_label['model9_part1']." ".$arr_label['model9_part11']." ".$arr_label['model9_part12b']." ".fecha_usr($_POST['fechaven'])." ".$arr_label['model9_part13']."<br>";// <b>".fecha_usr($_POST['fechaven']).".<br><br>";    
                                                break;

                                            case 'C':
                                                $body .= "<br>".$arr_label['model9_part1']." ".$arr_label['model9_part11']." ".$arr_label['model9_part12']." ".fecha_usr($_POST['fechaven'])." ".$arr_label['model9_part13']."<br>";// <b>".fecha_usr($_POST['fechaven']).".<br><br>";    
                                                break;
    
                                            default:
                                                $body .= "<br>".$arr_label['model9_part1'].".<br><br>";
                                                break;
                                        }
                                        break;

                                    default:
                                        $body .= "<br>".$arr_label['model9_part1'].".<br><br>";
                                        break;
                                }

                                // $body .= "<br>".$arr_label['model9_part1']." ".$arr_label['model9_part11']."<br><br>".$arr_label['model9_part12']." ".$dias_m." ".$arr_label['model9_part13']."<br><br>";// <b>".fecha_usr($_POST['fechaven']).".<br><br>";    
                            } else {
                                $body .= "<br>".$arr_label['model9_part1'].".<br><br>";
                            }
                            $sql="UPDATE vus_tramites_{$_POST['tipo']}{$_SESSION['dtb_vus']} SET
                            vus_{$_POST['tipo']}_samlim_dt ='".$_POST['fechaven']."',
                            vus_{$_POST['tipo']}_sta = '2', 
                            vus_{$_POST['tipo']}_usr = '".$_SESSION['ADMusuario_id']."',
                            vus_{$_POST['tipo']}_dt =now()          
                            WHERE vus_{$_POST['tipo']}_numsol = '{$_POST['codigo']}' AND vus_{$_POST['tipo']}_tpt_id = '{$_POST['ctg_tpt_id']}' AND vus_{$_POST['tipo']}_tpr_id = '{$_POST['ctg_tpr_id']}'";
                            echo $sql."<br>";
                            $result=$connectionVUS->Execute($sql);                                             
                            
                            break;

                        case 2: // aqui la fecha es la de vencimiento del faltante, o sea la fecha del sistema + los dias que le dara el evaluador en days for response
                            $dias = intval($_POST['res_ds']);                    
                            if ($dias > 0)
                                $_POST['fechaven'] = suma_fechas($_POST['fecha'],$dias);//recibe en formato d-m-Y y retorna Y-m-d

                            $body .= "<br>".$arr_label['model10_part1']." <b>".fecha_usr($_POST['fechaven'])."</b> ".$arr_label['model10_part2']."<br><br>".$arr_label['model10_part3']."<br>".$arr_label['model10_part4']."<br>";
                            // $body .= "<br>".$arr_label['model10_part1']." ".dias." ".$arr_label['model10_part2']."<br><br>";//".$arr_label['model10_part3']."<br>".$arr_label['model10_part4']."<br>";//fecha_usr($_POST['fechaven'])

                            // $body .= $arr_label['model10_part5']."<br>";
                            if (!empty($_POST['res_obs']))
                                $body .= nl2br($_POST['res_obs']);

                            $body .= "<br><br>".$tabla_docs_obs; //2013-03-12
                            
                            break;

                        case 4:  //aqui le texto para envio de informarcion de los tests que se van a hacer
                            
                            $body .= "<br>".$arr_label['model9_part1']." <br>".$arr_label['model9_part2']."".$arr_label['model9_part3']."<br>".$arr_label['model9_part4'];
                            
                            $body .= nl2br($_POST['res_obs']);
                            
                            break;

                    }
                    break;
                case '010104':
                case '010204':
                case '010404':
                    
                            // $body .= "<br>".$arr_label['model131_part1'];

                            switch ($_POST['ctg_tpr_id']) {
                                case '02':
                                    switch ($tpc_id) {
                                        case 'A':
                                        case 'B':
                                        case 'C2': // CON BIOEQUIVALENCIA
                                            $body .= "<br>".$arr_label['model132_part11']."<br><br>";
                                            break;

                                        case 'C1':
                                            $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                            break;

                                        default:
                                            $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                        break;
                                    }
                                    break;
                                case '06':

                                    switch ($tpc_id) {
                                        case 'A1':
                                        case 'A2':
                                        case 'B1':
                                        case 'B2':
                                            $body .= "<br>".$arr_label['model132_part11']."<br><br>";
                                            break;

                                        case 'C':
                                            $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                            break;

                                        default:
                                            $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                            break;
                                    }
                                    break;

                                default:
                                    $body .= "<br>".$arr_label['model131_part1']."<br><br>";
                                break;
                            }
                            break;
                case '010110':
                            $subject = $arr_label['model14_subject']." ".$arr_label['no'].". ".$_POST['codigo']; 
                            $_POST['fechaven'] = suma_fechas($_POST['fecha'],$dias);//recibe en formato d-m-Y y retorna Y-m-d
                            $body .= "<br>".$arr_label['model14_part1']."<br><br>".$arr_label['model14_part2']." ".fecha_usr($_POST['fechaven']).".<br><br>".$arr_label['model14_part3']."<br><br>";
                            if ( !empty($_POST['res_obs']))
                                $body .= nl2br($_POST['res_obs']);
                            break;

                case '010111':
                    $subject = $arr_label['model16_subject']." ".$arr_label['no'].". ".$_POST['codigo']; 
                    $body .= "<br>".$arr_label['model16_part1']."<br>";
                    // if ( !empty($_POST['res_obs']))
                    //     $body .= nl2br($_POST['res_obs']);
                    break;
    
                case '010106':
                case '010206':
                case '010406':
                        $subject = $arr_label['model15_subject'].". ".$_POST['codigo']; 

                        switch (intval($_POST['res_st'])) {
                            case 1 :
                                $body .= "<br>".$arr_label['model15_part1'];
                                break;
                            case 2 :
                                $body .= "<br>".$arr_label['model15_part2'];
                                break;
                            
                            case 3 :
                                $body .= "<br>".$arr_label['model15_part3']."<br><br>";
                                if ( !empty($_POST['obs']))
                                    $body .= nl2br($_POST['obs']);
                                break;
                        }
                        break;
                case '030509':
                case '030709':
                    $body .= "<br><br>".$_POST['res_obs']."<br><br>";
                    break;
                // qclab
                case '010401':
                case '010402':
                        switch(intval($_POST['res_st'])){

                        case 1: //screening acepta la solicitud
			                $subject = $arr_label['modelQ1_part3']." ".$arr_label['no'].". ".$_POST['codigo']; 

                            $body .= "<br>".$arr_label['modelQ1_part1']."<br>".$arr_label['modelQ1_part2']."<br><br>".$arr_label['modelQ_reqsta']."<b>".$arr_label['modelQ1_part3']."</b>";

                            break;

                        case 4: //screening comentarios
			                $subject = $arr_label['modelQ3_part6']."  ".$arr_label['no'].". ".$_POST['codigo']; 
                            
                            $body .= "<br>".$arr_label['modelQ3_part1']." ".$arr_label['modelQ3_part2']."<br>";

                            if (!empty($_POST['vus_qc_reqtest']))
                                $body .= $arr_label['modelQ3_part3']."<b>".nl2br($_POST['vus_qc_reqtest'])."</b><br>";
                            else
                                $body .= $arr_label['modelQ3_part3']."<b>..................</b>"."<br>";

                            if (!empty($_POST['res_obs']))
                                $body .= $arr_label['modelQ3_part4']."<b>".nl2br($_POST['res_obs'])."</b><br>";
                            else
                                $body .= $arr_label['modelQ3_part4'].".................."."<br>";

                            $body .= $arr_label['modelQ3_part5']."<br><br>".$arr_label['modelQ_reqsta']."<b>".$arr_label['modelQ3_part6']."</b>";
                                                        
                            break;

                        }
                        break;

                case '010403':
                        switch(intval($_POST['res_st'])) {

                        case 1: //aqui la fecha es la del sistema mas 2 meses
			                $subject = $arr_label['modelQ4_part3']."  ".$arr_label['no'].". ".$_POST['codigo']; 
                            
                            $body .= "<br>".$arr_label['modelQ4_part1']."<br>".$arr_label['modelQ4_part2']."<br><br>".$arr_label['modelQ_reqsta']."<b>".$arr_label['modelQ4_part3']."</b><br>";
                            
                            break;

                        case 4: //aqui le texto para envio de informarcion de los tests que se van a hacer
			                $subject = " Comments from CURS ".$arr_label['no'].". ".$_POST['codigo']; 
                            
                            $body .= "<br>".$arr_label['modelQ9_part1']."<br>";                            
                            $body .= nl2br($_POST['res_obs']);
                            
                            break;
                        }
                        break;
                case '010411':
                        switch(intval($_POST['res_st'])) {

                        case 1: //aqui la fecha es la del sistema mas 2 meses
                            $subject = $arr_label['modelQ4_part3']."  ".$arr_label['no'].". ".$_POST['codigo']; 
                            
                            $body .= "<br>".$arr_label['modelQ4_part1']."<br>".$arr_label['modelQ4_part2']."<br><br>".$arr_label['modelQ_reqsta']."<b>".$arr_label['modelQ4_part3']."</b><br>";

                            break;
                        case 4: //aqui le texto para envio de informarcion de los tests que se van a hacer
                            $subject = $arr_label['modelQ7_part7']." ".$arr_label['no'].". ".$_POST['codigo']; 
                            
                            $body .= "<br>".$arr_label['modelQ7_part1']." ".$arr_label['modelQ7_part2']." ".$arr_label['modelQ7_part3']."<br>";

                            if (!empty($_POST['vus_qc_reqtest']))
                                $body .= $arr_label['modelQ7_part4']."<b>".nl2br($_POST['vus_qc_reqtest'])."</b><br>";
                            else
                                $body .= $arr_label['modelQ7_part4']."<b>..................</b>"."<br>";

                            if (!empty($_POST['res_obs']))
                                $body .= $arr_label['modelQ7_part5']."<b>".nl2br($_POST['res_obs'])."</b><br>";
                            else
                                $body .= $arr_label['modelQ7_part5'].".................."."<br>";
                            
                            $body .= $arr_label['modelQ7_part6']."<br><br>";
                            $body .= $arr_label['modelQ_reqsta']."<b>".$arr_label['modelQ7_part7']."</b>";
                            break;
                        }

                break;
            }
        }

        if ( $hay_rechazo == 1 && $hay_rechazo_faltante == 0) {
            echo "por aqui ";
                $_POST['fecha'] = date("d-m-Y");
                $dias = intval($_POST['res_ds']);
                if ($dias > 0)
                    $_POST['fecha'] = suma_fechas($_POST['fecha'],$dias);//recibe en formato d-m-Y y retorna Y-m-d
                //ACTUALIZA LA TABLA DE TRAMITES        
                echo "INSERTO EN MENSAJES ";

                $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}_MENSAJES\" (
                \"vus_{$_POST['tipo']}MSG_numsol\",
                \"vus_{$_POST['tipo']}MSG_tpt_id\", 
                \"vus_{$_POST['tipo']}MSG_tpr_id\", 
                \"vus_{$_POST['tipo']}MSG_tipo\",                           
                \"vus_{$_POST['tipo']}MSG_fecha\", 
                \"vus_{$_POST['tipo']}MSG_asunto\", 
                \"vus_{$_POST['tipo']}MSG_mensaje\", 
                \"vus_{$_POST['tipo']}MSG_usr_id\", 
                \"vus_{$_POST['tipo']}MSG_esa_id\", 
                \"vus_{$_POST['tipo']}MSG_sta\", 
                \"vus_{$_POST['tipo']}MSG_usr\", 
                \"vus_{$_POST['tipo']}MSG_dt\",
                \"vus_{$_POST['tipo']}MSG_fecven\",
                \"vus_{$_POST['tipo']}MSG_fecfal\",
                \"vus_{$_POST['tipo']}MSG_falsta\",
                \"vus_{$_POST['tipo']}MSG_nomprod\"                
                ) VALUES (
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',
                '{$_POST['ctg_tpr_id']}',
                '1',
                now(),                
                '".$subject."',
                '".str_replace("'","#039;",$body)."',
                '".$vus_usr_id."',
                '".$_SESSION['ADMnivel']."',                
                '0',
                '".$_SESSION['ADMusuario_id']."',
                now(),                
                '".$_POST['fechaven']."',
                now(),    
                '1',
                '{$_POST['nomprod']}');";
                echo "SQL MENSAJES 1 ($sql)<br>";
                $result=$connectionVUS->Execute($sql);
                
        }

        if (!empty($faltante_str)) {
	        
	        echo $sql."1 <br>[".$error."]<br>[".$info."]<br>";	

			if (strpos("***".$_POST['tabla'],"adm")) {        
	        	$_POST['catalogo_prefijo'] = $_POST['catalogo_prefijo1'];        
	        } 
	        
	        $sql="UPDATE ".$_POST['tabla']." SET
	        $faltante_str
	        ".$_POST['catalogo_prefijo']."sta = '2', 
	        ".$_POST['catalogo_prefijo']."usr = '".$_SESSION['ADMusuario_id']."', 
	        ".$_POST['catalogo_prefijo']."dt  = now()		
	        WHERE 
	        ".$_POST['catalogo_prefijo']."numsol = '{$_POST['codigo']}' AND 
	        ".$_POST['catalogo_prefijo']."tpr_id = '{$_POST['ctg_tpr_id']}' AND 
	        ".$_POST['catalogo_prefijo']."tpt_id = '{$_POST['ctg_tpt_id']}' ";
	        
			file_put_contents("hhh31.txt",$sql."\n".$sql);
            echo $sql."<br>";

			if (strpos("***".$_POST['tabla'],"adm")) {

		        $result=$connection->Execute($sql);
		        $error = $connection->ErrorMsg();	
		        if ($connection->Affected_Rows() == 1)
		            $info = $arr_label['datos_grabados'];
		            
			} else {

		        //$sql .= " AND ".$_POST['catalogo_prefijo']."est_id = '".$est_id."'";

		        $result=$connectionVUS->Execute($sql);
		        $error = $connectionVUS->ErrorMsg();	
		        if ($connectionVUS->Affected_Rows() == 1)
		            $info = $arr_label['datos_grabados'];
			}
			if ($_POST['id']=='010411'){ //PASA COMO RESULTADO NEGATIVO EN TABLAS DE CONTROL DE ANALISIS
                    $sql="UPDATE adm_control_{$_POST['tipo']}{$_SESSION['dtb_adm']} SET
                    adm_con_rf_status = '3',
                    adm_con_obs = '".$_POST['res_obs']."',                                
                    adm_con_dt = now()                                
                    WHERE adm_con_numsol = '{$_POST['codigo']}' AND adm_con_tpr_id = '{$_POST['ctg_tpr_id']}' AND 
                    adm_con_tpt_id = '{$_POST['ctg_tpt_id']}'";// AND ctg_esa_id = '".$_POST['ctg_esa_id']."'";
			        echo $sql."<br>[ ADN CONTROL <br>";				        
                    $result = $connection->Execute ( $sql );
			}
		}

        echo "hay rechazo ".$hay_rechazo."<br>";
        echo "cambio de estatus ".$cambio_status."<br>";
        echo " error ".$error."<br>";
        $error="";
        if ($error == "") {        	
            if ($cambio_status) {                
                echo "CAMBIO DE ESTATUS ";
                $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}_ESTATUS\" (
                \"vus_{$_POST['tipo']}EST_numsol\",
                \"vus_{$_POST['tipo']}EST_tpt_id\", 
                \"vus_{$_POST['tipo']}EST_tpr_id\", 
                \"vus_{$_POST['tipo']}EST_tts_id\", 							
                \"vus_{$_POST['tipo']}EST_estatus_dt\", 
                \"vus_{$_POST['tipo']}EST_obs\", 
                \"vus_{$_POST['tipo']}EST_usr_id\", 
                \"vus_{$_POST['tipo']}EST_sta\",
                \"vus_{$_POST['tipo']}EST_usr\",
                \"vus_{$_POST['tipo']}EST_dt\"
                ) VALUES (
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',
                '{$_POST['ctg_tpr_id']}',
                '".$est_id_new."',
                now(),
                '".$_POST['res_obs']."',
                '".$_SESSION['ADMusuario_id']."',
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now());";
				$result=$connectionVUS->Execute($sql);
				echo "2.".$sql."<br>"; //2018-01-09                
            } 
            
            
            if ($hay_rechazo == 100) { //2014-07-19

                $_POST['fecha'] = date("Y-m-d");
                $dias = intval($_POST['res_ds']);
                if ($dias > 0)
                    $_POST['fecha'] = suma_fechas($_POST['fecha'],$dias);//recibe en formato d-m-Y y retorna Y-m-d
                    
                echo "<br>[fecha=".$_POST['fecha']."][$dias]*<br>(fecha_bol={$_POST['bolresdt']})";
                echo "<br>INSERTO EN MENSAJES POR RECHAZO ";
                $sql="INSERT INTO \"vus_tramites_{$_POST['tipo']}_MENSAJES\" (
                \"vus_{$_POST['tipo']}MSG_numsol\",
                \"vus_{$_POST['tipo']}MSG_tpt_id\", 
                \"vus_{$_POST['tipo']}MSG_tpr_id\", 
                \"vus_{$_POST['tipo']}MSG_tipo\", 							
                \"vus_{$_POST['tipo']}MSG_fecha\", 
                
                \"vus_{$_POST['tipo']}MSG_asunto\", 
                \"vus_{$_POST['tipo']}MSG_mensaje\", 
                \"vus_{$_POST['tipo']}MSG_usr_id\", 
                \"vus_{$_POST['tipo']}MSG_esa_id\",	
                						
                \"vus_{$_POST['tipo']}MSG_sta\", 
                \"vus_{$_POST['tipo']}MSG_usr\", 
                \"vus_{$_POST['tipo']}MSG_dt\",
                
                \"vus_{$_POST['tipo']}MSG_fecven\",
                \"vus_{$_POST['tipo']}MSG_fecfal\",
                \"vus_{$_POST['tipo']}MSG_falsta\",
                \"vus_{$_POST['tipo']}MSG_nomprod\"
                
                ) VALUES (
                '{$_POST['codigo']}',
                '{$_POST['ctg_tpt_id']}',
                '{$_POST['ctg_tpr_id']}',
                '".$tipo_mensaje."',
                now(),
                
                '".$subject."',
                '".str_replace("'","#039;",$body)."',
                '".$vus_usr_id."',
                '".$_SESSION['ADMnivel']."',
                
                '1',
                '".$_SESSION['ADMusuario_id']."',
                now(),
                
                '".$_POST['fecha']."',
                now(),    
                '1',
                '{$_POST['nomprod']}');";
                
				echo "3 ($sql)";
				
				$result=$connectionVUS->Execute($sql);

            }
            
        }
        echo "info_email ".$info_email."<br>  error ".$error."<br>";
        //$info_email="";
        $error="";
        if ($error != '') {                
            echo "error = (1)[$error]<br>";
            include_once ("send_error_mail.php");
            $error = 1; 
            $info = "";
        } else {

            if (trim($_POST['email']) != "") {       //de donde viene este email 18/11/2010             
                // $email_empresa = "";
                // $sql="SELECT * FROM \"vus_tramites_{$_POST['tipo']}{$dtb_vus}_EMPRESAS\" WHERE  
                // \"vus_{$_POST['tipo']}EMP_numsol\" = '{$_POST['codigo']}' AND 
                // \"vus_{$_POST['tipo']}EMP_tpt_id\" = '{$_POST['ctg_tpt_id']}' AND
                // \"vus_{$_POST['tipo']}EMP_tpr_id\" = '{$_POST['ctg_tpr_id']}' AND
                // \"vus_{$_POST['tipo']}EMP_repr\" = '1'";

                // echo $sql."<br>";
                // $result=$connectionVUS->Execute($sql);
                // if (!$result->EOF) {
                //     while ( !$result->EOF ) {
                //         $operador = $result->fields;
                //         //if ($email_empresa != "") $email_empresa .= ",";
                //         if (!empty($operador["vus_{$_POST['tipo']}EMP_email1"])) 
                //             $email_empresa[]=$operador["vus_{$_POST['tipo']}EMP_email1"];
                //         else 
                //             $email_empresa[] = $operador["vus_{$_POST['tipo']}EMP_email2"]; 
                        
                //         $email_nombre[] = $operador["vus_{$_POST['tipo']}EMP_nombre"]." ".trim($operador["vus_{$_POST['tipo']}EMP_nom1"]." ".$operador["vus_{$_POST['tipo']}EMP_nom2"]." ".$operador["vus_{$_POST['tipo']}EMP_ape1"]." ".$operador["vus_{$_POST['tipo']}EMP_ape2"]);
                //         $result->MoveNext();
                //     }
                // }

                $headers = "From: $soporte <$company_email3>\nReply-To: $soporte <$company_email3>\nContent-Type: text/html; charset=UTF-8";
                $content = email_tpl($arr_label['informacion_tramite'],$body);
                $mailstoo = $_POST['email'];
                
                $my_name = "$soporte";
                $my_mail = $company_email3;
                $my_replyto = $company_email3;

                $send= mail_attachment("", "", $mailstoo, $my_mail, $my_name, $my_replyto, $subject, $content);
                insert_email($_POST['tipo'],$_POST['codigo'],$_POST['ctg_tpt_id'],$_POST['ctg_tpr_id'],$_POST['nomprod'],$mailstoo,$subject,$body,$send,$_POST['id']);

                $sql="SELECT adm_cnf_email_asoc1, adm_cnf_email_asoc2, adm_cnf_email_asoc7, adm_cnf_email_asoc5 FROM adm_config";
                $email_asoc1="";
                $email_asoc2="";
                $email_asoc7="";
                $email_asoc5="";
                echo $sql."<br>";
                $result=$connection->Execute($sql);
                if (!$result->EOF) {
                    $email_asoc1=$result->fields[0];
                    $email_asoc2=$result->fields[1];
                    $email_asoc7=$result->fields[2];
                    $email_asoc5=$result->fields[3];
                }
                switch ($_POST['id']) {
                    case '010106': //EXPEDIENTE FISICO RECIBIDO
                        echo "SENT COPY TO <br>(".$email_asoc5.")";
                        $send= mail_attachment("", "", $email_asoc5, $my_mail, $my_name, $my_replyto, $subject, $content);
                        break;
                    case '010105': ///MUESTRAS RECIBIDAS
                        # code...
                        break;
                        
                    default: //OTROS
                        if (intval($_POST['res_st'])==1){ /// ADMISION
                            echo "SENT COPY TO <br>(".$email_asoc2.")";
                            $send= mail_attachment("", "", $email_asoc2, $my_mail, $my_name, $my_replyto, $subject, $content);
                        }
                        if (intval($_POST['res_st'])==2){ /// FALTANTE
                            echo "SENT COPY TO <br>(".$email_asoc1.")";
                            $send= mail_attachment("", "", $email_asoc1, $my_mail, $my_name, $my_replyto, $subject, $content);
                        }
                        if (intval($_POST['res_st'])==3 || ($hay_rechazo == 1 && $est_id_new == 7) ){ ///RECHAZO
                            echo "SENT COPY TO <br>(".$email_asoc7.")";
                            $email_asoc7.=",monterrosow@gmail.com";
                            $send= mail_attachment("", "", $email_asoc7, $my_mail, $my_name, $my_replyto, $subject, $content);
                        }    
                        break;
                }


                if ($send==1) 
                    $info_email .= "<br>".$arr_label['envio_correo']." ".$mailstoo." ".$arr_label['satisfactorio']; 
                else 
                    $info_email .= "<br>".$arr_label['no_envio_correo']." ".$mailstoo; 
                    // $error = 2;//"no pudo enviar correo a ".$_POST['email'];
            } else 
            	$error = 3;//"No se encontro cuenta de correo";
        }

    }
    
    //echo $sql."<br>[".$error."]<br>[".$info."]<br>";
}//este es del switch de hasta arriba

//sleep(1);

echo "error = [$error]<br>";	

echo "id=".$_POST['id']." est_id_new=".$est_id_new."<br> info_email ".$info_email."<br>";
echo "VENTANILLA ($ventanilla)<br> codigo ".$_POST['codigo'];

if(($_POST['id']=='010101' || $_POST['id']=='010102' || $_POST['id']=='010104' || $_POST['id']=='010103' || $_POST['id']=='010105' || $_POST['id']=='010204' || $_POST['id']=='010203' ||$_POST['id']=='010205' || $_POST['id']=='010404' || $_POST['id']=='010403' || $_POST['id']=='010405') && $est_id_new == 5){
		$connectionADM1 = $connection;
		$connectionVUS1 = $connectionVUS;
		$usuario = $_SESSION['ADMusuario_id'];
		//$_POST['tipo'] = $_POST['tipo'];
		//$_POST['ctg_tpr_id'] = $_POST['ctg_tpr_id'];
        ob_start();
	    include("admitir_tramite.php");
        echo "<br><br>******* COPIAR INGREDIENTES ****** <br><br>";
        include_once ('admitir_ingredientes.php');
        echo "<br><br>******* COPIAR EMPRESAS ****** <br><br>";
        include_once ('admitir_empresas.php');
        local_download($_POST['tipo'],$_POST['ctg_tpt_id'],$_POST['codigo'],$_POST['ctg_tpr_id'],1);           
        $out1 = ob_get_contents();	
        ob_end_clean();
        file_put_contents("admitir_tramite.txt",$out1);     
}
echo "(".$error.")(".$info_email.")";

$log = ob_get_contents();
//ob_end_clean();
// $log_1 = "";
// if (is_file("boleta_guarda_docs.txt"))
//     $log_1 = file_get_contents("boleta_guarda_docs.txt");

// $log_1 = str_replace("<br>","\n",$log) . $log_1;
// file_put_contents("boleta_guarda_docs.txt",$log_1);

$info .= $info_email;

echo "<br>VENTANILLA ($ventanilla))))<br>(".$info.")(".$ventanilla.")";


if ($ventanilla == 1) { //todos menos los de evaluacion porque todavia tiene que hacer otro submit en form_adm_control_etapa_evaluacion linea 2

    $codigo = $_POST['codigo'];

    if ($error != "" && $error != "1") {
        include_once ("send_error_mail.php");
        //$error = 1; 
        $info = "";
    }

    echo "(hay_faltante=$hay_rechazo)(faltante={$_POST['numfal']})(adm_cnf_numfal=$adm_cnf_numfal)($info)($est_id_new)";//2014-07-24

    if ($hay_rechazo == 1 && $_POST['numfal'] >= $adm_cnf_numfal && $est_id_new == 7 && $info != "") {
        $info .= "<br>".$arr_label['rechazada_faltas'];
    }

    ?>
    <script language="javascript" type="text/javascript">
    window.top.window.result_op('<?=$error?>','<?=$info?>','<?=$codigo?>');
    </script>
    <?php
}

die(); // Dont forget this, if not you'll echo the form again.    
?>
