<?
session_start();
if ($_SESSION['estado'] != "ON")
		{
		?>
		<script>
			parent.location.href = '../index.php';
		</script>
		<? 
		exit();
		}
$id_empresa = $_SESSION['ss_empresa'];
$id_user = $_SESSION['ss_user'];		
?>
<?
include("../conex.php");
$id_salida = $_POST["txtidsal"];
$sql_bs = "SELECT * FROM salida WHERE id = $id_salida";
$res_bs= mysql_query($sql_bs,$enlace);
$cnt_bs = 0;
if (mysql_fetch_object($res_bs))
		{
		$documento_control=mysql_result($res_bs, 0, "documento_control");
		}
		
$sql_scero = "DELETE FROM salida WHERE id = $id_salida";
$res= mysql_query($sql_scero,$enlace);
$sql_bstock = "SELECT * FROM movimiento WHERE id_soe=$id_salida AND entrada_salida_traspaso = 'S'";
$res_bstock = mysql_query($sql_bstock, $enlace);
$cont_bstock = 0;
if($documento_control==null)
  {
while ( mysql_fetch_object($res_bstock))
	{
	$cod_prod = mysql_result($res_bstock, $cont_bstock, "cod_producto");
	$cant_prod = mysql_result($res_bstock, $cont_bstock, "cantidad");
	$sql_ustock = "UPDATE productos SET saldo=(saldo+$cant_prod), u_salida=(u_salida-$cant_prod) WHERE codigo = $cod_prod";
	$res_ustock = mysql_query($sql_ustock, $enlace);
	$cont_bstock += 1;
	}
  }

$sql_mcero = "DELETE FROM movimiento WHERE id_soe = $id_salida AND entrada_salida_traspaso='S' ";
$res= mysql_query($sql_mcero,$enlace);		
	
// selecciono la guia correspondiente al documento de control
	$sql_bguia = "SELECT * FROM salida AS s, tipo_dcto AS td 
			WHERE s.tipo_dcto = td.id AND s.empresa = td.empresa AND s.documento_control = $id_salida AND td.descripcion ='GUIA'";
	$res_bguia= mysql_query($sql_bguia,$enlace);
	$cont_bguia = 0;
	
	while ( mysql_fetch_object($res_bguia))
		{
		$snum_dcto=mysql_result($res_bguia, $cont_bguia, "s.num_dcto");
		$id_guia=mysql_result($res_bguia, $cont_bguia, "s.id");
//		echo $sql_bguia;
		// devuelvo los cargos a la guia
		$sql_cc = "UPDATE pago_cliente SET num_salida = $id_guia, descripcion = 'G $snum_dcto' 
					WHERE num_salida = $id_salida AND tipo = 'C'";
		$res= mysql_query($sql_cc,$enlace);
		//devuelvo los abonos a la guia
		$sql_cc = "UPDATE pago_cliente SET num_salida = $id_guia, descripcion = 'PAGO G $snum_dcto' 
					WHERE num_salida = $id_salida AND tipo = 'A'";		
		$res= mysql_query($sql_cc,$enlace);
		$cont_bguia += 1;
		}
		
	
	
// hago null el documento de control del documento anterior
	$sql_dc = "UPDATE salida SET documento_control=null WHERE documento_control = $id_salida";
	$res= mysql_query($sql_dc,$enlace);
			
if ($cont_bguia==0) //Si no Proviene de Guia
	{
	// elimino los cargos de la factura
	$sql_cc = "DELETE FROM pago_cliente WHERE num_salida = $id_salida AND tipo = 'C'";
	$res= mysql_query($sql_cc,$enlace);
	}
?>
<script>
	alert ("ˇFactura Eliminada!");
	window.top.open('','_parent','');window.top.close();
</script>