<?php
include 'db.php';
include 'includes/auth.php';

// Fetch all damaged goods
$damaged = $conn->query("
    SELECT dg.*, p.name AS product_name, p.sku, d.name AS dept_name 
    FROM damaged_goods dg
    JOIN products p ON dg.product_id = p.id
    JOIN departments d ON dg.department_id = d.id
    ORDER BY dg.reported_at DESC
");

// Set headers for Excel download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=damaged_goods_".date('Y-m-d').".xls");
header("Pragma: no-cache");
header("Expires: 0");

echo "<table border='1'>";
echo "<tr>
        <th>Product</th>
        <th>SKU</th>
        <th>Department</th>
        <th>Quantity</th>
        <th>Reason</th>
        <th>Reported By</th>
        <th>Reported At</th>
      </tr>";

while($row = $damaged->fetch_assoc()){
    echo "<tr>
            <td>".htmlspecialchars($row['product_name'])."</td>
            <td>{$row['sku']}</td>
            <td>".htmlspecialchars($row['dept_name'])."</td>
            <td>{$row['quantity']}</td>
            <td>".htmlspecialchars($row['reason'])."</td>
            <td>".htmlspecialchars($row['reported_by'])."</td>
            <td>".date('Y-m-d H:i', strtotime($row['reported_at']))."</td>
          </tr>";
}
echo "</table>";
exit;
?>