<?php
include 'conexion.php';

$desde = $_POST['fecha_desde'];
$hasta = $_POST['fecha_hasta'];
$sucursal = $_POST['sucursal_id'];

$sql = "SELECT 
    i.id, i.lote_id, i.sucursal_id, i.stock_unidad_base, i.presentacion,
    l.fechacreacion AS fecha_ingreso
FROM inventario i
JOIN lote l ON i.lote_id = l.id
WHERE DATE(l.fechacreacion) BETWEEN ? AND ?";

$params = [$desde, $hasta];
$types = "ss";

if (!empty($sucursal)) {
    $sql .= " AND i.sucursal_id = ?";
    $types .= "i";
    $params[] = $sucursal;
}

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$datos = [];
while ($row = $result->fetch_assoc()) {
    $datos[] = $row;
}

echo json_encode($datos);
