<?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/LaundryBag.php';

require_login();
$user = current_user();

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

$bag = LaundryBag::getByUnit($unitId);
if ($bag) {
  header('Location: ' . BASE_URL . '/laundry_bag.php?bag_id=' . (int)$bag['id']);
  exit;
}

// Load unit info
$stmt = db()->prepare("
  SELECT 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]);
$unitInfo = $stmt->fetch();
if (!$unitInfo) exit('Unit not found.');

$ok = null;
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    $bagNumber = trim((string)($_POST['bag_number'] ?? ''));
    if ($bagNumber === '') throw new Exception('Bag number is required.');

    $bagId = LaundryBag::createOrUpdateBag($unitId, $bagNumber);
    header('Location: ' . BASE_URL . '/laundry_bag.php?bag_id=' . (int)$bagId);
    exit;

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

$pageTitle = 'Create Laundry Bag - ' . $unitInfo['unit_code'];
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container">

  <div class="card p-4 mb-3">
    <h5 class="page-title mb-1">Laundry Bag</h5>
    <div class="text-muted">
      <?= htmlspecialchars($unitInfo['building_name']) ?> • Unit <?= htmlspecialchars($unitInfo['unit_code']) ?>
    </div>
  </div>

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

  <div class="card p-4">
    <form method="post">
      <label class="form-label">Bag Number</label>
      <input class="form-control" name="bag_number" placeholder="e.g. 12345" required>
      <div class="form-text">One laundry bag per unit (items are tracked inside the bag).</div>

      <button class="btn btn-primary w-100 mt-3">Create Bag</button>
    </form>
  </div>

</div>

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