<?php
/* Connect To Database*/
include('is_logged.php');
require_once ("../config/db.php");
require_once ("../config/conexion.php");

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if (isset($_GET['id']))
{
	$id_movimiento=intval($_GET['id']);
	$query=mysqli_query($con, "select * from movimientos where movimiento.id_movimiento='".$id_movimiento."'");
	$count=mysqli_num_rows($query);
	if ($count>0)
	{
		$delete1=mysqli_query($con,"DELETE FROM movimientos WHERE id_movimiento='".$id_movimiento."'")
		$delete2=mysqli_query($con,"DELETE FROM detalle_movimiento WHERE id_movimiento='".$id_movimiento."'")
		
		if ($delete1)
		{
		?>
			<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> Datos eliminados 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> Lo siento algo ha salido mal intenta nuevamente.
			</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 eliminar éste  cliente. Existen facturas o Cotizaciones vinculadas. 
		</div>
	<?php
	}
}
if($action == 'ajax')
{

$desde = $_POST['desde'];
$hasta = $_POST['hasta'];
$tienda = $_POST['tienda'];		
$sTable = "despachos";
$sWhere = " ";

if($_POST['desde']!="" && $_POST['hasta']!="" && $_POST['tienda']=="") 
{
	$sWhere.= "WHERE (fecha BETWEEN '$desde' AND '$hasta') AND factura='Movimiento Interno' ";
}
else if($_POST['desde']!="" && $_POST['hasta']=="" && $_POST['tienda']=="")
{
	$sWhere.= "WHERE fecha = '$desde' AND factura='Movimiento Interno' ";
}
else if($_POST['desde']=="" && $_POST['hasta']!="" && $_POST['tienda']=="")
{
	$sWhere.= "WHERE fecha = '$hasta' AND factura='Movimiento Interno' ";
}

else if($_POST['tienda']!="" && $_POST['desde']=="" && $_POST['hasta']=="") 
{
	$sWhere.= "WHERE (destino = '$tienda') AND factura='Movimiento Interno' ";
}
else if($_POST['tienda']!="" && $_POST['desde']!="" && $_POST['hasta']=="") 
{
	$sWhere.= "WHERE (destino = '$tienda') AND fecha = '$desde' AND factura='Movimiento Interno' ";
}
else if($_POST['tienda']!="" && $_POST['desde']=="" && $_POST['hasta']!="") 
{
	$sWhere.= "WHERE (destino = '$tienda') AND fecha = '$hasta'  AND factura='Movimiento Interno'";
}
else if($_POST['tienda']!="" && $_POST['desde']!="" && $_POST['hasta']!="") 
{
	$sWhere.= "WHERE (destino = '$tienda') AND (fecha BETWEEN '$desde' AND '$hasta') AND factura='Movimiento Interno'";
}
else
{
	$sWhere.= "WHERE factura='Movimiento Interno'";	
}
$sWhere.= "ORDER BY id_despacho ASC";
include 'pagination.php'; //include pagination file
//pagination variables
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
$per_page = 30; //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 = './despachos.php';
//main query to fetch the data
$sql="SELECT * FROM  $sTable $sWhere LIMIT $offset,$per_page";
$query = mysqli_query($con, $sql);
?>

<div class="table_responsive">
	<table class="table" align="center">
		<tr>
			<th>Desachos Realizados:</th>
			<th class="pull-left"><?php echo $numrows;?></th>
		    <th width="80%"></th>
		</tr>
	</table>
</div>
<table class="table-responsive" align="center">
	<table class="table">
    	<tr>
        	<td colspan="6" class="text-right">
     			<a href="imp_despachos.php?tienda=<?php echo $tienda;?>"><button type="button" class="btn btn-info"><span class="glyphicon glyphicon-print" ></span> Imprimir</button></a>
            </td>
        </tr>
		<tr  class="info">
			<td>#</strong></td> 
    		<th>Fecha Despacho</th>
    		<th>Envio</th>
			<th>Recibio</th>
			<th>Estatus</th>
			<th>Acciones</th>
		</tr>
        <?php
		$item=0;
		$total=0;
		if($numrows>0)
		{
			while ($despacho=mysqli_fetch_array($query))
			{
				$envio=$despacho['usuario'];
				$recibio=$despacho['destino'];
				$responsable=$despacho['responsable'];
				$cedula_res=$despacho['cedula'];
				$marca_vehiculo=$despacho['marca_vehiculo'];
				$tipo_vehiculo=$despacho['tipo_vehiculo'];
				$placa_vehiculo=$despacho['placa_vehiculo'];
				$fecha=$despacho['fecha'];
				$num=$despacho['numero_despacho'];
				$factura=$despacho['factura'];
				$estatus=$despacho['estatus'];
				$id_despacho=$despacho['id_despacho'];
				$item=$item+1;
				?>
				<input type="hidden" value="<?php echo $num;?>" id="num_despa<?php echo $id_despacho;?>">
				<input type="hidden" value="<?php echo $recibio;?>" id="destino<?php echo $id_despacho;?>">
				<tr>
    				<td><?php echo $item;?></td>
					<td><?php echo $fecha;?></td>
		    		<td><?php echo $envio;?></td>
		    		<td><?php echo $recibio;?></td>
					<td><?php echo $estatus;?></td>
		    		<td>
					<?php 
					if($_SESSION['rol']=="gerencia" || $_SESSION['rol']=="supervisor")
					{ 
					?>
						<a href="ver_despacho.php?id_despacho=<?php echo $id_despacho;?>" class='btn btn-default' title='Ver Detalle' ><i class="glyphicon glyphicon-eye-open"></i></a>
					<?php
						if($estatus=="Sin Despacho")
						{
						?>	
							<a href="editar_despacho.php?id_despacho=<?php echo $id_despacho;?>" class='btn btn-default' title='Editar' ><i class="glyphicon glyphicon-edit"></i></a>
							<a href="#" class='btn btn-default' title='Anular despacho' onclick="eliminar('<?php echo $id_despacho; ?>')"><i class="glyphicon glyphicon-trash"></i></a>
						<?php 
						}
						$estado_usu=$_SESSION['estado'];
						$des=mysqli_query($con,"SELECT * FROM despachos where id_despacho='$id_despacho' AND usuario='$estado_usu'");
						$resp_des=mysqli_fetch_array($des);
						$responsable=$resp_des['responsable'];
						$estatus_bd=$resp_des['estatus'];
						if(mysqli_num_rows($des)>0 && $responsable!="")
						{
						
							if($estatus_bd=="Sin Despacho")
							{
							?>	<a href="#" class='btn btn-default' onclick="obtener_datos('<?php echo $id_despacho;?>',2);" data-toggle="modal" data-target="#myModa14" data-id="<?php echo $id_despacho ?>">Editar Datos del Despacho</a>
							<?php
							}
							?>
							<a href="#" class='btn btn-default' title='Ver Nota de Entrega y Guia de Despacho' onclick="imprimir_guia('<?php echo $id_despacho;?>');"><i class="glyphicon glyphicon-download"></i></a>
						<?php
						}
						else
						{
						?>
							<a href="#" class='btn btn-default' onclick="obtener_datos('<?php echo $id_despacho;?>',2);" data-toggle="modal" data-target="#myModa14" data-id="<?php echo $id_despacho ?>">Datos del Despacho</a>
						<?php 
						}
					}
					?>
					</td>
    			</tr>
		        <?php
				}
			}
			else
			{
			?>
				<tr>
					<td colspan="6">No se encontraron resultados</td>
				</tr>
		    <?php 
			} 
		    ?>
		    <tr>
				<td colspan=6><span class="pull-right"><?php echo paginate($reload, $page, $total_pages, $adjacents);?></span></td>
			</tr>
		</table>
	</table>
	
<?php 
} 
?>
		