<?php
include 'conexion.php';

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Inventario_" . date("Ymd_His") . ".xls");

$desde = $_GET['fecha_desde'];
$hasta = $_GET['fecha_hasta'];
$sucursal = $_GET['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();

echo "<table border='1'>";
echo "<tr><th>ID</th><th>Lote ID</th><th>Sucursal</th><th>Stock</th><th>Presentación</th><th>Fecha Ingreso</th></tr>";
while ($row = $result->fetch_assoc()) {
    echo "<tr>
        <td>{$row['id']}</td>
        <td>{$row['lote_id']}</td>
        <td>{$row['sucursal_id']}</td>
        <td>{$row['stock_unidad_base']}</td>
        <td>{$row['presentacion']}</td>
        <td>{$row['fecha_ingreso']}</td>
    </tr>";
}
echo "</table>";
?>
