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

$poId = (int)($_GET['po_id'] ?? $_POST['po_id'] ?? 0);
$po = null;
$poLines = [];
if ($poId) {
    $stmt = $pdo->prepare("SELECT po.*, s.name supplier_name FROM purchase_orders po JOIN suppliers s ON s.id=po.supplier_id WHERE po.id=?");
    $stmt->execute([$poId]);
    $po = $stmt->fetch();
    if ($po) {
        $lineStmt = $pdo->prepare("SELECT poi.item_id, i.name item_name, poi.unit_cost, poi.quantity_received
                                    FROM purchase_order_items poi JOIN items i ON i.id=poi.item_id
                                    WHERE poi.po_id=? AND poi.quantity_received > 0");
        $lineStmt->execute([$poId]);
        $poLines = $lineStmt->fetchAll();
    }
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_return'])) {
    $supplierId = $_POST['supplier_id'];
    $reason = trim($_POST['reason'] ?? '');
    $itemIds = $_POST['item_id'] ?? [];
    $qtys = $_POST['quantity'] ?? [];
    $costs = $_POST['unit_cost'] ?? [];
    $lineReasons = $_POST['line_reason'] ?? [];

    if (!$supplierId) {
        flash('error', 'Please select a supplier.');
    } else {
        $lines = [];
        foreach ($itemIds as $i => $itemId) {
            if (!$itemId || (float)$qtys[$i] <= 0) continue;
            $lines[] = [$itemId, (float)$qtys[$i], (float)($costs[$i] ?? 0), $lineReasons[$i] ?? ''];
        }
        if (empty($lines)) {
            flash('error', 'Please add at least one item to return.');
        } else {
            $pdo->beginTransaction();
            try {
                $returnNumber = generate_doc_number($pdo, 'return_to_supplier', 'return_number', 'RTS');
                $pdo->prepare("INSERT INTO return_to_supplier (return_number, po_id, supplier_id, reason, created_by) VALUES (?,?,?,?,?)")
                    ->execute([$returnNumber, $poId ?: null, $supplierId, $reason, $u['id']]);
                $returnId = $pdo->lastInsertId();

                $ins = $pdo->prepare("INSERT INTO return_to_supplier_items (return_id, item_id, quantity, unit_cost, reason) VALUES (?,?,?,?,?)");
                foreach ($lines as $l) {
                    [$ok, $msg] = main_store_return_out($pdo, $l[0], $l[1], $l[2], $returnId, $u['id'], "Return $returnNumber");
                    if (!$ok) throw new Exception($msg);
                    $ins->execute([$returnId, $l[0], $l[1], $l[2], $l[3]]);
                }

                $pdo->prepare("UPDATE return_to_supplier SET status='sent' WHERE id=?")->execute([$returnId]);

                // Notify supplier (if email on file) and accounts team
                $supStmt = $pdo->prepare("SELECT name, email FROM suppliers WHERE id=?");
                $supStmt->execute([$supplierId]);
                $sup = $supStmt->fetch();
                if (!empty($sup['email'])) {
                    send_email($sup['email'], APP_NAME . " - Return $returnNumber",
                        "<p>We are returning goods under return note <strong>$returnNumber</strong>.</p>" .
                        "<p>Reason: " . e($reason) . "</p><p>Please contact us to arrange collection/replacement/credit.</p>");
                }
                notify_role($pdo, 'accounts', "$returnNumber: goods returned to {$sup['name']}.", "return_to_supplier/view.php?id=$returnId", 'return_to_supplier', $returnId);

                $pdo->commit();
                flash('success', "Return $returnNumber recorded and stock updated.");
                redirect('return_to_supplier/view.php?id=' . $returnId);
            } catch (Exception $ex) {
                $pdo->rollBack();
                flash('error', 'Failed: ' . $ex->getMessage());
            }
        }
    }
}

$pageTitle = 'New Return to Supplier';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Return Goods to Supplier</h1>
<p class="text-slate-500 text-sm mb-6">This immediately deducts the returned quantity from Main Store stock.</p>

<form method="POST" class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
  <?php if ($poId): ?><input type="hidden" name="po_id" value="<?= $poId ?>"><?php endif; ?>
  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
    <div>
      <label class="text-sm font-medium block mb-1">Supplier</label>
      <select name="supplier_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Select supplier --</option>
        <?php foreach ($suppliers as $s): ?>
          <option value="<?= $s['id'] ?>" <?= ($po && $po['supplier_id']==$s['id']) ? 'selected' : '' ?>><?= e($s['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="text-sm font-medium block mb-1">Reason for Return</label>
      <input name="reason" placeholder="e.g. Damaged on arrival, wrong item supplied" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </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 to Return</th>
      <th class="text-left px-3 py-2">Unit Cost</th><th class="text-left px-3 py-2">Line Reason</th><th></th></tr></thead>
    <tbody id="lineBody">
    <?php if (!empty($poLines)): foreach ($poLines as $l): ?>
      <tr>
        <td class="px-3 py-2">
          <select name="item_id[]" class="w-full border border-slate-300 rounded-lg px-2 py-1.5">
            <option value="<?= $l['item_id'] ?>" selected><?= e($l['item_name']) ?></option>
          </select>
        </td>
        <td class="px-3 py-2"><input type="number" step="0.01" max="<?= $l['quantity_received'] ?>" name="quantity[]" placeholder="0" 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[]" value="<?= $l['unit_cost'] ?>" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input name="line_reason[]" 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>
    <?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="unit_cost[]" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input name="line_reason[]" 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>
    <?php endif; ?>
    </tbody>
  </table></div>
  <table class="hidden"><tbody>
    <tr id="blankItemRowTemplate">
      <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="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
      <td class="px-3 py-2"><input name="line_reason[]" 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>
  <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" name="submit_return" value="1" class="bg-amber-600 hover:bg-amber-700 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Record Return</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.getElementById('blankItemRowTemplate').cloneNode(true);
  row.removeAttribute('id');
  row.querySelectorAll('input').forEach(i => i.value = '');
  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'; ?>
