<?php
require_once __DIR__ . '/../config/config.php';
require_permission('return_to_supplier.manage');

$returns = $pdo->query("SELECT r.*, s.name supplier_name, u.username created_by_name, po.po_number
                         FROM return_to_supplier r
                         JOIN suppliers s ON s.id = r.supplier_id
                         JOIN users u ON u.id = r.created_by
                         LEFT JOIN purchase_orders po ON po.id = r.po_id
                         ORDER BY r.created_at DESC")->fetchAll();

$pageTitle = 'Return to Supplier';
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">Return to Supplier</h1>
  <a href="create.php" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">+ New Return</a>
</div>

<div class="bg-white rounded-xl shadow-sm border border-slate-200">
  <div class="overflow-x-auto"><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">Return No.</th><th class="text-left px-5 py-2">Supplier</th>
      <th class="text-left px-5 py-2">Related PO</th><th class="text-left px-5 py-2">Reason</th>
      <th class="text-left px-5 py-2">Status</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 ($returns as $r): ?>
      <?php $badge = ['pending'=>'bg-amber-100 text-amber-700','sent'=>'bg-blue-100 text-blue-700','resolved'=>'bg-emerald-100 text-emerald-700'][$r['status']]; ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5 font-medium"><?= e($r['return_number']) ?></td>
        <td class="px-5 py-2.5"><?= e($r['supplier_name']) ?></td>
        <td class="px-5 py-2.5"><?= e($r['po_number'] ?? '—') ?></td>
        <td class="px-5 py-2.5"><?= e($r['reason']) ?></td>
        <td class="px-5 py-2.5"><span class="px-2 py-0.5 rounded-full text-xs <?= $badge ?> capitalize"><?= $r['status'] ?></span></td>
        <td class="px-5 py-2.5 text-slate-500"><?= date('d M 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($returns)): ?><tr><td colspan="7" class="px-5 py-6 text-center text-slate-400">No returns recorded yet.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
