<?php

	/*-------------------------
	Autor: Obed Alvarado
	Web: obedalvarado.pw
	Mail: info@obedalvarado.pw
	---------------------------*/
	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
	
	
	$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
	if (isset($_GET['id'])){
		$numero_factura=intval($_GET['id']);
		$del1="update facturas set estado_factura = 3 where numero_factura='".$numero_factura."'";
		//$del2="delete from detalle_factura where numero_factura='".$numero_factura."'";
		if ($delete1=mysqli_query($con,$del1)){
			?>
			<div class="alert alert-success alert-dismissible" role="alert">
			  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			  <strong>Aviso!</strong> Bonificacion cancelada exitosamente
			</div>
			<?php 
		}else {
			?>
			<div class="alert alert-danger alert-dismissible" role="alert">
			  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
			  <strong>Error!</strong> No se pudo cancelar la bonificacion
			</div>
			<?php
			
		}
	}
	if($action == 'ajax'){
		// escaping, additionally removing everything that could be (html/javascript-) code
            
         if ( $_SESSION['permiso'] == 1) {
            
			$q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
			$sTable = "facturas, clientes, mayorista,zona,users";
			$sWhere = "";
			$sWhere.=" WHERE facturas.id_cliente=clientes.id_cliente 
						and facturas.id_mayorista=mayorista.id_mayorista
						and facturas.zona=zona.id_zona
						and clientes.ejecutivo_cliente = users.user_id
						and facturas.estado_factura = 1
						
											";
       }
		  elseif ( $_SESSION['permiso'] == 4) {
            
			$q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
			$sTable = "facturas, clientes, mayorista,zona,users";
			$sWhere = "";
			$sWhere.=" WHERE facturas.id_cliente=clientes.id_cliente 
						and facturas.id_mayorista=mayorista.id_mayorista
						and facturas.zona=zona.id_zona
						and clientes.ejecutivo_cliente = users.user_id
						and facturas.estado_factura = 1
						
											";
         }else {  
		  
             
			$q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
			$sTable = "facturas, clientes, mayorista,zona,users";
			$sWhere = "";
			$sWhere.=" WHERE facturas.id_cliente=clientes.id_cliente 
					and facturas.id_mayorista=mayorista.id_mayorista
					and facturas.zona=zona.id_zona
					and clientes.ejecutivo_cliente = users.user_id
					and facturas.estado_factura = 1
					and users.user_id='$_SESSION[user_id]'";
         }
                 
                 
                 
                 
		if ( $_GET['q'] != "" )
		{
			$sWhere.= " and  (clientes.nombre_cliente like '%$q%' or facturas.numero_factura like '%$q%' 
		                or clientes.ejecutivo_cliente like '%$q%' or facturas.fecha_factura like '%$q%'
						or facturas.condiciones like '%$q%' or facturas.condiciones2 like '%$q%'
						or users.firstname like '%$q%' or users.lastname like '%$q%'
						   )";
			
		}
		
		$sWhere.=" order by facturas.id_factura desc";
		include 'pagination.php'; //include pagination file
		//pagination variables
		$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
		$per_page = 10; //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*/
		$count_query   = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable  $sWhere");
		$row= mysqli_fetch_array($count_query);
		$numrows = $row['numrows'];
		$total_pages = ceil($numrows/$per_page);
		$reload = './facturas.php';
		//main query to fetch the data
		$sql="SELECT * FROM  $sTable $sWhere LIMIT $offset,$per_page";
		$query = mysqli_query($con, $sql);
		//loop through fetched data
		if ($numrows>0){
			echo mysqli_error($con);
			?>
			<div class="table-responsive">
			<tr class='text-center'>
			  <table class="table">
				<tr  class="info">
					<th height="20" align="center" valign="middle"><small>FOLIO</small></th>
					<th height="20" align="center" valign="middle"><small>PERIODO</small></th>
					<th height="20" align="center" valign="middle"><small>BIMESTRE</small></th>
					<th height="20" align="center" valign="middle"><small>FECHA</small></th>
					<th height="20" align="center" valign="middle"><small>EJECUTIVO</small></th>
					<th height="20" align="center" valign="middle"><small>P.V.</small></th>
					<th height="20" align="center" valign="middle"><small>MAYORISTA</small></th>
					<th height="20" align="center" valign="middle"><small>ESTATUS</small></th>
					<th height="20" align="center" valign="middle"><small>TOTAL</small></th>
					<th height="20" align="center" valign="middle"><small>ACCION</small></th>
					
					
				</tr>
				</tr>
				<?php
				$sumadortototalventa=0;
				while ($row=mysqli_fetch_array($query)){
						$id_factura=$row['id_factura'];
					   

						$numero_factura= $row['numero_factura'];
						$fecha=date("d/m/Y", strtotime($row['fecha_factura']));
						$observaciones=$row['observaciones'];
						$observaciones2=$row['observaciones2'];
						$zona=$row['zona'];
						$nombre_cliente=$row['nombre_cliente'];
						$poblacion_cliente=$row['poblacion_cliente'];
						$ejecutivo_cliente=$row['firstname']." ".$row["lastname"];
						//$nombre_vendedor=$row['firstname']." ".$row['lastname'];
						$nombre_mayorista=$row['nombre_mayorista'];
						$nombre_zona=$row['nombre_zona'];
						$estado_factura=$row['estado_factura'];
						//$condiciones=$row['condiciones'];
						if ($estado_factura==1){$text_estado="POR BONIFICAR";$label_class='label-warning';}
						elseif ($estado_factura==2){$text_estado="BONIFICADA";$label_class='label-success';}
						elseif ($estado_factura==3){$text_estado="CANCELADA";$label_class='label-danger';}
						
						
						//else{$text_estado="Pagada";$label_class='label-warning';}
						$total_venta=$row['total_venta'];
						//($total_ventaSiva= $total_venta / 1.16) /100;
					  
						//$total_con_porcentaje = number_format ($total_venta)." %";; 
						
						
					?>
					<tr class='text-center'>
						<!-- 
						<td height="20" align="center" valing="middle">
							<input type="checkbox" name="column-check-factura" value="<?php echo $id_factura; ?>">
						</td>
						-->
						<th height="20" align="center" valign="middle"><small><?php echo 'B'. $numero_factura; ?></small></th>
						<th height="20" align="center" valign="middle"><small><?php echo $observaciones2; ?></small></th>
						<th height="20" align="center" valign="middle"><small><?php echo $observaciones; ?></small></th>
						<th height="20" align="center" valign="middle"><small><?php echo $fecha; ?></small></th>
						<th height="20" align="center" valign="middle"><small><?php echo $ejecutivo_cliente; ?></small></th>	
						<th height="20" align="center" valign="middle"><small><?php echo $nombre_cliente; ?> <br> <?php echo $poblacion_cliente;?></small></th>	
						<th height="20" align="center" valign="middle"><small><?php echo $nombre_mayorista; ?></small></th>	
						<th height="20" align="center" valign="middle"><span class="label <?php echo $label_class;?>"><?php echo $text_estado; ?></span></th>		
						<th height="20" align="center" valign="middle"><small><?php echo number_format ($total_venta); ?></small></th>
										
						<td class="text-left">
							<a href="editar_factura.php?id_factura=<?php echo $id_factura;?>" class='btn btn-primary' title='Editar Bonificacion' ><i class="glyphicon glyphicon-edit"></i></a> 
							<a href="#" class='btn btn-primary' title='Cancelar Bonificacion' onclick="eliminar('<?php echo $numero_factura; ?>')"><i class="glyphicon glyphicon-remove"></i> </a>
												
													<!--<a href="#" class='btn btn-default' title='Descargar Bonificacion' onclick="imprimir_factura('<?php echo $id_factura;?>');"><i class="glyphicon glyphicon-download"></i></a>-->
						</td>
						
					</tr>
					<?php
				}
				?>
				<tr>
					<td colspan=7><span class="pull-right"><?php
					 echo paginate($reload, $page, $total_pages, $adjacents);
					?></span></td>
				</tr>
			  </table>
			</div>
			<?php
		}
	}
?>