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

$items = $pdo->query("SELECT id, name FROM items WHERE is_active=1 ORDER BY name")->fetchAll();
$suppliers = $pdo->query("SELECT id, name FROM suppliers WHERE is_active=1 ORDER BY name")->fetchAll();
$outlets = $pdo->query("SELECT id, name FROM outlets WHERE is_active=1 ORDER BY name")->fetchAll();

// If cloning from a rejected/older requisition, prefill from it (only if the
// user is allowed to see the original)
$cloneLines = [];
$cloneOutletId = null;
$cloneNotes = '';
if (isset($_GET['clone_from'])) {
    $cloneStmt = $pdo->prepare("SELECT * FROM purchase_requisitions WHERE id = ?");
    $cloneStmt->execute([$_GET['clone_from']]);
    $cloneSrc = $cloneStmt->fetch();
    if ($cloneSrc && can_view_requisition($pdo, $u, $cloneSrc['department_id'], $cloneSrc['requested_by'])) {
        $cloneOutletId = $cloneSrc['outlet_id'];
        $cloneNotes = $cloneSrc['notes'];
        $lineStmt = $pdo->prepare("SELECT pri.*, i.name item_name FROM purchase_requisition_items pri
                                    JOIN items i ON i.id = pri.item_id WHERE pri.pr_id = ?");
        $lineStmt->execute([$cloneSrc['id']]);
        $cloneLines = $lineStmt->fetchAll();
    }
}

$formToken = new_form_token('pr_create');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $outletId = $_POST['outlet_id'] ?: null;
    $notes = trim($_POST['notes'] ?? '');
    $itemIds = $_POST['item_id'] ?? [];
    $qtys = $_POST['quantity'] ?? [];
    $costs = $_POST['estimated_unit_cost'] ?? [];
    $supIds = $_POST['supplier_id'] ?? [];

    $lines = [];
    $total = 0;
    foreach ($itemIds as $i => $itemId) {
        if (!$itemId || (float)$qtys[$i] <= 0) continue;
        $qty = (float)$qtys[$i];
        $cost = (float)($costs[$i] ?? 0);
        $lines[] = [$itemId, $qty, $cost, $supIds[$i] ?: null];
        $total += $qty * $cost;
    }

    if (empty($lines)) {
        $msg = 'Please add at least one valid item line.';
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
    } elseif (!consume_form_token('pr_create', $_POST['form_token'] ?? '')) {
        // Only checked here (right before the write) so a validation error
        // above doesn't burn the token and block a legitimate resubmission.
        $msg = 'This form was already submitted. Refresh the page to submit another.';
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
        redirect('purchase_requisitions/create.php');
    } else {
        $pdo->beginTransaction();
        try {
            $prNumber = generate_doc_number($pdo, 'purchase_requisitions', 'pr_number', 'PR');
            $pdo->prepare("INSERT INTO purchase_requisitions (pr_number, requested_by, department_id, outlet_id, total_estimated_cost, notes)
                           VALUES (?,?,?,?,?,?)")
                ->execute([$prNumber, $u['id'], $u['department_id'], $outletId, $total, $notes]);
            $prId = $pdo->lastInsertId();

            $ins = $pdo->prepare("INSERT INTO purchase_requisition_items (pr_id, item_id, quantity, estimated_unit_cost, supplier_id)
                                   VALUES (?,?,?,?,?)");
            foreach ($lines as $l) { $ins->execute([$prId, $l[0], $l[1], $l[2], $l[3]]); }

            $pdo->commit();
            notify_stage_approvers($pdo, 'purchase_requisition', $prNumber, $prId, 1, $total, "purchase_requisitions/view.php?id=$prId", $u['department_id'], $u['id']);

            $successMsg = "Purchase requisition $prNumber submitted for approval.";
            $redirectTo = 'purchase_requisitions/view.php?id=' . $prId;
            if (is_ajax()) json_response(true, $successMsg, ['redirect' => $redirectTo]);
            flash('success', $successMsg);
            redirect($redirectTo);
        } catch (Exception $ex) {
            $pdo->rollBack();
            $msg = 'Failed to create requisition: ' . $ex->getMessage();
            if (is_ajax()) json_response(false, $msg);
            flash('error', $msg);
        }
    }
}

$pageTitle = 'New Purchase Requisition';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">New Purchase Requisition</h1>

<form method="POST" class="ajax-form bg-white rounded-xl shadow-sm border border-slate-200 p-6" data-loading-text="Submitting...">
  <input type="hidden" name="form_token" value="<?= e($formToken) ?>">
  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
    <div>
      <label class="text-sm font-medium block mb-1">Outlet / Department (optional)</label>
      <select name="outlet_id" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- None (general/main store) --</option>
        <?php foreach ($outlets as $o): ?><option value="<?= $o['id'] ?>" <?= $cloneOutletId==$o['id']?'selected':'' ?>><?= e($o['name']) ?></option><?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="text-sm font-medium block mb-1">Notes</label>
      <input name="notes" value="<?= e($cloneNotes) ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm" placeholder="Purpose / justification">
    </div>
  </div>

  <div class="overflow-x-auto">
  <table class="w-full text-sm mb-4" id="lineTable">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-3 py-2">Item</th><th class="text-left px-3 py-2">Qty</th>
      <th class="text-left px-3 py-2">Est. Unit Cost</th><th class="text-left px-3 py-2">Preferred Supplier</th>
      <th></th></tr></thead>
    <tbody id="lineBody">
    <?php if (!empty($cloneLines)): foreach ($cloneLines as $l): ?>
      <tr>
        <td class="px-3 py-2">
          <div class="item-autocomplete relative">
            <input type="text" class="item-search w-full border border-slate-300 rounded-lg px-2 py-1.5" value="<?= e($l['item_name']) ?>" autocomplete="off">
            <input type="hidden" class="item-id-input" name="item_id[]" value="<?= $l['item_id'] ?>">
            <div class="item-dropdown hidden absolute z-20 bg-white border border-slate-200 rounded-lg mt-1 max-h-48 overflow-y-auto w-full shadow-lg"></div>
          </div>
        </td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="quantity[]" value="<?= $l['quantity'] ?>" class="w-24 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="estimated_unit_cost[]" value="<?= $l['estimated_unit_cost'] ?>" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><select name="supplier_id[]" class="w-full border border-slate-300 rounded-lg px-2 py-1.5">
          <option value="">-- Supplier --</option><?php foreach ($suppliers as $s): ?><option value="<?= $s['id'] ?>" <?= $l['supplier_id']==$s['id']?'selected':'' ?>><?= e($s['name']) ?></option><?php endforeach; ?>
        </select></td>
        <td><button type="button" onclick="this.closest('tr').remove()" class="text-red-500 px-2">✕</button></td>
      </tr>
    <?php endforeach; else: ?>
      <tr>
        <td class="px-3 py-2">
          <div class="item-autocomplete relative">
            <input type="text" class="item-search w-full border border-slate-300 rounded-lg px-2 py-1.5" placeholder="Type to search item..." autocomplete="off">
            <input type="hidden" class="item-id-input" name="item_id[]">
            <div class="item-dropdown hidden absolute z-20 bg-white border border-slate-200 rounded-lg mt-1 max-h-48 overflow-y-auto w-full shadow-lg"></div>
          </div>
        </td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="quantity[]" class="w-24 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="estimated_unit_cost[]" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><select name="supplier_id[]" class="w-full border border-slate-300 rounded-lg px-2 py-1.5">
          <option value="">-- Supplier --</option><?php foreach ($suppliers as $s): ?><option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option><?php endforeach; ?>
        </select></td>
        <td><button type="button" onclick="this.closest('tr').remove()" class="text-red-500 px-2">✕</button></td>
      </tr>
    <?php endif; ?>
    </tbody>
  </table>
  </div>
  <button type="button" id="addLine" class="text-blue-600 text-sm font-medium mb-6">+ Add another item</button>

  <div class="flex gap-3">
    <button type="submit" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Submit for Approval</button>
    <a href="list.php" class="text-slate-500 text-sm self-center">Cancel</a>
  </div>
</form>

<script>
window.ITEMS_DATA = <?= json_encode(array_map(fn($it) => ['id' => $it['id'], 'name' => $it['name']], $items)) ?>;
document.getElementById('addLine').addEventListener('click', function () {
  const row = document.querySelector('#lineBody tr').cloneNode(true);
  row.querySelectorAll('input').forEach(i => i.value = '');
  row.querySelectorAll('select').forEach(s => s.selectedIndex = 0);
  const dropdown = row.querySelector('.item-dropdown');
  if (dropdown) { dropdown.classList.add('hidden'); dropdown.innerHTML = ''; }
  document.getElementById('lineBody').appendChild(row);
});
</script>
<?php include __DIR__ . '/../includes/item_autocomplete.php'; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>
