<?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();
$outlets = $pdo->query("SELECT id, name FROM outlets WHERE is_active=1 ORDER BY name")->fetchAll();

$cloneLines = [];
$cloneOutletId = null;
$cloneNotes = '';
if (isset($_GET['clone_from'])) {
    $cloneStmt = $pdo->prepare("SELECT sr.*, o.department_id outlet_department_id FROM store_requisitions sr
                                 JOIN outlets o ON o.id = sr.outlet_id WHERE sr.id = ?");
    $cloneStmt->execute([$_GET['clone_from']]);
    $cloneSrc = $cloneStmt->fetch();
    if ($cloneSrc && can_view_requisition($pdo, $u, $cloneSrc['outlet_department_id'], $cloneSrc['requested_by'])) {
        $cloneOutletId = $cloneSrc['outlet_id'];
        $cloneNotes = $cloneSrc['notes'];
        $lineStmt = $pdo->prepare("SELECT sri.*, i.name item_name FROM store_requisition_items sri
                                    JOIN items i ON i.id = sri.item_id WHERE sri.sr_id = ?");
        $lineStmt->execute([$cloneSrc['id']]);
        $cloneLines = $lineStmt->fetchAll();
    }
}

$formToken = new_form_token('sr_create');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $outletId = $_POST['outlet_id'];
    $notes = trim($_POST['notes'] ?? '');
    $itemIds = $_POST['item_id'] ?? [];
    $qtys = $_POST['quantity'] ?? [];

    $lines = [];
    foreach ($itemIds as $i => $itemId) {
        if (!$itemId || (float)$qtys[$i] <= 0) continue;
        $lines[] = [$itemId, (float)$qtys[$i]];
    }

    if (!$outletId) {
        $msg = 'Please select the requesting outlet.';
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
    } elseif (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('sr_create', $_POST['form_token'] ?? '')) {
        $msg = 'This form was already submitted. Refresh the page to submit another.';
        if (is_ajax()) json_response(false, $msg);
        flash('error', $msg);
        redirect('store_requisitions/create.php');
    } else {
        $pdo->beginTransaction();
        try {
            $srNumber = generate_doc_number($pdo, 'store_requisitions', 'sr_number', 'SR');
            $pdo->prepare("INSERT INTO store_requisitions (sr_number, outlet_id, requested_by, notes) VALUES (?,?,?,?)")
                ->execute([$srNumber, $outletId, $u['id'], $notes]);
            $srId = $pdo->lastInsertId();

            $ins = $pdo->prepare("INSERT INTO store_requisition_items (sr_id, item_id, quantity_requested) VALUES (?,?,?)");
            foreach ($lines as $l) { $ins->execute([$srId, $l[0], $l[1]]); }

            $pdo->commit();
            $deptStmt = $pdo->prepare("SELECT department_id FROM outlets WHERE id = ?");
            $deptStmt->execute([$outletId]);
            $outletDeptId = $deptStmt->fetchColumn();
            notify_stage_approvers($pdo, 'store_requisition', $srNumber, $srId, 1, 0, "store_requisitions/view.php?id=$srId", $outletDeptId ?: null, $u['id']);

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

$pageTitle = 'New Store Requisition';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">New Store 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">Requesting Outlet</label>
      <select name="outlet_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Select outlet --</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">
    </div>
  </div>

  <div class="overflow-x-auto"><table class="w-full text-sm mb-4">
    <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 Requested</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_requested'] ?>" class="w-32 border border-slate-300 rounded-lg px-2 py-1.5"></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-32 border border-slate-300 rounded-lg px-2 py-1.5"></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'; ?>
