<?php include "../index/conexion.inc" ?>
<?php include "../index/validacion.php" ?>
<!doctype html>
<html lang="es">
	<head>
	<?php include '../index/head.php'; ?>
		<?php
			$cVD01 = 0;
			$cVD02 = 0;
			$cVD03 = "";
			$cVD04 = "";
			if (isset($_POST['Generar']))
			{
				//Crear variables
				$cR01 = $_POST['desde'];		// Numero de cajas master por crear
				$cVD04 = $_POST['BodegaID'];		// Numero de cajas master por crear
				// 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
				{
					// Consulta BASE TIPO Y UNIDADES
					$sql = "DECLARE @sV01 INT \n"
						  ."DECLARE @sV02 VARCHAR(2) \n"
						  ."DECLARE @sV03 INT \n"
						  ."DECLARE @sV04 VARCHAR(10) \n"
						  ."DECLARE @sv05 datetime \n"
						  ."SET @sV01 = YEAR(GETDATE()) \n"
						  ."SET @sV02 = RIGHT(CONVERT(VARCHAR, @sV01),2) \n"
						  ."SET @sv05 = (SELECT GETDATE()) \n"
						  ."SET @sV03 = (SELECT TOP(1) F.Id FROM \n"
						  ."( \n"
						  ."	SELECT TOP(1) CONVERT(INT, CODIGOBARRAS) AS Id, FECHAREGISTRO FROM JOIN_CODBARCAJMAS WHERE (YEAR(FECHAREGISTRO) = @sV01) AND (LEN(CODIGOBARRAS) = 8) ORDER BY CONVERT(INT, CODIGOBARRAS) DESC \n"
						  .") AS F ORDER BY Id DESC) \n"
						  ."IF (ISNULL(@sV03, 0) = 0) BEGIN \n"
						  ."	SET @sV04 = @sV02 + RIGHT('000000' + CONVERT(VARCHAR(8), (ISNULL(@sV03, 0) + 1)), 6) \n"
						  ."END ELSE BEGIN \n"
						  ."	IF (ISNULL(@sV03, 0) + 1 = 1) BEGIN \n"
						  ."		SET @sV04 = ISNULL(@sV03, 0) + 1 \n"
						  ."	END ELSE BEGIN \n"
						  ."		SET @sV04 = @sV02 + RIGHT('000000' + CONVERT(VARCHAR(8), (ISNULL(@sV03, 0) + 1)), 6) \n"
						  ."	END \n"
						  ."END \n"
						  ."SELECT CONVERT(INT, @sV04) AS IId, CONVERT(VARCHAR(30), @sv05, 121) as FECHA";
					$pa1 = array();
					$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
					$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
					while($fila1 = sqlsrv_fetch_array($re1))
					{
						$cVD01 = $fila1['IId'];
						$cVD02 = ($cVD01 + $cR01) - 1;
						$cVD03 = $fila1['FECHA'];
						for ($i = $cVD01; $i <= $cVD02; $i++)
						{
							$cR01 = $i;
							$cR02 = "CODE128";
							$cR03 = "True";
							$cR04 = "";
							$cR05 = $_SESSION["mLogin"];
							/* INSERTO NUEVAS CAJAS MASTER */
							$sql = "INSERT INTO JOIN_CODBARCAJMAS (CODIGOBARRAS, FORMATO, DISPONIBLE, ACTIVIDAD, FECHAREGISTRO, USUARIOREGISTRO, USUARIOMODIFICACION) VALUES \n"
								  ."('$cR01', '$cR02', '$cR03', '$cR04', '$cVD03', '$cR05', '$cR05')";
							$pa1 = array();
							$op1 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
							$re1 = sqlsrv_query($conexion, $sql, $pa1, $op1);
							if ( $re1 )
							{
								//$something = "Submission successful.";
								$sql2 = "INSERT INTO JOIN_CAJAMASTER_UBICACION (CODIGOBARRAS,UBICACION,FECHAALTA) VALUES "
										."('$cR01','$cVD04','$cVD03')";
								$pa11 = array();
								$op11 = array("scrollable" => SQLSRV_CURSOR_KEYSET);
								$re11 = sqlsrv_query($conexion, $sql2, $pa11, $op11);
								if($re11){
									$something = "Submission successful.";
								}else{
									$something = "Submission unsuccessful.";
								die( print_r( sqlsrv_errors(), true));
								}

							}
							else
							{
								$something = "Submission unsuccessful.";
								die( print_r( sqlsrv_errors(), true));
							}
						}
					}
					sqlsrv_free_stmt($re1);
					sqlsrv_close($conexion);
				}
			}
		?>
		<script language="javascript">
			function recargar()
			{
				var v01 = $('input[name=desde]').val();
				var v02 = $('input[name=hasta]').val();
				$('#recargado').html('<div class="d-flex justify-content-center"><img src="../images/loader.gif" width="150" alt="loading"/><br/>Un momento, por favor...</div>');
				$.post("generacajamaster_etq.php", { v1:v01, v2:v02}, function(data){$("#recargado").html(data);});
			}
		</script>
		<style>
			#boton{display:none;}
		</style>
	</head>
	<body class="nav-md" onLoad="recargar();">
		<div class="container body">
			<div class="main_container">
				<?php include '../index/body.php'; ?>
				<div class="right_col" role="main">
				<div class="">
					<!-- page content -->
					<div class="clearfix"></div>
					<div class="row">
						<div class="col-md-12 col-sm-12 col-xs-12">
							<form name="neo02" class="form-vertical" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" onsubmit="return valida_campos(this)">
								<div class="row">
									<div class="col-sm-4">
										<div class="form-group">
											<label>Cuantas cajas master desea crear?</label>
											<?php
												if ($cVD01 == 0)
												{
													echo"<input type='number' class='form-control' value='".$cVD01."' name='desde' autofocus>";
												}
												else
												{
													echo"<input type='number' class='form-control' value='".$cVD01."' name='desde' readonly>";
													
												}
											?>
										</div>
										</div>
										<div class="col-sm-4">		
											<div class="form-group">
												<label>Seleccione una bodega destino: </label>
												<select name="BodegaID" class='form-control'>
													<option value="6324" selected>01</option>
													<option value="201">20</option>
													<option value="7871">21</option>
												</select>
											</div>
										</div>
									<div class="col-sm-1">
										<div class="form-group">
											<input type="number" style="display:none" class="form-control" value="<?php echo $cVD02; ?>" name="hasta" readonly>
										</div>
									</div>
									<div class="col-md-4">
										<div class="form-group">
											<?php
												if ($cVD01 == 0)
												{
													echo "
													<button type='botton' class='btn btn-dark' name='Generar'>
														<span class='glyphicon glyphicon-briefcase' aria-hidden='true'></span> Generar cajas master
													</button>
													";
												}
												else
												{
													echo "
													<a href='generacajamaster.php'>
														<button type='botton' class='btn btn-success' name='Nuevo'>
															<span class='glyphicon glyphicon-file' aria-hidden='true'></span> Nuevo
														</button>
													</a>
													";
												}
											?>
										</div>
									</div>
								</div>
							</form>
							<div class="row">
								<form name="neo" class="form-vertical" method="POST" action="impresion.php?id=1" enctype="multipart/form-data" target="_blank">
									<div class="col-xs-12" id="recargado">
									</div>
								</form>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php include '../index/footer.php'; ?>
		<?php include '../index/fbody.php'; ?>
	</body>
</html>
<script>
	function valida_campos(f)
	{
		if (this.neo02.desde.value <= 0)
		{
			alert("Ingrese el número de cajas master.");
			this.neo02.desde.focus();
			return false;
		}
		if (this.neo02.hasta.value == 0)
		{
			if (this.neo02.desde.value > 100)
			{
				alert("El límite por cajas es de 100.");
				this.neo02.desde.focus();
				return false;
			}
		}
	}
</script>