<?php $this->start('body'); ?>
<?php $f = $this->data['form']; $g = $this->data['g']; $isNew = $this->data['is_new']; ?>
<?php $action = $isNew ? PROOT . 'Geofences/save' : PROOT . 'Geofences/update/' . (int)$g['c0d']; ?>

<div class="d-flex align-items-center justify-content-between mb-3">
  <h5 class="mb-0 fw-semibold"><i class="fas fa-<?= $isNew?'plus':'pen'; ?> me-2 text-muted"></i><?= $isNew ? 'New Geofence' : 'Edit · ' . htmlspecialchars($g['name']); ?></h5>
  <a href="<?= PROOT; ?>Geofences<?= $isNew?'':'/view/'.(int)$g['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
</div>

<?= $this->raw('fb_msg'); ?>

<div class="alert alert-info small">
  <i class="fas fa-info-circle me-1"></i>
  MVP supports <strong>circle geofences</strong> only (center + radius). Polygon editor lands in Iter 3.3.
  To pick coordinates: open <a href="https://www.google.com/maps" target="_blank" rel="noopener">Google Maps</a>, right-click any point → click the lat,lng chip to copy.
</div>

<form method="POST" action="<?= $action; ?>" class="card border-0 shadow-sm" autocomplete="off">
  <?= csrf_field(); ?>
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-6"><label class="form-label">Name <span class="text-danger">*</span></label>
        <input type="text" name="name" class="form-control" required value="<?= htmlspecialchars($f['name'] ?? ''); ?>" placeholder="e.g. Ubungo depot"></div>
      <div class="col-md-3"><label class="form-label">Kind</label>
        <select name="kind" class="form-select">
          <?php foreach (['depot'=>'Depot','customer_site'=>'Customer site','project_site'=>'Project site','no_go'=>'No-go zone','route_corridor'=>'Route corridor','fuel_station'=>'Fuel station','weighbridge'=>'Weighbridge'] as $k=>$v): ?>
            <option value="<?= $k; ?>" <?= ($f['kind'] ?? 'depot')===$k?'selected':''; ?>><?= $v; ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-3"><label class="form-label">Colour</label>
        <input type="color" name="color" class="form-control form-control-color" value="<?= htmlspecialchars($f['color'] ?? '#2626F5'); ?>"></div>

      <div class="col-md-4"><label class="form-label">Center latitude <span class="text-danger">*</span></label>
        <input type="text" name="center_lat" class="form-control font-monospace" required value="<?= htmlspecialchars((string)($f['center_lat'] ?? '')); ?>" placeholder="-6.7924"></div>
      <div class="col-md-4"><label class="form-label">Center longitude <span class="text-danger">*</span></label>
        <input type="text" name="center_lng" class="form-control font-monospace" required value="<?= htmlspecialchars((string)($f['center_lng'] ?? '')); ?>" placeholder="39.2083"></div>
      <div class="col-md-4"><label class="form-label">Radius (metres) <span class="text-danger">*</span></label>
        <input type="text" name="radius_m" class="form-control js-int" required value="<?= htmlspecialchars((string)($f['radius_m'] ?? 250)); ?>" placeholder="250"></div>

      <div class="col-md-4"><label class="form-label">Linked customer (if customer site)</label>
        <select name="customer_id" class="form-select">
          <option value="">— none —</option>
          <?php foreach ($this->data['customers'] as $c): ?>
            <option value="<?= (int)$c['c0d']; ?>" <?= ($f['customer_id'] ?? '')==$c['c0d']?'selected':''; ?>><?= htmlspecialchars($c['customer_name']); ?></option>
          <?php endforeach; ?>
        </select></div>
      <div class="col-md-4 d-flex align-items-end">
        <div class="form-check">
          <input type="checkbox" name="trigger_alert" value="1" class="form-check-input" id="chkTa" <?= !empty($f['trigger_alert'])?'checked':''; ?>>
          <label class="form-check-label" for="chkTa">Fire alert on enter/exit</label>
        </div></div>
      <div class="col-md-4 d-flex align-items-end">
        <div class="form-check">
          <input type="checkbox" name="active" value="1" class="form-check-input" id="chkAc" <?= (!isset($f['active']) || !empty($f['active']))?'checked':''; ?>>
          <label class="form-check-label" for="chkAc">Active</label>
        </div></div>

      <div class="col-12"><label class="form-label">Notes</label>
        <textarea name="notes" rows="2" class="form-control" placeholder="Landmarks, access notes, opening hours…"><?= htmlspecialchars($f['notes'] ?? ''); ?></textarea></div>
    </div>
    <div class="row g-2 mt-2">
      <div class="col-12 small text-muted">
        <i class="fas fa-map-pin me-1"></i>Preview:
        <span id="previewLink" class="text-muted fst-italic">enter coordinates to preview</span>
      </div>
    </div>
  </div>
  <div class="card-footer bg-white d-flex justify-content-end gap-2 py-3">
    <a href="<?= PROOT; ?>Geofences<?= $isNew?'':'/view/'.(int)$g['c0d']; ?>" class="btn btn-outline-secondary">Cancel</a>
    <button class="btn btn-primary"><i class="fas fa-save me-1"></i><?= $isNew ? 'Create geofence' : 'Save changes'; ?></button>
  </div>
</form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
document.querySelectorAll('.js-int').forEach(el => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 0 }));

const latIn = document.querySelector('[name="center_lat"]');
const lngIn = document.querySelector('[name="center_lng"]');
const link  = document.getElementById('previewLink');
function refreshPreview() {
    const lat = parseFloat(latIn.value), lng = parseFloat(lngIn.value);
    if (isNaN(lat) || isNaN(lng)) { link.innerHTML = '<span class="fst-italic">enter coordinates to preview</span>'; return; }
    link.innerHTML = `<a href="https://www.google.com/maps/search/?api=1&query=${lat},${lng}" target="_blank" rel="noopener"><i class="fas fa-external-link-alt me-1"></i>Open ${lat.toFixed(5)}, ${lng.toFixed(5)} on Google Maps</a>`;
}
latIn.addEventListener('input', refreshPreview);
lngIn.addEventListener('input', refreshPreview);
// Paste "lat,lng" into the lat field and it auto-splits
latIn.addEventListener('paste', e => {
    const t = (e.clipboardData.getData('text') || '').trim();
    const m = t.match(/^\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*$/);
    if (m) { e.preventDefault(); latIn.value = m[1]; lngIn.value = m[2]; refreshPreview(); }
});
refreshPreview();
</script>
<?php $this->end(); ?>
