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

$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) {
    if (is_ajax()) json_response(false, 'Requisition not found.');
    flash('error', 'Requisition not found.'); redirect('purchase_requisitions/list.php');
}
if (!can_view_requisition($pdo, $u, $pr['department_id'], $pr['requested_by'])) {
    if (is_ajax()) json_response(false, 'This requisition belongs to another department.');
    flash('error', 'This requisition belongs to another department.');
    redirect('purchase_requisitions/list.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $comments = trim($_POST['comments'] ?? '');
    [$ok, $msg] = process_approval($pdo, 'purchase_requisition', 'purchase_requisitions', $id, $u['id'], $u['role'], $_POST['action'], $comments);
    if (is_ajax()) json_response($ok, $msg);
    flash($ok ? 'success' : 'error', $msg);
    redirect('purchase_requisitions/view.php?id=' . $id);
}

$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.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();

$canAct = $pr['status'] === 'pending' && can_approve($pdo, 'purchase_requisition', $pr['current_stage'], $pr['total_estimated_cost'], $u['role']);
$requiredRole = role_for_stage($pdo, 'purchase_requisition', $pr['current_stage'], $pr['total_estimated_cost']);

$pageTitle = 'PR ' . $pr['pr_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($pr['pr_number']) ?></h1>
    <p class="text-slate-500 text-sm">Requested by <?= e($pr['requester']) ?> on <?= date('d M Y', strtotime($pr['created_at'])) ?></p>
  </div>
  <?php $badge = ['pending'=>'bg-amber-100 text-amber-700','approved'=>'bg-emerald-100 text-emerald-700',
                  'rejected'=>'bg-red-100 text-red-700','ordered'=>'bg-blue-100 text-blue-700',
                  'received'=>'bg-slate-200 text-slate-700','cancelled'=>'bg-slate-200 text-slate-500'][$pr['status']]; ?>
  <span class="px-3 py-1 rounded-full text-sm <?= $badge ?> capitalize"><?= $pr['status'] ?></span>
  <a href="print.php?id=<?= $pr['id'] ?>" target="_blank" class="ml-3 text-sm text-blue-600 hover:underline">🖨️ Print / PDF</a>
</div>

<?php if ($pr['status'] === 'rejected'): ?>
  <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-center justify-between flex-wrap gap-3">
    <p class="text-sm text-red-700">This requisition was rejected and is now closed — it can't be edited or resubmitted as-is.
      To try again, raise a fresh requisition (you can start from a copy of this one).</p>
    <a href="create.php?clone_from=<?= $pr['id'] ?>" class="shrink-0 bg-red-600 hover:bg-red-700 text-white text-sm font-medium px-4 py-2 rounded-lg">
      Raise a New Requisition From This
    </a>
  </div>
<?php endif; ?>

<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">Requested 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">Est. Unit Cost</th><th class="text-left px-5 py-2">Line Total</th>
          <th class="text-left px-5 py-2">Supplier</th></tr></thead>
        <tbody>
        <?php foreach ($lines as $l): ?>
          <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['estimated_unit_cost'],2) ?></td>
            <td class="px-5 py-2.5">₦<?= number_format($l['quantity']*$l['estimated_unit_cost'],2) ?></td>
            <td class="px-5 py-2.5"><?= e($l['supplier_name'] ?? '—') ?></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 Estimated Cost</td>
          <td class="px-5 py-2.5">₦<?= number_format($pr['total_estimated_cost'],2) ?></td><td></td>
        </tr></tfoot>
      </table></div>
    </div>

    <?php if ($pr['notes']): ?>
      <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
        <p class="text-sm font-semibold mb-1">Notes</p>
        <p class="text-sm text-slate-600"><?= e($pr['notes']) ?></p>
      </div>
    <?php endif; ?>

    <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">Approval History</div>
      <div class="overflow-x-auto"><table class="w-full text-sm">
        <tbody>
        <?php foreach ($logs as $lg): ?>
          <tr class="border-t border-slate-100">
            <td class="px-5 py-2.5"><?= e($lg['username']) ?></td>
            <td class="px-5 py-2.5">Stage <?= $lg['stage'] ?></td>
            <td class="px-5 py-2.5 capitalize"><?= e($lg['action']) ?></td>
            <td class="px-5 py-2.5 text-slate-500"><?= e($lg['comments']) ?></td>
            <td class="px-5 py-2.5">
              <?php if (!empty($lg['signature_path'])): ?>
                <img src="<?= SIGNATURE_UPLOAD_URL . e($lg['signature_path']) ?>" alt="signature" class="h-8 inline-block">
              <?php endif; ?>
            </td>
            <td class="px-5 py-2.5 text-slate-400"><?= e($lg['created_at']) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (empty($logs)): ?><tr><td class="px-5 py-4 text-slate-400">No actions yet.</td></tr><?php endif; ?>
        </tbody>
      </table></div>
    </div>
  </div>

  <div class="space-y-6">
    <?php if ($pr['status'] === 'pending'): ?>
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
      <p class="text-sm font-semibold mb-2">Current Stage: <?= $pr['current_stage'] ?> (<?= e($requiredRole ?? 'N/A') ?> approval)</p>
      <?php if ($canAct): ?>
        <form class="ajax-form space-y-3" method="POST" data-loading-text="Submitting...">
          <textarea name="comments" placeholder="Comments (optional)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm"></textarea>
          <div class="flex gap-2">
            <button type="submit" name="action" value="approved" class="flex-1 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium py-2 rounded-lg">Approve</button>
            <button type="submit" name="action" value="rejected" class="flex-1 bg-red-600 hover:bg-red-700 text-white text-sm font-medium py-2 rounded-lg">Reject</button>
          </div>
        </form>
      <?php else: ?>
        <p class="text-sm text-slate-500">Waiting on <span class="font-medium capitalize"><?= e($requiredRole ?? 'next stage') ?></span> to act.</p>
      <?php endif; ?>
    </div>
    <?php elseif ($pr['status'] === 'approved'): ?>
      <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
        <p class="text-sm text-slate-600 mb-3">This requisition is fully approved and ready to be converted into a Purchase Order.</p>
        <a href="../purchase_orders/create.php?pr_id=<?= $pr['id'] ?>" class="block text-center bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium py-2 rounded-lg">Create Purchase Order</a>
      </div>
    <?php endif; ?>

    <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">Outlet/Dept:</span> <?= e($pr['outlet_name'] ?? $pr['dept_name'] ?? '—') ?></p>
      <p><span class="text-slate-500">Requested by:</span> <?= e($pr['requester']) ?></p>
      <p><span class="text-slate-500">Date:</span> <?= date('d M Y H:i', strtotime($pr['created_at'])) ?></p>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
