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

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

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

$buildings = Building::all();

$stmt = db()->prepare("SELECT * FROM units WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$unit = $stmt->fetch();
if (!$unit) exit('Unit not found.');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $buildingId = (int)($_POST['building_id'] ?? 0);
  $unitCode = trim($_POST['unit_code'] ?? '');
  $floor = trim($_POST['floor'] ?? '');
  $status = $_POST['status'] ?? 'vacant';
  $notes = trim($_POST['notes'] ?? '');

  if ($buildingId <= 0 || $unitCode === '') {
    $error = "Building and Unit Code are required.";
  } else {
    $upd = db()->prepare("UPDATE units SET building_id=?, unit_code=?, floor=?, status=?, notes=? WHERE id=?");
    $upd->execute([$buildingId, $unitCode, $floor, $status, $notes, $id]);
    $success = "Unit updated ✅";

    // reload
    $stmt->execute([$id]);
    $unit = $stmt->fetch();
  }
}

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

<div class="container-narrow mx-auto">
  <div class="mb-3 d-flex gap-2 flex-wrap">
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/units_list.php">← Back to Units List</a>
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/unit.php?id=<?= (int)$unit['id'] ?>">View Unit Profile</a>
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/unit_qr.php?id=<?= (int)$unit['id'] ?>">View/Print QR</a>
  </div>

  <div class="card p-4">
    <h5 class="page-title mb-3">Edit Unit</h5>

    <?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">
      <div class="mb-3">
        <label class="form-label">Building</label>
        <select name="building_id" class="form-select" required>
          <option value="">Select building</option>
          <?php foreach ($buildings as $b): ?>
            <option value="<?= (int)$b['id'] ?>" <?= ((int)$unit['building_id'] === (int)$b['id']) ? 'selected' : '' ?>>
              <?= htmlspecialchars($b['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="mb-3">
        <label class="form-label">Unit Code</label>
        <input name="unit_code" class="form-control" required value="<?= htmlspecialchars($unit['unit_code']) ?>">
      </div>

      <div class="mb-3">
        <label class="form-label">Floor</label>
        <input name="floor" class="form-control" value="<?= htmlspecialchars($unit['floor']) ?>">
      </div>

      <div class="mb-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="vacant" <?= ($unit['status']==='vacant')?'selected':'' ?>>Vacant</option>
          <option value="occupied" <?= ($unit['status']==='occupied')?'selected':'' ?>>Occupied</option>
          <option value="maintenance" <?= ($unit['status']==='maintenance')?'selected':'' ?>>Maintenance</option>
        </select>
      </div>

      <div class="mb-4">
        <label class="form-label">Notes</label>
        <textarea name="notes" class="form-control" rows="3"><?= htmlspecialchars($unit['notes'] ?? '') ?></textarea>
      </div>

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

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