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

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

$id = (int)($_POST['id'] ?? 0);
if (!$id) { header('Location: ' . BASE_URL . '/units_list.php'); exit; }

try {
  db()->beginTransaction();

  // delete photo rows + optionally files
  $photos = db()->prepare("
    SELECT ip.file_path
    FROM inspection_photos ip
    JOIN inspections i ON i.id = ip.inspection_id
    WHERE i.unit_id = ?
  ");
  $photos->execute([$id]);
  $paths = $photos->fetchAll();

  // delete DB rows
  db()->prepare("DELETE ip FROM inspection_photos ip JOIN inspections i ON i.id = ip.inspection_id WHERE i.unit_id = ?")->execute([$id]);
  db()->prepare("DELETE FROM inspections WHERE unit_id = ?")->execute([$id]);
  db()->prepare("DELETE FROM inventory_items WHERE unit_id = ?")->execute([$id]);
  db()->prepare("DELETE FROM tenants WHERE unit_id = ?")->execute([$id]);
  db()->prepare("DELETE FROM units WHERE id = ?")->execute([$id]);

  db()->commit();

  // remove files from disk (best-effort)
  foreach ($paths as $p) {
    $rel = $p['file_path'] ?? '';
    if ($rel) {
      $full = __DIR__ . '/' . $rel;
      if (is_file($full)) @unlink($full);
    }
  }

} catch (Throwable $e) {
  db()->rollBack();
  // Optional: log error
}

header('Location: ' . BASE_URL . '/units_list.php');
exit;
