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

$username = $_SESSION['username'] ?? 'Guest';
$allowed_roles = ['admin','stores','finance'];
$user_role = $_SESSION['role'] ?? 'guest';

function canManageMenu(){
    global $user_role, $allowed_roles;
    return in_array($user_role, $allowed_roles);
}

// ===================== FETCH DAMAGED GOODS =====================
$damaged_items = $conn->query("
    SELECT dg.*, p.name AS product_name, p.sku, d.name AS department_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
");

?>

<div class="container mt-4">
    <h3 class="text-center">🛑 Damaged Goods Report</h3>
    <hr>
    
    <div class="mb-3">
        <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>

        <a href="export_damaged_excel.php" class="btn btn-success">
            <i class="fa fa-file-excel"></i> Export to Excel
        </a>
        <a href="export_damaged_pdf.php" class="btn btn-danger">
            <i class="fa fa-file-pdf"></i> Export to PDF
        </a>


             <a href="record_damaged.php" class="btn btn-danger mb-3">
    <i class="fa fa-exclamation-triangle"></i>Record Damaged
</a>
    </div>

    <table class="table table-bordered table-striped" style="font-size:14px;">
        <thead class="bg-dark text-white">
            <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>
        </thead>
        <tbody>
            <?php while($row = $damaged_items->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($row['product_name']) ?></td>
                <td><?= htmlspecialchars($row['sku']) ?></td>
                <td><?= htmlspecialchars($row['department_name']) ?></td>
                <td><?= intval($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>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<?php include 'includes/footer.php'; ?>