<?php
/**
 * لوحة المناطق الجغرافية
 */
// لا نحتاج للتحقق من user_id هنا لأن dashboard.php يقوم بذلك
if (isset($_SESSION['user_id']) && isset($conn)) {
    if (!class_exists('GeofencingService')) {
        require_once __DIR__ . '/geofencing_service.php';
    }
    try {
        $geofencingService = new GeofencingService($conn, $_SESSION['user_id']);
        $geofences = $geofencingService->getGeofences();
    } catch (Exception $e) {
        error_log("❌ خطأ في جلب المناطق الجغرافية: " . $e->getMessage());
        $geofences = [];
    }
} else {
    $geofences = [];
}
?>

<div id="geofencingPanel" class="modal-panel" style="display:none;">
  <div class="modal-content" style="max-width:900px;">
    <div class="modal-header">
      <h2>📍 المناطق الجغرافية (Geofencing)</h2>
      <button onclick="closeGeofencingPanel()" class="close-btn">✕</button>
    </div>
    <div class="modal-body">
      <div class="geofencing-controls">
        <button onclick="showAddGeofenceForm()" class="primary">➕ إضافة منطقة</button>
      </div>
      
      <div id="geofencesList">
        <?php if (empty($geofences)): ?>
          <p style="text-align:center; padding:20px; color:#666;">لا توجد مناطق جغرافية محددة</p>
        <?php else: ?>
          <?php foreach ($geofences as $geofence): ?>
            <div class="geofence-item" data-geofence-id="<?= $geofence['id'] ?>">
              <div class="geofence-header">
                <strong><?= htmlspecialchars($geofence['name'], ENT_QUOTES, 'UTF-8') ?></strong>
                <span class="geofence-type"><?= $geofence['type'] === 'safe_zone' ? 'منطقة آمنة' : ($geofence['type'] === 'restricted_zone' ? 'منطقة محظورة' : 'مخصصة') ?></span>
              </div>
              <div class="geofence-info">
                <div>📍 الموقع: <?= $geofence['latitude'] ?>, <?= $geofence['longitude'] ?></div>
                <div>📏 نصف القطر: <?= $geofence['radius'] ?> متر</div>
                <div>🔔 تنبيه عند الدخول: <?= $geofence['alert_on_enter'] ? 'نعم' : 'لا' ?></div>
                <div>🚪 تنبيه عند الخروج: <?= $geofence['alert_on_exit'] ? 'نعم' : 'لا' ?></div>
              </div>
              <div class="geofence-actions">
                <button onclick="showGeofenceOnMap(<?= $geofence['id'] ?>, <?= $geofence['latitude'] ?>, <?= $geofence['longitude'] ?>, <?= $geofence['radius'] ?>)" class="btn-view">📍 عرض على الخريطة</button>
                <button onclick="deleteGeofence(<?= $geofence['id'] ?>)" class="btn-delete">🗑️ حذف</button>
              </div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
      
      <div id="addGeofenceForm" style="display:none;">
        <h3>إضافة منطقة جغرافية جديدة</h3>
        <form onsubmit="addGeofence(event)">
          <div class="form-group">
            <label>اسم المنطقة:</label>
            <input type="text" id="geofenceName" required>
          </div>
          <div class="form-group">
            <label>النوع:</label>
            <select id="geofenceType">
              <option value="safe_zone">منطقة آمنة</option>
              <option value="restricted_zone">منطقة محظورة</option>
              <option value="custom">مخصصة</option>
            </select>
          </div>
          <div class="form-group">
            <label>خط العرض:</label>
            <input type="number" id="geofenceLat" step="any" required>
          </div>
          <div class="form-group">
            <label>خط الطول:</label>
            <input type="number" id="geofenceLng" step="any" required>
          </div>
          <div class="form-group">
            <label>نصف القطر (متر):</label>
            <input type="number" id="geofenceRadius" value="100" min="10" required>
          </div>
          <div class="form-group">
            <label>
              <input type="checkbox" id="geofenceAlertEnter" checked>
              تنبيه عند الدخول
            </label>
          </div>
          <div class="form-group">
            <label>
              <input type="checkbox" id="geofenceAlertExit" checked>
              تنبيه عند الخروج
            </label>
          </div>
          <div class="form-actions">
            <button type="submit" class="primary">💾 حفظ</button>
            <button type="button" onclick="hideAddGeofenceForm()" class="secondary">إلغاء</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<style>
.geofence-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  background: #f9f9f9;
}

.geofence-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.geofence-type {
  background: #007bff;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.geofence-info {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.geofence-info div {
  margin-bottom: 5px;
}

.geofence-actions {
  display: flex;
  gap: 10px;
}

.btn-view {
  background: #007bff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 5px;
  cursor: pointer;
}

.btn-delete {
  background: #dc3545;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 5px;
  cursor: pointer;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}
</style>

<script>
let geofenceCircles = [];

function showGeofencing() {
  document.getElementById('geofencingPanel').style.display = 'flex';
}

function closeGeofencingPanel() {
  document.getElementById('geofencingPanel').style.display = 'none';
}

function showAddGeofenceForm() {
  document.getElementById('addGeofenceForm').style.display = 'block';
  // إذا كان هناك موقع محدد على الخريطة، استخدمه
  if (typeof latestMarker !== 'undefined' && latestMarker) {
    const pos = latestMarker.getPosition();
    document.getElementById('geofenceLat').value = pos.lat();
    document.getElementById('geofenceLng').value = pos.lng();
  }
}

function hideAddGeofenceForm() {
  document.getElementById('addGeofenceForm').style.display = 'none';
}

function addGeofence(event) {
  event.preventDefault();
  
  const formData = {
    name: document.getElementById('geofenceName').value,
    type: document.getElementById('geofenceType').value,
    latitude: document.getElementById('geofenceLat').value,
    longitude: document.getElementById('geofenceLng').value,
    radius: document.getElementById('geofenceRadius').value,
    alert_on_enter: document.getElementById('geofenceAlertEnter').checked ? 1 : 0,
    alert_on_exit: document.getElementById('geofenceAlertExit').checked ? 1 : 0
  };
  
  fetch('add_geofence.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData)
  })
  .then(res => res.json())
  .then(data => {
    if (data.status === 'success') {
      location.reload();
    } else {
      alert('خطأ: ' + data.message);
    }
  });
}

function showGeofenceOnMap(id, lat, lng, radius) {
  if (typeof map === 'undefined' || !map) {
    alert('الخريطة غير جاهزة');
    return;
  }
  
  // رسم دائرة على الخريطة
  const circle = new google.maps.Circle({
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35,
    map: map,
    center: { lat: parseFloat(lat), lng: parseFloat(lng) },
    radius: parseInt(radius)
  });
  
  geofenceCircles.push(circle);
  
  // تمركز الخريطة على المنطقة
  map.setCenter({ lat: parseFloat(lat), lng: parseFloat(lng) });
  map.setZoom(15);
  
  closeGeofencingPanel();
}

function deleteGeofence(id) {
  if (!confirm('هل أنت متأكد من حذف هذه المنطقة؟')) {
    return;
  }
  
  fetch('delete_geofence.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ id: id })
  })
  .then(res => res.json())
  .then(data => {
    if (data.status === 'success') {
      document.querySelector(`.geofence-item[data-geofence-id="${id}"]`).remove();
    } else {
      alert('خطأ: ' + data.message);
    }
  });
}
</script>

