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

$hasAudit = file_exists(__DIR__ . '/../app/models/AuditLog.php');
if ($hasAudit) require_once __DIR__ . '/../app/models/AuditLog.php';

require_login();
$user = function_exists('current_user') ? current_user() : ($_SESSION['user'] ?? []);
$userId = isset($user['id']) ? (int)$user['id'] : 0;

$pageTitle = 'New Inspection';

function loadUnitById(int $id): ?array
{
  if ($id <= 0) return null;

  try {
    $stmt = db()->prepare("
      SELECT u.*, b.name AS building_name
      FROM units u
      JOIN buildings b ON b.id = u.building_id
      WHERE u.id = ?
      LIMIT 1
    ");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    return $row ?: null;
  } catch (Throwable $e) {
    return null;
  }
}

$unitId = (int)($_GET['unit_id'] ?? 0);
$unit = loadUnitById($unitId);

$ok = false;
$error = null;

if (!$unit) {
  http_response_code(404);
  $error = "Unit not found (ID: {$unitId}).";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $unit) {
  $notes = trim($_POST['notes'] ?? '');

  // multiple
  $before = $_FILES['before_photo'] ?? null;
  $after  = $_FILES['after_photo'] ?? null;

  $beforeMissing = !$before || empty($before['name']) || (is_array($before['name']) && count(array_filter($before['name'])) === 0);
  $afterMissing  = !$after  || empty($after['name'])  || (is_array($after['name'])  && count(array_filter($after['name'])) === 0);

  if ($beforeMissing || $afterMissing) {
    $error = "Before and After photos are required (you can upload multiple).";
  } else {
    try {
      if ($userId <= 0) throw new Exception("Missing logged-in user id (staff_user_id).");

      $geoLat = isset($_POST['geo_lat']) && $_POST['geo_lat'] !== '' ? (float)$_POST['geo_lat'] : null;
      $geoLng = isset($_POST['geo_lng']) && $_POST['geo_lng'] !== '' ? (float)$_POST['geo_lng'] : null;
      $geoAcc = isset($_POST['geo_accuracy']) && $_POST['geo_accuracy'] !== '' ? (int)$_POST['geo_accuracy'] : null;

      $geoAddress = trim($_POST['geo_address'] ?? '');
      $geoAddress = $geoAddress !== '' ? $geoAddress : null;

      $inspectionId = Inspection::create(
        (int)$unit['id'],
        (int)$userId,
        $notes,
        $before,
        $after,
        $geoLat,
        $geoLng,
        $geoAcc,
        $geoAddress
      );

      if ($hasAudit && class_exists('AuditLog')) {
        AuditLog::log($userId, 'CREATE_INSPECTION', [
          'inspection_id' => (int)$inspectionId,
          'unit_id' => (int)$unit['id'],
          'unit_code' => $unit['unit_code'] ?? null,
          'geo_lat' => $geoLat,
          'geo_lng' => $geoLng,
          'geo_accuracy' => $geoAcc,
          'geo_address' => $geoAddress,
        ]);
      }

      $ok = true;

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

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

<div class="container">

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

  <?php if ($unit): ?>
    <div class="card p-4">
      <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
        <div>
          <h5 class="mb-1">Unit Inspection</h5>
          <div class="text-muted small">
            <div><strong>Building:</strong> <?= htmlspecialchars($unit['building_name'] ?? '-') ?></div>
            <div><strong>Unit:</strong> <?= htmlspecialchars($unit['unit_code'] ?? '-') ?></div>
          </div>
        </div>

        <div class="text-muted small text-end">
          <div id="geoStatus">Getting location…</div>
          <div id="geoAddr" class="small"></div>
        </div>
      </div>

      <?php if ($ok): ?>
        <div class="alert alert-success mt-3 mb-0">
          Inspection saved ✅
        </div>
      <?php endif; ?>

      <form id="inspectionForm" method="post" enctype="multipart/form-data" class="mt-3">

        <!-- hidden geo fields -->
        <input type="hidden" name="geo_lat" id="geo_lat">
        <input type="hidden" name="geo_lng" id="geo_lng">
        <input type="hidden" name="geo_accuracy" id="geo_accuracy">
        <input type="hidden" name="geo_address" id="geo_address">

        <label class="form-label">Before Photos (required, multiple allowed)</label>
        <input
          type="file"
          name="before_photo[]"
          class="form-control"
          accept="image/jpeg,image/png,image/webp"
          multiple
          required
        >
        <div class="form-text">JPG/PNG/WEBP • Max <?= (int)(defined('MAX_UPLOAD_MB') ? MAX_UPLOAD_MB : 8) ?>MB each</div>

        <label class="form-label mt-3">After Photos (required, multiple allowed)</label>
        <input
          type="file"
          name="after_photo[]"
          class="form-control"
          accept="image/jpeg,image/png,image/webp"
          multiple
          required
        >
        <div class="form-text">JPG/PNG/WEBP • Max <?= (int)(defined('MAX_UPLOAD_MB') ? MAX_UPLOAD_MB : 8) ?>MB each</div>

        <label class="form-label mt-3">Notes</label>
        <textarea name="notes" class="form-control" rows="6"><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>

        <div class="d-flex gap-2 mt-3">
          <button class="btn btn-primary" id="saveBtn">Save Inspection</button>
          <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/scan.php?t=<?= urlencode($unit['qr_token'] ?? '') ?>">
            Back to Scan Result
          </a>
        </div>

        <div class="form-text mt-2">
          If location permission is denied, the inspection will still save but without address.
        </div>

      </form>
    </div>
  <?php endif; ?>

</div>

<script>
(function() {
  const statusEl = document.getElementById('geoStatus');
  const addrEl = document.getElementById('geoAddr');

  const latEl = document.getElementById('geo_lat');
  const lngEl = document.getElementById('geo_lng');
  const accEl = document.getElementById('geo_accuracy');
  const addressEl = document.getElementById('geo_address');

  const form = document.getElementById('inspectionForm');

  let hasGeo = false;
  let hasAddress = false;
  let inFlight = false;

  function setStatus(msg) {
    if (statusEl) statusEl.textContent = msg;
  }
  function setAddr(msg) {
    if (addrEl) addrEl.textContent = msg;
  }

  async function reverseGeocode(lat, lng) {
    try {
      const url = `<?= BASE_URL ?>/geo_reverse.php?lat=${encodeURIComponent(lat)}&lng=${encodeURIComponent(lng)}`;
      const res = await fetch(url, { credentials: 'same-origin' });
      const json = await res.json();
      if (json && json.ok && json.address) return String(json.address);
    } catch (e) {}
    return '';
  }

  async function getGeoAndAddress() {
    if (inFlight) return;
    inFlight = true;

    try {
      if (!navigator.geolocation) {
        setStatus('Location not supported.');
        setAddr('');
        inFlight = false;
        return;
      }

      setStatus('Getting location…');
      setAddr('');

      const pos = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0
        });
      });

      const c = pos.coords || {};
      latEl.value = c.latitude ?? '';
      lngEl.value = c.longitude ?? '';
      accEl.value = c.accuracy ? Math.round(c.accuracy) : '';

      hasGeo = !!(latEl.value && lngEl.value);
      if (!hasGeo) {
        setStatus('Location not available.');
        setAddr('');
        inFlight = false;
        return;
      }

      setStatus(`Location saved (±${accEl.value || '?'}m). Getting address…`);

      const addr = await reverseGeocode(latEl.value, lngEl.value);
      if (addr) {
        addressEl.value = addr;
        hasAddress = true;
        setStatus(`Location saved (±${accEl.value || '?'}m).`);
        setAddr(addr);
      } else {
        addressEl.value = '';
        hasAddress = false;
        setStatus(`Location saved (±${accEl.value || '?'}m). Address not available.`);
        setAddr('');
      }

    } catch (err) {
      setStatus('Location not available (permission denied or timeout).');
      setAddr('');
      hasGeo = false;
      hasAddress = false;
    } finally {
      inFlight = false;
    }
  }

  // Try on load
  getGeoAndAddress();

  // Ensure we try before submit if missing
  form?.addEventListener('submit', async function(e) {
    const hasLatLng = !!(latEl.value && lngEl.value);
    const hasAddr = !!(addressEl.value);

    // We only block submit if there is ZERO geo yet (so we can attempt).
    // If geo exists but address failed, we still submit.
    if (hasLatLng) return;

    e.preventDefault();
    await getGeoAndAddress();
    form.submit();
  });
})();
</script>

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