<?php
// public/adjust_stock.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = "Adjust Stock - IMS";
$user = current_user();

function post_str(string $key): string {
    return trim((string)($_POST[$key] ?? ''));
}
function post_int(string $key): int {
    return (int)($_POST[$key] ?? 0);
}

$error = '';
$success = '';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = post_int('product_id');
    $qty = (int)($_POST['quantity'] ?? 0); // can be negative or positive
    $notes = post_str('notes');

    if ($product_id <= 0) {
        $error = "Please select a product.";
    } elseif ($qty === 0) {
        $error = "Quantity cannot be 0. Use + to add, - to subtract.";
    } elseif ($notes === '') {
        $error = "Notes is required for adjustments (explain why).";
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO inventory_movements
                (product_id, movement_type, quantity, unit_cost, reference_type, reference_id, notes, created_by)
                VALUES
                (:product_id, 'ADJUST', :quantity, NULL, 'MANUAL', NULL, :notes, :created_by)
            ");
            $stmt->execute([
                ':product_id' => $product_id,
                ':quantity' => $qty,
                ':notes' => $notes,
                ':created_by' => $user['id'],
            ]);

            $success = "Stock adjusted successfully.";
        } catch (PDOException $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}

// Recent adjustments
$recent = $pdo->query("
    SELECT m.*, p.sku, p.name
    FROM inventory_movements m
    JOIN products p ON p.id = m.product_id
    WHERE m.movement_type='ADJUST'
    ORDER BY m.created_at DESC
    LIMIT 20
")->fetchAll();

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <h4 class="mb-3">Adjust Stock</h4>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($success !== ''): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3">Adjustment Entry</h5>

          <form method="POST">
            <div class="mb-2">
              <label class="form-label">Product</label>
              <select class="form-select" name="product_id" required>
                <option value="0">-- Select --</option>
                <?php foreach ($products as $p): ?>
                  <option value="<?= (int)$p['id'] ?>">
                    <?= htmlspecialchars($p['name']) ?> (<?= htmlspecialchars($p['sku']) ?>)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="mb-2">
              <label class="form-label">Quantity (+ add / - subtract)</label>
              <input class="form-control" name="quantity" type="number" step="1" required placeholder="e.g. 5 or -2">
            </div>

            <div class="mb-3">
              <label class="form-label">Notes (required)</label>
              <input class="form-control" name="notes" maxlength="255" required placeholder="Reason for adjustment">
            </div>

            <button class="btn btn-warning w-100" type="submit">Save Adjustment</button>

            <div class="text-muted small mt-2">
              Example: “Damaged items” or “Recount correction”
            </div>
          </form>
        </div>
      </div>
    </div>

    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Recent Adjustments</h6>

          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>SKU</th>
                  <th>Product</th>
                  <th class="text-end">Qty</th>
                  <th>Notes</th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$recent): ?>
                  <tr><td colspan="5" class="text-muted">No adjustments yet.</td></tr>
                <?php else: ?>
                  <?php foreach ($recent as $r): ?>
                    <tr>
                      <td><?= htmlspecialchars($r['created_at']) ?></td>
                      <td><?= htmlspecialchars($r['sku']) ?></td>
                      <td><?= htmlspecialchars($r['name']) ?></td>
                      <td class="text-end fw-semibold"><?= (int)$r['quantity'] ?></td>
                      <td><?= htmlspecialchars($r['notes'] ?? '-') ?></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="text-muted small">
            Next: we start the <b>Deliveries module</b> (create delivery, add items, assign driver, track status).
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
