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

$canAdjustMainStore = has_permission($pdo, $u, 'main_store.adjust');
$canViewAll = has_permission($pdo, $u, 'requisitions.view_all');

if ($canViewAll) {
    $outlets = $pdo->query("SELECT id, name FROM outlets WHERE is_active=1 ORDER BY name")->fetchAll();
} elseif ($u['department_id'] !== null) {
    $stmt = $pdo->prepare("SELECT id, name FROM outlets WHERE is_active=1 AND department_id = ? ORDER BY name");
    $stmt->execute([$u['department_id']]);
    $outlets = $stmt->fetchAll();
} else {
    $outlets = $pdo->query("SELECT id, name FROM outlets WHERE is_active=1 ORDER BY name")->fetchAll();
}

$items = $pdo->query("SELECT i.id, i.name, COALESCE(s.avg_cost,0) avg_cost FROM items i
                       LEFT JOIN main_store_stock s ON s.item_id = i.id
                       WHERE i.is_active=1 ORDER BY i.name")->fetchAll();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $locationType = $_POST['location_type'] ?? '';
    $outletId = $_POST['outlet_id'] ?: null;
    $notes = trim($_POST['notes'] ?? '');
    $itemIds = $_POST['item_id'] ?? [];
    $qtys = $_POST['quantity'] ?? [];
    $costs = $_POST['unit_cost'] ?? [];
    $lineReasonIds = $_POST['reason_id'] ?? [];
    $lineNotes = $_POST['line_notes'] ?? [];

    if ($locationType === 'main_store' && !$canAdjustMainStore) {
        flash('error', 'You do not have permission to write off Main Store stock.');
        redirect('waste/create.php');
    }
    if ($locationType === 'outlet' && !$outletId) {
        flash('error', 'Please select an outlet.');
        redirect('waste/create.php');
    }

    $lines = [];
    foreach ($itemIds as $i => $itemId) {
        if (!$itemId || (float)$qtys[$i] <= 0 || empty($lineReasonIds[$i])) continue;
        $lines[] = [$itemId, (float)$qtys[$i], (float)($costs[$i] ?? 0), (int)$lineReasonIds[$i], $lineNotes[$i] ?? ''];
    }

    if (empty($lines)) {
        flash('error', 'Please add at least one item.');
    } else {
        $pdo->beginTransaction();
        try {
            $wasteNumber = generate_doc_number($pdo, 'waste_records', 'waste_number', 'WST');
            $total = 0;
            foreach ($lines as $l) { $total += $l[1] * $l[2]; }

            $pdo->prepare("INSERT INTO waste_records (waste_number, location_type, outlet_id, recorded_by, total_value, notes)
                           VALUES (?,?,?,?,?,?)")
                ->execute([$wasteNumber, $locationType, $locationType === 'outlet' ? $outletId : null, $u['id'], $total, $notes]);
            $wasteId = $pdo->lastInsertId();

            $reasonNames = [];
            foreach ($reasons as $r) { $reasonNames[$r['id']] = $r['name']; }

            $insItem = $pdo->prepare("INSERT INTO waste_items (waste_id, item_id, quantity, unit_cost, reason_id, notes) VALUES (?,?,?,?,?,?)");
            foreach ($lines as $l) {
                [$itemId, $qty, $cost, $reasonId, $lineNote] = $l;
                $reasonName = $reasonNames[$reasonId] ?? 'Other';
                if ($locationType === 'main_store') {
                    [$ok, $msg] = main_store_waste_out($pdo, $itemId, $qty, $cost, $wasteId, $u['id'], "Waste $wasteNumber: $reasonName");
                } else {
                    [$ok, $msg] = outlet_waste_out($pdo, $itemId, $outletId, $qty, $cost, $wasteId, $u['id'], "Waste $wasteNumber: $reasonName");
                }
                if (!$ok) throw new Exception($msg);
                $insItem->execute([$wasteId, $itemId, $qty, $cost, $reasonId, $lineNote]);
            }

            notify_role($pdo, 'accounts', "$wasteNumber recorded: ₦" . number_format($total,2) . " in stock written off.", "waste/view.php?id=$wasteId", 'waste', $wasteId);

            $pdo->commit();
            flash('success', "Waste record $wasteNumber saved and stock updated.");
            redirect('waste/view.php?id=' . $wasteId);
        } catch (Exception $ex) {
            $pdo->rollBack();
            flash('error', 'Failed: ' . $ex->getMessage());
        }
    }
}

$pageTitle = 'Record Waste';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Record Waste / Spoilage</h1>
<p class="text-slate-500 text-sm mb-6">This immediately deducts the written-off quantity from stock.</p>

<form method="POST" class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
    <div>
      <label class="text-sm font-medium block mb-1">Location</label>
      <select name="location_type" id="locationType" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm" onchange="toggleOutletField()">
        <option value="">-- Select location --</option>
        <?php if ($canAdjustMainStore): ?><option value="main_store">Main Store</option><?php endif; ?>
        <option value="outlet">Outlet</option>
      </select>
    </div>
    <div id="outletFieldWrap" class="hidden">
      <label class="text-sm font-medium block mb-1">Outlet</label>
      <select name="outlet_id" id="outletField" 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'] ?>"><?= e($o['name']) ?></option><?php endforeach; ?>
      </select>
    </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</th>
      <th class="text-left px-3 py-2">Unit Cost</th><th class="text-left px-3 py-2">Reason</th>
      <th class="text-left px-3 py-2">Notes</th><th></th></tr></thead>
    <tbody id="lineBody">
      <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="unit_cost[]" class="item-cost-input w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2">
          <select name="reason_id[]" required class="border border-slate-300 rounded-lg px-2 py-1.5">
            <option value="">-- Reason --</option>
            <?php foreach ($reasons as $r): ?><option value="<?= $r['id'] ?>"><?= e($r['name']) ?></option><?php endforeach; ?>
          </select>
        </td>
        <td class="px-3 py-2"><input name="line_notes[]" class="w-full 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>
    </tbody>
  </table>
  </div>
  <button type="button" id="addLine" class="text-blue-600 text-sm font-medium mb-6">+ Add another item</button>

  <textarea name="notes" placeholder="Overall notes (optional)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm mb-6"></textarea>

  <div class="flex gap-3">
    <button type="submit" class="bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Record Waste</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'], 'cost' => $it['avg_cost']], $items)) ?>;

function toggleOutletField() {
  const type = document.getElementById('locationType').value;
  document.getElementById('outletFieldWrap').classList.toggle('hidden', type !== 'outlet');
}

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'; ?>
