<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';
require_once __DIR__ . '/../app/config/db.php';
require_once __DIR__ . '/../app/models/InventoryItem.php';

require_login();

// Admin only
if ($_SESSION['user']['role'] !== 'admin') {
    http_response_code(403);
    exit('Forbidden');
}

$unitId = (int)($_GET['unit_id'] ?? 0);
if (!$unitId) exit('Invalid unit.');

// Load unit header info
$stmt = db()->prepare("
  SELECT u.id, u.unit_code, b.name AS building_name
  FROM units u
  JOIN buildings b ON b.id = u.building_id
  WHERE u.id = ?
  LIMIT 1
");
$stmt->execute([$unitId]);
$unit = $stmt->fetch();
if (!$unit) exit('Unit not found.');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    try {
        if ($action === 'add') {
            $itemName = trim($_POST['item_name'] ?? '');
            $qty = (int)($_POST['quantity'] ?? 1);
            $condition = $_POST['item_condition'] ?? 'good';
            $remarks = trim($_POST['remarks'] ?? '');

            if ($itemName === '') {
                $error = 'Item name is required.';
            } elseif ($qty <= 0) {
                $error = 'Quantity must be at least 1.';
            } else {
                InventoryItem::create($unitId, $itemName, $qty, $condition, $remarks);
                $success = 'Item added successfully ✅';
            }
        }

        if ($action === 'delete') {
            $itemId = (int)($_POST['item_id'] ?? 0);
            if ($itemId) {
                InventoryItem::delete($itemId);
                $success = 'Item deleted ✅';
            }
        }

    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$items = InventoryItem::listByUnit($unitId);

$pageTitle = 'Manage Inventory';
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container-narrow mx-auto">

  <div class="mb-3">
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/unit.php?id=<?= $unitId ?>">
      ← Back to Unit Profile
    </a>
  </div>

  <div class="card p-4 mb-3">
    <h5 class="page-title mb-1">Manage Beds & Furniture</h5>
    <div class="text-muted">
      <?= htmlspecialchars($unit['building_name']) ?> • Unit <?= htmlspecialchars($unit['unit_code']) ?>
    </div>
  </div>

  <div class="card p-4 mb-3">
    <h6 class="mb-3">Add Item</h6>

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

    <form method="post">
      <input type="hidden" name="action" value="add">

      <div class="mb-3">
        <label class="form-label">Item Name</label>
        <input name="item_name" class="form-control" required placeholder="e.g. Bed, Cabinet, Table">
        <div class="form-text">Tip: Use the word “Bed” for beds so bed count works.</div>
      </div>

      <div class="row g-2">
        <div class="col-md-4">
          <div class="mb-3">
            <label class="form-label">Quantity</label>
            <input name="quantity" type="number" min="1" value="1" class="form-control" required>
          </div>
        </div>

        <div class="col-md-8">
          <div class="mb-3">
            <label class="form-label">Condition</label>
            <select name="item_condition" class="form-select">
              <option value="good">Good</option>
              <option value="fair">Fair</option>
              <option value="poor">Poor</option>
              <option value="broken">Broken</option>
            </select>
          </div>
        </div>
      </div>

      <div class="mb-4">
        <label class="form-label">Remarks (optional)</label>
        <input name="remarks" class="form-control" placeholder="e.g. small scratches, needs repair">
      </div>

      <button class="btn btn-primary w-100">Add Item</button>
    </form>
  </div>

  <div class="card p-4">
    <h6 class="mb-3">Items List</h6>

    <?php if (!$items): ?>
      <div class="text-muted">No items yet.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
            <tr>
              <th>Item</th>
              <th>Qty</th>
              <th>Condition</th>
              <th>Remarks</th>
              <th class="text-end">Action</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $it): ?>
              <tr>
                <td><?= htmlspecialchars($it['item_name']) ?></td>
                <td><?= (int)$it['quantity'] ?></td>
                <td><span class="badge badge-soft"><?= htmlspecialchars($it['item_condition']) ?></span></td>
                <td class="text-muted small"><?= htmlspecialchars($it['remarks'] ?? '') ?></td>
                <td class="text-end">
                  <form method="post" class="d-inline" onsubmit="return confirm('Delete this item?');">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
                    <button class="btn btn-sm btn-outline-danger">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

</div>

<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
