<?php include "../index/conexion.inc" ?>
<!doctype html>
<html lang="es">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<!-- Meta, title, CSS, favicons, etc. -->
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Reportes</title>
		<!-- Bootstrap -->
		<link href="../config/dist/css/bootstrap.min.css" rel="stylesheet">
		<!-- DataTable -->
		<script src="../config/datatable/jquery-3.5.1.js"></script>
		<script src="../config/datatable/jquery.dataTables.min.js"></script>
		<script src="../config/datatable/dataTables.searchBuilder.min.js"></script>
		<script src="../config/datatable/dataTables.dateTime.min.js"></script>
		<script src="../config/datatable/dataTables.scroller.min.js"></script>
		<script src="../config/datatable/dataTables.fixedColumns.min.js"></script>
		<script src="../config/datatable/dataTables.select.min.js"></script>
		<script src="../config/datatable/dataTables.buttons.min.js"></script>

		<link rel="stylesheet" href="../config/datatable/jquery.dataTables.min.css" />
		<link rel="stylesheet" href="../config/datatable/scroller.dataTables.min.css" />
		<link rel="stylesheet" href="../config/datatable/searchBuilder.dataTables.min.css" />
		<link rel="stylesheet" href="../config/datatable/dataTables.dateTime.min.css" />
		<link rel="stylesheet" href="../config/datatable/fixedColumns.dataTables.min.css" />
		<link rel="stylesheet" href="../config/datatable/select.dataTables.min.css" />
		<link rel="stylesheet" href="../config/datatable/buttons.dataTables.min.css" />
		<style>
			body {
			font-family: sans-serif;
			font-weight: bold;
			margin: 10px;
			padding: 10px;}
		</style>
		<?php
			if (isset($_POST['Guardar']))
			{
				if (!empty($_POST['lista']))
				{
					$cR01 = $_POST['cV01'];					// Serie
					$cR02 = $_POST['cV02'];					// Pedido
					$cR04 = substr($_POST['cV04'], 0, strripos($_POST['cV04'], '.'));	// Id Vendedor
					foreach($_POST['lista'] AS $selected)
					{
						echo 
						//Crear variables
						$cR03 = $selected;					// Linea
						// conexión
						$servername = $svr_servidor;
						$conectioninfo = array("Database"=>$svr_base, "UID"=>$svr_usuario, "PWD"=>$svr_contrasena, "CharacterSet"=>"UTF-8");
						$conexion = sqlsrv_connect($servername, $conectioninfo);
						if ($conexion == false)
						{
							$mensaje = "Existe un error al intentar conectarse con el servidor...";
						}
						else
						{
							/* ACTUALIZO RUTA */
							$sql = "UPDATE PEDVENTALIN \n"
								  ."SET CODVENDEDOR = ".$cR04." \n"
								  ."WHERE (NUMSERIE = '".$cR01."') AND (NUMPEDIDO = ".$cR02.") AND (NUMLIN = ".$cR03.")";
							$params = array();
							$options = array("scrollable" => SQLSRV_CURSOR_KEYSET);
							// Lanzar la consulta
							$resultado = sqlsrv_query($conexion, $sql);
							if ( $resultado )
							{
								 $something = "Submission successful.";
							}
							else
							{
								 $something = "Submission unsuccessful.";
								 die( print_r( sqlsrv_errors(), true));
							}
							sqlsrv_free_stmt($resultado);
						}
						sqlsrv_close($conexion);
						echo "<script languaje='javascript' type='text/javascript'> self.close(); </script>";
					}
				}
			}
		?>
		<script>
			function datos(cV01)
			{
				opener.document.envios.cV03.value = cV01;
				window.close()
			}
		</script>
	</head>
	<body>
		<div class="main_container">
			<!-- page content -->
			<div class="right_col" role="main">
				<div class="">
					<div class="clearfix"></div>
					<div class="x_panel">
						<div class="x_title">
							<h2>PEDIDO: <?php echo $_GET['id']; ?> | SERIE: <?php echo $_GET['id2']; ?></h2>
							<div class="clearfix"></div>
						</div>
						<div class="x_content">
							<form name="neo99" class="form-vertical" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" onsubmit="return valida_campos(this)">
								<div class="row">
									<table id="example" class="display nowrap" style="width:100%">
										<thead>
											<tr>
												<th><input type="checkbox" name="select_all" value="1" id="example-select-all"></th>
												<th>LINEA</th>
												<th>FABRICANTE</th>
												<th>CODIGO FABRICANTE</th>
												<th>REFERENCIA</th>
												<th>COLOR</th>
												<th>TALLA</th>
												<th>SOLICITADO</th>
												<th>DESPACHADO</th>
												<th>DIFERENCIA</th>
												<th>VENDEDOR</th>
												<th>PASILLO/UBICACION</th>
												<th>DEPARTAMENTO</th>
												<th>PAIS</th>
												<th>SUPEDIDO</th>
												<th>ARTICULO</th>
												<th>DESCRIPCION</th>
												<th>COD.ALMACEN</th>
											</tr>
										</thead>
										<tbody>
											<?php
												// conexión
												$servername = $svr_servidor;
												$conectioninfo = array("Database"=>$svr_base, "UID"=>$svr_usuario, "PWD"=>$svr_contrasena, "CharacterSet"=>"UTF-8");
												$conexion = sqlsrv_connect($servername, $conectioninfo);
												if ($conexion == false)
												{
													$mensaje = "Existe un error al intentar conectarse con el servidor...";
												}
												else
												{
													$cV00 = $_GET['id'];
													$cV01 = $_GET['id2'];
													// CONSULTA SQL
													$sql = "
													         DECLARE @B NVARCHAR(4) \n"
															." DECLARE @E INT \n"
															." DECLARE @BODEGA NVARCHAR(20) \n"
															." SET @E = ( SELECT ISNULL(COUNT(*),0) E FROM JOIN_INV_RESURTIDO WHERE DOCNUM COLLATE Latin1_General_CS_AI = (SELECT SUPEDIDO FROM PEDVENTACAB WHERE NUMSERIE =  '".$cV00."' AND NUMPEDIDO = ".$cV01.") ) \n"
															." SET @B = (SELECT   dbo.JOIN_OBTENERBODEGASUPEDIDO  ((SELECT SUPEDIDO FROM PEDVENTACAB WHERE NUMSERIE =  '".$cV00."' AND NUMPEDIDO = ".$cV01.") )	)	\n"												 
															." IF @B = '01' OR @E = 0 \n"
															." BEGIN\n"
													        ." SELECT PC.NUMSERIE, PC.NUMPEDIDO, PC.SUPEDIDO, PL.NUMLIN, PL.CODARTICULO, A.DESCRIPCION, PL.REFERENCIA, PL.TALLA, PL.COLOR, PL.UNIDADESTOTAL UNIDADESTOTAL,  PL.CODALMACEN, \n"
															."( \n"
															."	SELECT TOP(1)  B.PASILLO+'-'+A.CODUBICACION \n"
															."	FROM JOIN_CAJAMASTER_2 AS A  \n"
															."	INNER JOIN JOIN_UBICACIONES As B ON A.CODUBICACION = B.IDUBICACION \n"
															."	WHERE (A.CODARTICULO = PL.CODARTICULO) AND (A.TALLA = PL.TALLA COLLATE Latin1_General_CS_AI) AND (B.BODEGA = PL.CODALMACEN COLLATE Latin1_General_CS_AI) \n"
															.") PASILLO_UBICACION, PL.CODVENDEDOR, V.NOMVENDEDOR, D.DESCRIPCION AS DEPARTAMENTO, AC.PAIS_FABRICANTE AS PAIS, AC.CODIGO_FABRICANTE , AC.FABRICANTE, \n"
															."  PL.UNID1 SOLICITADO, \n"
															."  ISNULL(ds.des,0) as DESPACHADO, \n"
															."  PL.UNID1 - ISNULL(ds.des,0) as  DIFERENCIA \n"
															."FROM  \n"
															."PEDVENTACAB AS PC  \n"
															."INNER JOIN PEDVENTALIN AS PL ON (PC.NUMSERIE = PL.NUMSERIE) AND (PC.NUMPEDIDO = PL.NUMPEDIDO) \n"
															."INNER JOIN ARTICULOS AS A ON (PL.CODARTICULO = A.CODARTICULO) \n"
															."INNER JOIN ARTICULOSCAMPOSLIBRES AS AC ON (A.CODARTICULO = AC.CODARTICULO)\n"
															."LEFT JOIN VENDEDORES AS V ON (PL.CODVENDEDOR = V.CODVENDEDOR) \n"
															."LEFT JOIN DEPARTAMENTO AS D ON (A.DPTO = D.NUMDPTO)  \n"
															."   left join (select docnum, itemcode, sum( quantity) quantity, U_color, U_talla  from 	JOIN_INV_RESURTIDO group by docnum, itemcode, U_color, U_talla) AS JIR ON JIR.DocNum = PC.SUPEDIDO COLLATE Latin1_General_CS_AI \n"
															." AND JIR.ItemCode = pl.REFERENCIA COLLATE Latin1_General_CS_AI   \n"
															." and jir.U_Talla = pl.TALLA  COLLATE Latin1_General_CS_AI  \n"
															." and jir.u_color = pl.color  COLLATE Latin1_General_CS_AI  \n"
															."  left join (SELECT  DOCUMENTO, CODIGOARTICULO , Talla, color, sum(cantidaddevuelta) DES  FROM JOIN_DEVOLUCIONES \n"
															."	WHERE  MODULO = 22 GROUP BY DOCUMENTO, CODIGOARTICULO, talla, color) as Ds on pc.supedido = ds.documento COLLATE Latin1_General_CS_AI \n"
															."		and pl.codarticulo  = ds.codigoarticulo and pl.talla = ds.talla COLLATE Latin1_General_CS_AI and pl.color = ds.color COLLATE Latin1_General_CS_AI \n"
															."WHERE (PC.NUMSERIE = '".$cV00."') AND (PC.NUMPEDIDO = ".$cV01.") \n"
															."ORDER BY PL.NUMLIN ASC \n"
															."END \n"
															."ELSE \n"
															."BEGIN  \n"
															." SET @B = (SELECT   dbo.JOIN_OBTENERBODEGASUPEDIDO  ((SELECT SUPEDIDO FROM PEDVENTACAB WHERE NUMSERIE =  '".$cV00."' AND NUMPEDIDO = ".$cV01.") )	)	\n"												 
													        ." SELECT PC.NUMSERIE, PC.NUMPEDIDO, PC.SUPEDIDO, PL.NUMLIN, PL.CODARTICULO, A.DESCRIPCION, PL.REFERENCIA, PL.TALLA, PL.COLOR, PL.UNIDADESTOTAL, PL.CODALMACEN, \n"
															."( \n"
															."	SELECT TOP(1)  B.PASILLO+'-'+A.CODUBICACION \n"
															."	FROM JOIN_CAJAMASTER_2 AS A  \n"
															."	INNER JOIN JOIN_UBICACIONES As B ON A.CODUBICACION = B.IDUBICACION \n"
															."	WHERE (A.CODARTICULO = PL.CODARTICULO) AND (A.TALLA = PL.TALLA COLLATE Latin1_General_CS_AI) AND (B.BODEGA = PL.CODALMACEN COLLATE Latin1_General_CS_AI) \n"
															.") PASILLO_UBICACION, PL.CODVENDEDOR, V.NOMVENDEDOR, D.DESCRIPCION AS DEPARTAMENTO, AC.PAIS_FABRICANTE AS PAIS, AC.CODIGO_FABRICANTE , AC.FABRICANTE, \n"
															."  jir.Quantity SOLICITADO, \n"
															."  ISNULL(ds.des,0) as DESPACHADO, \n"
															."  jir.Quantity- ISNULL(ds.des,0) as  DIFERENCIA \n"
															."FROM  \n"
															."PEDVENTACAB AS PC  \n"
															."INNER JOIN PEDVENTALIN AS PL ON (PC.NUMSERIE = PL.NUMSERIE) AND (PC.NUMPEDIDO = PL.NUMPEDIDO) \n"
															."INNER JOIN ARTICULOS AS A ON (PL.CODARTICULO = A.CODARTICULO) \n"
															."INNER JOIN ARTICULOSCAMPOSLIBRES AS AC ON (A.CODARTICULO = AC.CODARTICULO)\n"
															."LEFT JOIN VENDEDORES AS V ON (PL.CODVENDEDOR = V.CODVENDEDOR) \n"
															."LEFT JOIN DEPARTAMENTO AS D ON (A.DPTO = D.NUMDPTO)  \n"
															."   left join (select docnum, itemcode, sum( quantity) quantity, U_color, U_talla  from 	JOIN_INV_RESURTIDO group by docnum, itemcode, U_color, U_talla) AS JIR ON JIR.DocNum = PC.SUPEDIDO COLLATE Latin1_General_CS_AI \n"
															." AND JIR.ItemCode = pl.REFERENCIA COLLATE Latin1_General_CS_AI   \n"
															." and jir.U_Talla = pl.TALLA  COLLATE Latin1_General_CS_AI  \n"
															." and jir.u_color = pl.color  COLLATE Latin1_General_CS_AI  \n"
															."  left join (SELECT  DOCUMENTO, CODIGOARTICULO , Talla, color, sum(cantidaddevuelta) DES  FROM JOIN_DEVOLUCIONES \n"
															."	WHERE  MODULO = 22 GROUP BY DOCUMENTO, CODIGOARTICULO, talla, color) as Ds on pc.supedido = ds.documento COLLATE Latin1_General_CS_AI \n"
															."		and pl.codarticulo  = ds.codigoarticulo and pl.talla = ds.talla COLLATE Latin1_General_CS_AI and pl.color = ds.color COLLATE Latin1_General_CS_AI \n"
															."WHERE (PC.NUMSERIE = '".$cV00."') AND (PC.NUMPEDIDO = ".$cV01.") \n"
															."ORDER BY PL.NUMLIN ASC	END	";
													$pa1 = array();
													$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
													// Lanzar la consulta
													$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
													while($fila = sqlsrv_fetch_array($re1))
													{
														$cV01 = $_GET['id'];
														$cV02 = $_GET['id2'];
														$cV03 = $fila['NUMLIN'];
														echo "
															<tr>
																<td>
																	<input type='checkbox' name='lista[]' value='".$cV03."'>
																</td>
																<td>".$fila['NUMLIN']."</td>
																<td>".$fila['FABRICANTE']."</td>
																<td>".$fila['CODIGO_FABRICANTE']."</td>
																<td>".$fila['REFERENCIA']."</td>
																<td>".$fila['COLOR']."</td>
																<td>".$fila['TALLA']."</td>
																<td>".$fila['SOLICITADO']."</td>
																<td>".$fila['DESPACHADO']."</td>
																<td>".$fila['DIFERENCIA']."</td>
																<td>".$fila['NOMVENDEDOR']."</td>
																<td>".$fila['PASILLO_UBICACION']."</td>
																<td>".$fila['DEPARTAMENTO']."</td>
																<td>".$fila['PAIS']."</td>
																<td>".$fila['SUPEDIDO']."</td>
																<td>".$fila['CODARTICULO']."</td>
																<td>".$fila['DESCRIPCION']."</td>
																<td>".$fila['CODALMACEN']."</td>
																
																
																
																
															</tr>
														";
													}
												}
											?>
										</tbody>
									</table>										
								</div>
								<div class="row">
									<div class="col-sm-3">
										<div class="form-group">
											<label>Seleccione un vendedor</label>
											<div class="input-group">
												<span class="input-group-btn">
													<button type='button' class='btn btn-info' onclick='popup02()'>Go!</i></button>
												</span>
												<input type="text" class="form-control" name="cV04" value="0" readonly>
											</div>
										</div>
									</div>
									<div class='col-sm-2'>
										<button type="submit" class="btn btn-success" name="Guardar">
											<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Guardar/Actualizar
										</button>
									</div>
									<div class='col-sm-1'>
										<button type="button" class="btn btn-danger" onclick="self.close();">
											<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span> Cancelar
										</button>
									</div>
									<div class='col-md-2'>										
										<input type='text' style="display:none" class='form-control' name='cV01' value="<?php echo $_GET['id']; ?>" readonly>
										<input type='text' style="display:none" class='form-control' name='cV02' value="<?php echo $_GET['id2']; ?>" readonly>
									</div>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
			<!-- /page content -->
		</div>
		<!-- Bootstrap -->
		<script src="../config/dist/js/bootstrap.min.js"></script>
		<!-- Custom Theme Scripts -->
		<script src="../config/build/js/custom.min.js"></script>
		<!-- iCheck -->
		<script src="../config/iCheck/icheck.min.js"></script>
	</body>
</html>
<script>
	function valida_campos(f)
	{
		if (this.neo99.cV04.value == '')
		{
			alert("Seleccione un vendedor.");
			this.neo99.cV04.focus();
			return false;
		}
	}
</script>
<script>
	var mipopup;
	function popup01(d1, d2, d3)
	{
		v01 = d1;
		v02 = d2;
		v03 = d3;
		posicion_x=(screen.width/2)-(650/2);
		posicion_y=(screen.height/2)-(650/2)-50;
		mipopup = window.open("reporte_11_ven.php?id="+v01+"&id2="+v02+"&id3="+v03, "winVen", "width=650, Height=650, menubar=0, toolbar=0,directories=0,scrollbars=no,resizable=no,left="+posicion_x+",top="+posicion_y+"");
		mipopup.focus()
	}
</script>
<script>
	var mipopup;
	function popup02()
	{
		posicion_x=(screen.width/2)-(600/2);
		posicion_y=(screen.height/2)-(580/2)-50;
		mipopup = window.open("vendedores.php", "SelecVen", "width=600, Height=580, menubar=0, toolbar=0,directories=0,scrollbars=no,resizable=no,left="+posicion_x+",top="+posicion_y+"");
		mipopup.focus()
	}
</script>
<script>
	$(document).ready(function (){
		var table = $('#example').DataTable({
			scrollY:        "500px",
			scrollX:        true,
			scrollCollapse: true,
			columnDefs: [{
			targets: 0,
			searchable: false,
			orderable: false,
			className: 'dt-body-center'
			}],
			order: [[1, 'asc']],
			pageLength : -1,
			lengthMenu: [[12, 50, 100, -1], [12, 50, 100, 'Todos']],
			
			dom: 'Qlfrtip'
		});

		// Handle click on "Select all" control
		$('#example-select-all').on('click', function(){
		  // Get all rows with search applied
		  var rows = table.rows({ 'search': 'applied' }).nodes();
		  // Check/uncheck checkboxes for all rows in the table
		  $('input[type="checkbox"]', rows).prop('checked', this.checked);
		});

		// Handle click on checkbox to set state of "Select all" control
		$('#example tbody').on('change', 'input[type="checkbox"]', function(){
		  // If checkbox is not checked
		  if(!this.checked){
			 var el = $('#example-select-all').get(0);
			 // If "Select all" control is checked and has 'indeterminate' property
			 if(el && el.checked && ('indeterminate' in el)){
				// Set visual state of "Select all" control
				// as 'indeterminate'
				el.indeterminate = true;
			 }
		  }
		});
	});
</script>