<?php
require_once __DIR__ . '/../config/config.php';
require_login();

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT pr.*, u.username requester, d.name dept_name, o.name outlet_name
                        FROM purchase_requisitions pr
                        JOIN users u ON u.id = pr.requested_by
                        LEFT JOIN departments d ON d.id = pr.department_id
                        LEFT JOIN outlets o ON o.id = pr.outlet_id
                        WHERE pr.id = ?");
$stmt->execute([$id]);
$pr = $stmt->fetch();
if (!$pr) { die('Requisition not found.'); }
if (!can_view_requisition($pdo, current_user(), $pr['department_id'], $pr['requested_by'])) {
    die('You do not have access to this requisition.');
}

$lineStmt = $pdo->prepare("SELECT pri.*, i.name item_name, un.abbreviation unit_abbr, s.name supplier_name
                            FROM purchase_requisition_items pri
                            JOIN items i ON i.id = pri.item_id
                            LEFT JOIN units un ON un.id = i.unit_id
                            LEFT JOIN suppliers s ON s.id = pri.supplier_id
                            WHERE pri.pr_id = ?");
$lineStmt->execute([$id]);
$lines = $lineStmt->fetchAll();

$logStmt = $pdo->prepare("SELECT al.*, u.username, u.role, u.signature_path FROM approval_logs al JOIN users u ON u.id=al.approver_id
                           WHERE module='purchase_requisition' AND reference_id=? ORDER BY al.created_at");
$logStmt->execute([$id]);
$logs = $logStmt->fetchAll();

$printTitle = 'Purchase Requisition';
$printSubtitle = $pr['pr_number'];
include __DIR__ . '/../includes/print_header.php';
?>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm mb-6">
  <div><span class="text-slate-500">Requested By:</span> <?= e($pr['requester']) ?></div>
  <div><span class="text-slate-500">Date:</span> <?= date('d M Y', strtotime($pr['created_at'])) ?></div>
  <div><span class="text-slate-500">Department/Outlet:</span> <?= e($pr['outlet_name'] ?? $pr['dept_name'] ?? '—') ?></div>
  <div><span class="text-slate-500">Status:</span> <span class="capitalize"><?= e($pr['status']) ?></span></div>
</div>

<div class="overflow-x-auto"><table class="w-full text-sm mb-6 border-collapse">
  <thead><tr class="border-b-2 border-slate-800 text-left text-xs uppercase text-slate-500">
    <th class="py-2">Item</th><th class="py-2">Qty</th><th class="py-2">Est. Unit Cost</th><th class="py-2">Line Total</th><th class="py-2">Supplier</th></tr></thead>
  <tbody>
  <?php foreach ($lines as $l): ?>
    <tr class="border-b border-slate-100">
      <td class="py-2"><?= e($l['item_name']) ?></td>
      <td class="py-2"><?= number_format($l['quantity'],2) ?> <?= e($l['unit_abbr']) ?></td>
      <td class="py-2">₦<?= number_format($l['estimated_unit_cost'],2) ?></td>
      <td class="py-2">₦<?= number_format($l['quantity']*$l['estimated_unit_cost'],2) ?></td>
      <td class="py-2"><?= e($l['supplier_name'] ?? '—') ?></td>
    </tr>
  <?php endforeach; ?>
  </tbody>
  <tfoot><tr class="font-semibold"><td colspan="3" class="py-2 text-right">Total Estimated Cost</td><td class="py-2">₦<?= number_format($pr['total_estimated_cost'],2) ?></td><td></td></tr></tfoot>
</table></div>

<?php if ($pr['notes']): ?><p class="text-sm mb-6"><span class="text-slate-500">Notes:</span> <?= e($pr['notes']) ?></p><?php endif; ?>

<h2 class="text-sm font-bold uppercase tracking-wide text-slate-600 mb-3 mt-8">Approval Signatures</h2>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
  <?php foreach ($logs as $lg): ?>
    <div class="border border-slate-200 rounded-lg p-4">
      <p class="text-xs text-slate-500 uppercase">Stage <?= $lg['stage'] ?> · <?= e(ucfirst($lg['role'])) ?></p>
      <div class="h-14 flex items-end my-2">
        <?php if (!empty($lg['signature_path'])): ?>
          <img src="<?= SIGNATURE_UPLOAD_URL . e($lg['signature_path']) ?>" class="h-12">
        <?php else: ?>
          <span class="text-slate-300 text-xs italic">No signature on file</span>
        <?php endif; ?>
      </div>
      <p class="text-sm font-semibold"><?= e($lg['username']) ?></p>
      <p class="text-xs <?= $lg['action']==='approved' ? 'text-emerald-600' : 'text-red-600' ?> capitalize"><?= e($lg['action']) ?> — <?= date('d M Y H:i', strtotime($lg['created_at'])) ?></p>
      <?php if ($lg['comments']): ?><p class="text-xs text-slate-500 mt-1">"<?= e($lg['comments']) ?>"</p><?php endif; ?>
    </div>
  <?php endforeach; ?>
  <?php if (empty($logs)): ?><p class="text-sm text-slate-400 col-span-2">No approvals recorded yet.</p><?php endif; ?>
</div>
<?php include __DIR__ . '/../includes/print_footer.php'; ?>
