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

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT r.*, s.name supplier_name, s.email supplier_email, s.phone supplier_phone,
                        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
                        WHERE r.id = ?");
$stmt->execute([$id]);
$ret = $stmt->fetch();
if (!$ret) { flash('error', 'Return not found.'); redirect('return_to_supplier/list.php'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['status'])) {
    $pdo->prepare("UPDATE return_to_supplier SET status=? WHERE id=?")->execute([$_POST['status'], $id]);
    flash('success', 'Status updated.');
    redirect('return_to_supplier/view.php?id=' . $id);
}

$lineStmt = $pdo->prepare("SELECT rti.*, i.name item_name, un.abbreviation unit_abbr FROM return_to_supplier_items rti
                            JOIN items i ON i.id = rti.item_id LEFT JOIN units un ON un.id = i.unit_id
                            WHERE rti.return_id = ?");
$lineStmt->execute([$id]);
$lines = $lineStmt->fetchAll();

$pageTitle = 'Return ' . $ret['return_number'];
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="flex items-center justify-between mb-6">
  <div>
    <h1 class="text-2xl font-bold"><?= e($ret['return_number']) ?></h1>
    <p class="text-slate-500 text-sm">Supplier: <?= e($ret['supplier_name']) ?><?= $ret['po_number'] ? ' · PO ' . e($ret['po_number']) : '' ?> ·
      Recorded by <?= e($ret['created_by_name']) ?> on <?= date('d M Y', strtotime($ret['created_at'])) ?></p>
  </div>
  <?php $badge = ['pending'=>'bg-amber-100 text-amber-700','sent'=>'bg-blue-100 text-blue-700','resolved'=>'bg-emerald-100 text-emerald-700'][$ret['status']]; ?>
  <span class="px-3 py-1 rounded-full text-sm <?= $badge ?> capitalize"><?= $ret['status'] ?></span>
  <a href="print.php?id=<?= $ret['id'] ?>" target="_blank" class="ml-3 text-sm text-blue-600 hover:underline">🖨️ Print / PDF</a>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
  <div class="lg:col-span-2 space-y-6">
    <div class="bg-white rounded-xl shadow-sm border border-slate-200">
      <div class="px-5 py-4 border-b border-slate-200 font-semibold">Returned Items</div>
      <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">Item</th><th class="text-left px-5 py-2">Qty</th>
          <th class="text-left px-5 py-2">Unit Cost</th><th class="text-left px-5 py-2">Value</th>
          <th class="text-left px-5 py-2">Reason</th></tr></thead>
        <tbody>
        <?php $total = 0; foreach ($lines as $l): $val = $l['quantity']*$l['unit_cost']; $total += $val; ?>
          <tr class="border-t border-slate-100">
            <td class="px-5 py-2.5"><?= e($l['item_name']) ?></td>
            <td class="px-5 py-2.5"><?= number_format($l['quantity'],2) ?> <?= e($l['unit_abbr']) ?></td>
            <td class="px-5 py-2.5">₦<?= number_format($l['unit_cost'],2) ?></td>
            <td class="px-5 py-2.5">₦<?= number_format($val,2) ?></td>
            <td class="px-5 py-2.5 text-slate-500"><?= e($l['reason']) ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot><tr class="border-t border-slate-200 font-semibold"><td colspan="3" class="px-5 py-2.5 text-right">Total Value</td><td class="px-5 py-2.5">₦<?= number_format($total,2) ?></td><td></td></tr></tfoot>
      </table></div>
    </div>
    <?php if ($ret['reason']): ?>
      <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
        <p class="text-sm font-semibold mb-1">Overall Reason</p>
        <p class="text-sm text-slate-600"><?= e($ret['reason']) ?></p>
      </div>
    <?php endif; ?>
  </div>

  <div class="space-y-6">
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5 text-sm space-y-2">
      <p><span class="text-slate-500">Supplier email:</span> <?= e($ret['supplier_email'] ?? '—') ?></p>
      <p><span class="text-slate-500">Supplier phone:</span> <?= e($ret['supplier_phone'] ?? '—') ?></p>
    </div>
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
      <p class="text-sm font-semibold mb-3">Update Status</p>
      <form method="POST" class="flex gap-2">
        <select name="status" class="flex-1 border border-slate-300 rounded-lg px-3 py-2 text-sm">
          <?php foreach (['pending','sent','resolved'] as $st): ?>
            <option value="<?= $st ?>" <?= $ret['status']===$st?'selected':'' ?>><?= ucfirst($st) ?></option>
          <?php endforeach; ?>
        </select>
        <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Save</button>
      </form>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
