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

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT sr.*, u.username requester, o.name outlet_name, o.id outlet_id, o.department_id outlet_department_id
                        FROM store_requisitions sr
                        JOIN users u ON u.id = sr.requested_by
                        JOIN outlets o ON o.id = sr.outlet_id
                        WHERE sr.id = ?");
$stmt->execute([$id]);
$sr = $stmt->fetch();
if (!$sr) {
    if (is_ajax()) json_response(false, 'Requisition not found.');
    flash('error', 'Requisition not found.'); redirect('store_requisitions/list.php');
}
if (!can_view_requisition($pdo, $u, $sr['outlet_department_id'], $sr['requested_by'])) {
    if (is_ajax()) json_response(false, 'This requisition belongs to another department.');
    flash('error', 'This requisition belongs to another department.');
    redirect('store_requisitions/list.php');
}

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

// Issue stock (main store -> outlet)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['issue'])) {
    if (!has_permission($pdo, $u, 'store_requisitions.issue')) {
        if (is_ajax()) json_response(false, 'You do not have permission to issue stock.');
        require_permission('store_requisitions.issue'); // renders the normal 403 page for non-AJAX
    }
    $itemIds = $_POST['issue_item_id'] ?? [];
    $qtys = $_POST['issue_qty'] ?? [];

    $pdo->beginTransaction();
    try {
        foreach ($itemIds as $i => $itemId) {
            $qty = (float)($qtys[$i] ?? 0);
            if ($qty <= 0) continue;
            [$ok, $msg] = transfer_main_to_outlet($pdo, $itemId, $sr['outlet_id'], $qty, 'SR', $id, $u['id'], "SR " . $sr['sr_number']);
            if (!$ok) throw new Exception($msg);
            $pdo->prepare("UPDATE store_requisition_items SET quantity_issued = quantity_issued + ? WHERE sr_id=? AND item_id=?")
                ->execute([$qty, $id, $itemId]);
        }
        $pdo->prepare("UPDATE store_requisitions SET status='issued' WHERE id=?")->execute([$id]);
        $pdo->commit();
        $msg = 'Stock issued to outlet successfully.';
        if (is_ajax()) json_response(true, $msg);
        flash('success', $msg);
    } catch (Exception $ex) {
        $pdo->rollBack();
        $msg = 'Issue failed: ' . $ex->getMessage();
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
    }
    redirect('store_requisitions/view.php?id=' . $id);
}

$lineStmt = $pdo->prepare("SELECT sri.*, i.name item_name, un.abbreviation unit_abbr, COALESCE(ms.quantity,0) main_stock
                            FROM store_requisition_items sri
                            JOIN items i ON i.id = sri.item_id
                            LEFT JOIN units un ON un.id = i.unit_id
                            LEFT JOIN main_store_stock ms ON ms.item_id = i.id
                            WHERE sri.sr_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='store_requisition' AND reference_id=? ORDER BY al.created_at");
$logStmt->execute([$id]);
$logs = $logStmt->fetchAll();

$canAct = $sr['status'] === 'pending' && can_approve($pdo, 'store_requisition', $sr['current_stage'], 0, $u['role']);
$requiredRole = role_for_stage($pdo, 'store_requisition', $sr['current_stage'], 0);

$pageTitle = 'SR ' . $sr['sr_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($sr['sr_number']) ?></h1>
    <p class="text-slate-500 text-sm">Outlet: <?= e($sr['outlet_name']) ?> · Requested by <?= e($sr['requester']) ?> on <?= date('d M Y', strtotime($sr['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','issued'=>'bg-blue-100 text-blue-700',
                  'cancelled'=>'bg-slate-200 text-slate-500'][$sr['status']]; ?>
  <span class="px-3 py-1 rounded-full text-sm <?= $badge ?> capitalize"><?= $sr['status'] ?></span>
  <a href="print.php?id=<?= $sr['id'] ?>" target="_blank" class="ml-3 text-sm text-blue-600 hover:underline">🖨️ Print / PDF</a>
</div>

<?php if ($sr['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. To try again, raise a fresh requisition
      (you can start from a copy of this one).</p>
    <a href="create.php?clone_from=<?= $sr['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>
      <form class="ajax-form" method="POST" data-loading-text="Issuing...">
      <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">Requested</th>
          <th class="text-left px-5 py-2">Issued</th><th class="text-left px-5 py-2">Main Store Stock</th>
          <?php $canIssue = has_permission($pdo, $u, 'store_requisitions.issue'); ?>
          <?php if ($sr['status']==='approved' && $canIssue): ?><th class="text-left px-5 py-2">Issue Qty</th><?php endif; ?>
        </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']) ?><?php if ($sr['status']==='approved' && $canIssue): ?><input type="hidden" name="issue_item_id[]" value="<?= $l['item_id'] ?>"><?php endif; ?></td>
            <td class="px-5 py-2.5"><?= number_format($l['quantity_requested'],2) ?> <?= e($l['unit_abbr']) ?></td>
            <td class="px-5 py-2.5"><?= number_format($l['quantity_issued'],2) ?></td>
            <td class="px-5 py-2.5"><?= number_format($l['main_stock'],2) ?></td>
            <?php if ($sr['status']==='approved' && $canIssue): ?>
              <td class="px-5 py-2.5"><input type="number" step="0.01" name="issue_qty[]" max="<?= min($l['quantity_requested'],$l['main_stock']) ?>"
                value="<?= min($l['quantity_requested'],$l['main_stock']) ?>" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
            <?php endif; ?>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
      <?php if ($sr['status']==='approved' && has_permission($pdo, $u, 'store_requisitions.issue')): ?>
        <div class="p-5">
          <button type="submit" name="issue" value="1" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Issue Stock to Outlet</button>
        </div>
      <?php endif; ?>
      </form>
    </div>

    <?php if ($sr['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($sr['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 ($sr['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: <?= $sr['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 endif; ?>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
