<?php
session_start();
if (!isset($_SESSION['warehouse'])) {
  header("Location: login_warehouse.php");
  exit;
}

<?php
$host = "localhost";
$user = "odmr9632_userdb";
$pass = "@Sukabumi2018";
$db   = "odmr9632_order_db";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
  die("Koneksi gagal: " . $conn->connect_error);
}
?>
if ($conn->connect_error) {
  die("Koneksi gagal: " . $conn->connect_error);
}

$tgl1 = $_GET['tgl1'] ?? '';
$tgl2 = $_GET['tgl2'] ?? '';
$produk_filter = $_GET['produk'] ?? '';
$jenis_filter = $_GET['jenis'] ?? '';

$where = "WHERE 1=1";
if ($tgl1 && $tgl2) $where .= " AND tanggal BETWEEN '$tgl1' AND '$tgl2'";
if ($produk_filter) $where .= " AND nama_produk = '" . $conn->real_escape_string($produk_filter) . "'";
if ($jenis_filter) $where .= " AND jenis = '" . $conn->real_escape_string($jenis_filter) . "'";

$query = "SELECT * FROM riwayat_stok $where ORDER BY tanggal DESC";
$result = $conn->query($query);

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

echo "<table border='1'>";
echo "<tr><th colspan='6'>Riwayat Stok</th></tr>";
echo "<tr><th colspan='6'>Periode: $tgl1 s/d $tgl2</th></tr>";
echo "<tr><th>Tanggal</th><th>Produk</th><th>Jenis</th><th>Jumlah</th><th>Keterangan</th><th>Petugas</th></tr>";

if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($row['tanggal']) . "</td>";
    echo "<td>" . htmlspecialchars($row['nama_produk']) . "</td>";
    echo "<td>" . htmlspecialchars($row['jenis']) . "</td>";
    echo "<td>" . (int)$row['qty'] . "</td>";
    echo "<td>" . htmlspecialchars($row['keterangan']) . "</td>";
    echo "<td>" . htmlspecialchars($row['petugas']) . "</td>";
    echo "</tr>";
  }
} else {
  echo "<tr><td colspan='6'>Tidak ada data.</td></tr>";
}

echo "</table>";
exit;
?>
