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

require_login();

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

$user = current_user();
$buildings = Building::all();

$qrUrl = '';
$qrImg = '';
$selectedBuildingId = '';
$unitCodeVal = '';
$floorVal = '';
$statusVal = 'vacant';
$notesVal = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $selectedBuildingId = $_POST['building_id'] ?? '';
  $unitCodeVal = trim($_POST['unit_code'] ?? '');
  $floorVal = trim($_POST['floor'] ?? '');
  $statusVal = $_POST['status'] ?? 'vacant';
  $notesVal = trim($_POST['notes'] ?? '');

  $token = Unit::generateToken();

  $newUnitId = Unit::create([
    'building_id' => $selectedBuildingId,
    'unit_code'   => $unitCodeVal,
    'floor'       => $floorVal,
    'status'      => $statusVal,
    'qr_token'    => $token,
    'notes'       => $notesVal
  ]);

  // ✅ notify admins
  Notification::notifyAdmins(
    'unit_added',
    'New unit added',
    ($user['full_name'] ?? 'Admin') . " added unit {$unitCodeVal}.",
    "/unit.php?id=" . (int)$newUnitId,
    (int)($user['id'] ?? null)
  );

  $qrUrl = BASE_URL . '/scan.php?t=' . $token;
  $qrImg = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . urlencode($qrUrl);
}

$pageTitle = 'Add 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 ?>/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="card p-4">
    <h5 class="page-title mb-4">Add New Unit</h5>

    <?php if ($qrUrl): ?>
      <div class="alert alert-success">
        <strong>Unit created successfully ✅</strong>
        <hr class="my-2">

        <div class="small mb-1">QR Scan URL:</div>
        <a href="<?= htmlspecialchars($qrUrl) ?>" target="_blank"><?= htmlspecialchars($qrUrl) ?></a>

        <div class="mt-3 text-center">
          <div class="fw-semibold mb-2">QR Code</div>
          <img
            src="<?= htmlspecialchars($qrImg) ?>"
            alt="QR Code"
            class="img-fluid rounded border"
            style="max-width: 280px;"
          >

          <div class="mt-3 d-flex gap-2 justify-content-center flex-wrap">
            <a href="<?= htmlspecialchars($qrImg) ?>" class="btn btn-outline-primary" target="_blank">
              Open QR Image
            </a>
            <button type="button" onclick="window.print()" class="btn btn-primary">
              Print QR
            </button>
          </div>

          <div class="small text-muted mt-2">
            Tip: Print and place this QR on the unit door.
          </div>
        </div>
      </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'] ?>"
              <?= ((string)$selectedBuildingId === (string)$b['id']) ? 'selected' : '' ?>>
              <?= htmlspecialchars($b['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="mb-3">
        <label class="form-label">Unit Code</label>
        <input
          type="text"
          name="unit_code"
          class="form-control"
          required
          placeholder="e.g. A-101"
          value="<?= htmlspecialchars($unitCodeVal) ?>"
        >
      </div>

      <div class="mb-3">
        <label class="form-label">Floor</label>
        <input
          type="text"
          name="floor"
          class="form-control"
          placeholder="e.g. 1st Floor"
          value="<?= htmlspecialchars($floorVal) ?>"
        >
      </div>

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

      <div class="mb-4">
        <label class="form-label">Notes</label>
        <textarea
          name="notes"
          class="form-control"
          rows="3"
          placeholder="Optional notes about the unit"
        ><?= htmlspecialchars($notesVal) ?></textarea>
      </div>

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

</div>

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