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

require_login();
$user = current_user();

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

$ok = null;
$error = null;

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

    if ($action === 'create') {
      $code = strtolower(trim((string)($_POST['code'] ?? '')));
      $name = trim((string)($_POST['name'] ?? ''));
      $sort = (int)($_POST['sort_order'] ?? 0);
      $active = isset($_POST['is_active']) ? 1 : 0;

      if ($code === '' || $name === '') throw new Exception("Code and Name are required.");
      if (!preg_match('/^[a-z0-9_]+$/', $code)) throw new Exception("Code must be lowercase letters/numbers/underscore only.");

      LaundryItemType::create($code, $name, $sort, $active);
      $ok = "Item type added.";
    }

    if ($action === 'update') {
      $code = strtolower(trim((string)($_POST['code'] ?? '')));
      $name = trim((string)($_POST['name'] ?? ''));
      $sort = (int)($_POST['sort_order'] ?? 0);
      $active = isset($_POST['is_active']) ? 1 : 0;

      if ($code === '' || $name === '') throw new Exception("Code and Name are required.");

      LaundryItemType::update($code, $name, $sort, $active);
      $ok = "Item type updated.";
    }

    if ($action === 'delete') {
      $code = strtolower(trim((string)($_POST['code'] ?? '')));
      if ($code === '') throw new Exception("Missing code.");
      LaundryItemType::delete($code);
      $ok = "Item type deleted.";
    }

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

$items = LaundryItemType::all();

$pageTitle = 'Laundry Bag Items (CRUD)';
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container">

  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between flex-wrap gap-2">
      <div>
        <h5 class="page-title mb-1">Bag Item Types</h5>
        <div class="text-muted">CRUD for items that can be inside a laundry bag.</div>
      </div>
      <div class="d-flex gap-2">
        <a class="btn btn-outline-primary" href="<?= BASE_URL ?>/laundry.php">Laundry Dashboard</a>
        <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/laundry_worklist.php">Worklist</a>
      </div>
    </div>
  </div>

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

  <!-- Add new -->
  <div class="card p-4 mb-3">
    <h6 class="mb-3">Add Item Type</h6>
    <form method="post" class="row g-2">
      <input type="hidden" name="_action" value="create">

      <div class="col-md-3">
        <label class="form-label">Code (unique)</label>
        <input class="form-control" name="code" placeholder="e.g. robe" required>
        <div class="form-text">lowercase letters/numbers/_ only</div>
      </div>

      <div class="col-md-5">
        <label class="form-label">Name</label>
        <input class="form-control" name="name" placeholder="e.g. Robe" required>
      </div>

      <div class="col-md-2">
        <label class="form-label">Sort</label>
        <input type="number" class="form-control" name="sort_order" value="0">
      </div>

      <div class="col-md-2 d-flex align-items-end">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" name="is_active" id="active_new" checked>
          <label class="form-check-label" for="active_new">Active</label>
        </div>
      </div>

      <div class="col-12">
        <button class="btn btn-primary">Add</button>
      </div>
    </form>
  </div>

  <!-- List + Edit -->
  <div class="card p-4">
    <h6 class="mb-3">Existing Item Types</h6>

    <?php if (!$items): ?>
      <div class="text-muted">No item types yet.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-striped align-middle">
          <thead>
            <tr>
              <th>Code</th>
              <th>Name</th>
              <th>Sort</th>
              <th>Active</th>
              <th style="width:320px;">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($items as $it): ?>
              <tr>
                <form method="post">
                  <input type="hidden" name="_action" value="update">
                  <td>
                    <input class="form-control form-control-sm" name="code" value="<?= htmlspecialchars($it['code']) ?>" readonly>
                  </td>
                  <td>
                    <input class="form-control form-control-sm" name="name" value="<?= htmlspecialchars($it['name']) ?>">
                  </td>
                  <td>
                    <input type="number" class="form-control form-control-sm" name="sort_order" value="<?= (int)$it['sort_order'] ?>">
                  </td>
                  <td>
                    <input class="form-check-input" type="checkbox" name="is_active" <?= (int)$it['is_active'] === 1 ? 'checked' : '' ?>>
                  </td>
                  <td class="d-flex gap-2 flex-wrap">
                    <button class="btn btn-sm btn-primary">Save</button>
                </form>

                <form method="post" onsubmit="return confirm('Delete this item type?');">
                  <input type="hidden" name="_action" value="delete">
                  <input type="hidden" name="code" value="<?= htmlspecialchars($it['code']) ?>">
                  <button class="btn btn-sm btn-outline-danger">Delete</button>
                </form>

                  </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="text-muted small">
        If delete fails, it means the item type is already used in bags/transactions — deactivate instead.
      </div>
    <?php endif; ?>

  </div>

</div>

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