<?php
require_once __DIR__ . '/../config/config.php';
require_permission('waste.manage');
$u = current_user();

$canViewAll = has_permission($pdo, $u, 'requisitions.view_all');

$sql = "SELECT w.*, u.username recorded_by_name, o.name outlet_name, o.department_id
        FROM waste_records w
        JOIN users u ON u.id = w.recorded_by
        LEFT JOIN outlets o ON o.id = w.outlet_id";
$conditions = [];
$params = [];
if (!$canViewAll) {
    $conditions[] = "(w.recorded_by = ? OR w.location_type = 'main_store' OR o.department_id "
                  . ($u['department_id'] !== null ? "= ?" : "IS NULL") . ")";
    $params[] = $u['id'];
    if ($u['department_id'] !== null) $params[] = $u['department_id'];
}
if ($conditions) { $sql .= " WHERE " . implode(' AND ', $conditions); }
$sql .= " ORDER BY w.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$records = $stmt->fetchAll();

$pageTitle = 'Waste Records';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="flex items-center justify-between mb-6">
  <h1 class="text-2xl font-bold">Waste & Spoilage Records</h1>
  <a href="create.php" class="bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium px-4 py-2 rounded-lg">+ Record Waste</a>
</div>

<div class="overflow-x-auto">
<div class="bg-white rounded-xl shadow-sm border border-slate-200">
  <table class="w-full text-sm">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">Waste No.</th><th class="text-left px-5 py-2">Location</th>
      <th class="text-left px-5 py-2">Recorded By</th><th class="text-left px-5 py-2">Total Value</th>
      <th class="text-left px-5 py-2">Date</th><th class="text-right px-5 py-2">Action</th></tr></thead>
    <tbody>
    <?php foreach ($records as $r): ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5 font-medium"><?= e($r['waste_number']) ?></td>
        <td class="px-5 py-2.5"><?= $r['location_type']==='main_store' ? 'Main Store' : e($r['outlet_name']) ?></td>
        <td class="px-5 py-2.5"><?= e($r['recorded_by_name']) ?></td>
        <td class="px-5 py-2.5">₦<?= number_format($r['total_value'],2) ?></td>
        <td class="px-5 py-2.5 text-slate-500"><?= date('M j, Y', strtotime($r['created_at'])) ?></td>
        <td class="px-5 py-2.5 text-right"><a href="view.php?id=<?= $r['id'] ?>" class="text-blue-600 hover:underline">View →</a></td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($records)): ?><tr><td colspan="6" class="px-5 py-6 text-center text-slate-400">No waste recorded yet.</td></tr><?php endif; ?>
    </tbody>
  </table>
</div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
