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

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

$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Building::create(
        trim($_POST['name']),
        trim($_POST['address']),
        trim($_POST['notes'])
    );
    $success = true;
}

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

<div class="mb-3 d-flex gap-2 flex-wrap">
  <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/dashboard.php">← Back to Dashboard</a>
  <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/units_list.php">Units List</a>
</div>


<div class="container-narrow mx-auto">
  <div class="card p-4">
    <h5 class="page-title mb-4">Add Building</h5>

    <?php if ($success): ?>
      <div class="alert alert-success">Building added successfully ✅</div>
    <?php endif; ?>

    <form method="post">
      <div class="mb-3">
        <label class="form-label">Building Name</label>
        <input name="name" class="form-control" required>
      </div>

      <div class="mb-3">
        <label class="form-label">Address</label>
        <input name="address" class="form-control">
      </div>

      <div class="mb-4">
        <label class="form-label">Notes</label>
        <textarea name="notes" class="form-control" rows="3"></textarea>
      </div>

      <button class="btn btn-primary w-100">Save Building</button>
    </form>
  </div>
</div>

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