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

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax')
{
	// escaping, additionally removing everything that could be (html/javascript-) code
    $q = isset($_REQUEST['q']) ? mysqli_real_escape_string($con, strip_tags($_REQUEST['q'], ENT_QUOTES)) : '';
    $tipo = isset($_REQUEST['tipo']) ? mysqli_real_escape_string($con, strip_tags($_REQUEST['tipo'], ENT_QUOTES)) : '';
    $est = isset($_REQUEST['est']) ? mysqli_real_escape_string($con, strip_tags($_REQUEST['est'], ENT_QUOTES)) : '';

	$wheres = array();
	if ($q != "") {
		$wheres[] = "pf.nombre LIKE '%".$q."%'";
	}
	if ($tipo != "") {
		$wheres[] = "pf.tipo LIKE '%".$tipo."%'";
	}
	if ($_SESSION['rol'] != "gerencia") {
		// Para vendedores, solo mostrar productos finales cuyos componentes estén en su almacén
		$wheres[] = "pf.id IN (SELECT c.id_producto_final FROM composicion_producto_final c JOIN products p ON c.id_producto = p.id_producto WHERE p.almacen = '".$_SESSION['estado']."' GROUP BY c.id_producto_final HAVING COUNT(DISTINCT p.almacen) = 1)";
	}
	if ($est != "") {
		// Si se selecciona una tienda, filtrar productos finales cuyos componentes estén en esa tienda
		$wheres[] = "pf.id IN (SELECT c.id_producto_final FROM composicion_producto_final c JOIN products p ON c.id_producto = p.id_producto WHERE p.almacen = '$est' GROUP BY c.id_producto_final HAVING COUNT(DISTINCT p.almacen) = 1)";
	}

	$sql = "SELECT pf.* FROM producto_final pf";
	if (count($wheres) > 0) {
		$sql .= ' WHERE ' . implode(' AND ', $wheres);
	}
	$sql .= " ORDER BY pf.nombre";

	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_sql = "SELECT count(*) AS numrows FROM producto_final pf";
	if (count($wheres) > 0) {
		$count_sql .= ' WHERE ' . implode(' AND ', $wheres);
	}

	$count_query = mysqli_query($con, $count_sql);
	$row= mysqli_fetch_array($count_query);
	$numrows = $row['numrows'];
	$total_pages = ceil($numrows/$per_page);
	$reload = './nueva_factura.php';

	$sql .= " LIMIT $offset,$per_page";
	$query = mysqli_query($con, $sql) or die(mysqli_error($con));

	// Calcular precio total para cada producto final
	function calcular_precio_final($id_producto_final, $con) {
		$sql_comp = "SELECT c.cantidad, p.precio_venta FROM composicion_producto_final c JOIN products p ON c.id_producto = p.id_producto WHERE c.id_producto_final = '$id_producto_final'";
		$query_comp = mysqli_query($con, $sql_comp);
		$total = 0;
		while ($row_comp = mysqli_fetch_array($query_comp)) {
			$total += $row_comp['cantidad'] * $row_comp['precio_venta'];
		}
		return $total;
	}

	?>
		<div class="table-responsive">
			<table class="table">
				<tr  class="warning">
					<th>Producto</th>
					<th>Cantidad</th>
					<th>Precio Venta</th>
					<th></th>
				</tr>
				<?php
				if ($numrows>0) {
					while ($row = mysqli_fetch_array($query)) {
						$id = $row['id'];
						$nombre = $row['nombre'];
						$precio_total = calcular_precio_final($id, $con);
						?>
						<tr>
							<td><?php echo $nombre; ?></td>
							<td><input type="text" class="form-control input-sm" id="cantidad_<?php echo $id; ?>" value="1" style="width:60px;"></td>
							<td>$<?php echo number_format($precio_total, 2); ?></td>
							<td><button class="btn btn-success btn-sm" onclick="agregar_producto_final(<?php echo $id; ?>, '<?php echo addslashes($nombre); ?>', <?php echo $precio_total; ?>)">+</button></td>
						</tr>
						<?php
					}
				} else {
					?>
					<tr>
						<td colspan="4" class="text-center">No se encontraron productos finales.</td>
					</tr>
					<?php
				}
				?>
				<tr>
					<td colspan=4><span class="pull-right"><?php echo paginate($reload, $page, $total_pages, $adjacents);?></span></td>
				</tr>
			</table>
		</div>
		<?php
}
?>