<script type="text/jscript">
function Valtext(e) {
    key = e.keyCode || e.which;
    tecla = String.fromCharCode(key).toLowerCase();
    letras = " áéíóúabcdefghijklmnñopqrstuvwxyz";
    especiales = [8, 37, 39, 46];

    tecla_especial = false
    for(var i in especiales) {
        if(key == especiales[i]) {
            tecla_especial = true;
            break;
        }
    }

    if(letras.indexOf(tecla) == -1 && !tecla_especial)
        return false;
}

function ValNumero(e) {
    key = e.keyCode || e.which;
    tecla = String.fromCharCode(key).toLowerCase();
    letras = "0123456789";
    especiales = [8, 37, 39, 46];

    tecla_especial = false
    for(var i in especiales) {
        if(key == especiales[i]) {
            tecla_especial = true;
            break;
        }
    }

    if(letras.indexOf(tecla) == -1 && !tecla_especial)
        return false;
}
</script>

<?php
include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
	/* Connect To Database*/
	require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
	require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
	$tienda=$_SESSION['estado'];
	if($tienda==""){$tienda="1";}
	$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
	if($action == 'ajax'){
		// escaping, additionally removing everything that could be (html/javascript-) code
		    $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
			$rubro = mysqli_real_escape_string($con,(strip_tags($_REQUEST['rub'], ENT_QUOTES)));
			
	$sql="";
	if ($_GET['q']!="" && $_GET['rub']!="")
	{
		$sql.="select * from products where almacen='1' AND tipo_producto='".$rubro."' AND nombre_producto LIKE '%".$q."%'";
		$count_query = mysqli_query($con, "SELECT count(*) AS numrows from products where  almacen='1' AND tipo_producto='".$rubro."' AND nombre_producto LIKE '%".$q."%'");
	}
	
	else if ($_GET['q']!="" && $_GET['rub']=="")
	{
		$sql.="select * from products where almacen='1' AND nombre_producto LIKE '%".$q."%'";
		$count_query = mysqli_query($con, "SELECT count(*) AS numrows from products where almacen='1' AND nombre_producto LIKE '%".$q."%'");
	}
	else if ($_GET['q']=="" && $_GET['rub']!="")
	{
		$sql.="select * from products where almacen='1' AND tipo_producto='".$rubro."'";
		$count_query = mysqli_query($con, "SELECT count(*) AS numrows from products where almacen='1' AND tipo_producto='".$rubro."'");
	}
	else if ($_GET['q']=="" && $_GET['rub']=="")
	{
		$sql.="select * from products where almacen='1'";
		$count_query = mysqli_query($con, "SELECT count(*) AS numrows from products where almacen='1'");
	}
	
	include 'pagination.php'; //include pagination file
	//pagination variables
	$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
	$per_page = 5; //how much records you want to show
	$adjacents  = 4; //gap between pages after number of adjacents
	$offset = ($page - 1) * $per_page;
	//Count the total number of row in your table*/
	$row= mysqli_fetch_array($count_query);
	$numrows = $row['numrows'];
	$total_pages = ceil($numrows/$per_page);
	$reload = '../nueva_compra.php';
	$sql.=" order by nombre_producto asc LIMIT $offset,$per_page";
	$query = mysqli_query($con, $sql);
	
		//loop through fetched data
		if($numrows>0)
		{
		?>
			<div class="table-responsive">
				<table class="table" style="font-size:11px;">
					<tr  class="warning">
					
						<th>Producto</th>
						<th>Presentacion</th>
						<th>Existencia</th>
       			    	<th><span class="pull-right">Cant</span></th>
						<th><span class="pull-right">Precio $</span></th>
                    	<th><span class="pull-right">Utilidad(%)</span></th>
						<th class='text-center'>Exento</th>
							<th class='text-center' style="width: 36px;">Agregar</th>
					</tr>
					<?php
					while ($row=mysqli_fetch_array($query))
					{
						$id_producto=$row['id_producto'];
						$codigo_producto=$row['codigo_producto'];
						$presen_producto=$row['status_producto'];
						$nombre_producto=$row['nombre_producto'];
						$existencia_producto=$row['existencia'];
	     	           	?>
						<tr>
						
							<td>
								<?php echo $nombre_producto; ?>
							</td>
							<td><?php echo $presen_producto; ?></td>
							<td><?php echo $existencia_producto; ?></td>
							<td class='col-xs-3'><input type="text" class="form-control" style="text-align:right" id="cantidad_<?php echo $id_producto; ?>" value="1" onKeyPress="return ValNumero(event)"></td>
							<td class='col-xs-3'><div class="pull-right"><input type="text" class="form-control" style="text-align:right" id="precio_compra_<?php echo $id_producto; ?>" onKeyPress="return ValNumero(event)"></td>
							<td class='col-xs-2'><div class="pull-right"><input type="text" class="form-control" style="text-align:right" id="utilidad_<?php echo $id_producto; ?>" onKeyPress="return ValNumero(event)"></td>
							<td class='text-center'>
								<label style="font-weight:normal;">
									<input type="checkbox" id="exento_<?php echo $id_producto; ?>" value="1">
								</label>
							</td>
							<td class='text-center'><a class='btn btn-info'href="#" onclick="agregar('<?php echo $id_producto ?>')"><i class="glyphicon glyphicon-plus"></i></a></td>
						</tr>
					<?php
					}
					?>
					<tr>
						<td colspan=8><span class="pull-right"><?php echo paginate($reload, $page, $total_pages, $adjacents);?></span></td>
					</tr>
			  	</table>
			</div>
		<?php
		}
	}
	?>
	