<?php
require_once __DIR__ . "/../includes/config.php";
session_start_secure();
$user = current_user();
if (!$user) { header("Location: ../login.php"); exit; }
$lang  = $user["lang_pref"]  ?? "ar";
$theme = $user["theme_pref"] ?? "light";
?>
<!DOCTYPE html>
<html lang="<?php echo htmlspecialchars($lang); ?>" dir="rtl" data-theme="<?php echo htmlspecialchars($theme); ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="theme-color" content="#dc2626">
<title>بيطري — خريطة الطوارئ</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css">
<style>
:root{
  --green-500:#1a9f6a;--green-600:#1a7f5a;--green-700:#155f44;
  --red-500:#ef4444;--red-600:#dc2626;--red-glow:rgba(239,68,68,.35);
  --bg:#f7faf9;--bg-card:#fff;--bg-input:#f3f7f5;
  --border:#e0ece7;--text-primary:#0e2d20;--text-sec:#4a7060;--text-muted:#8aaa9a;
  --shadow-md:0 4px 20px rgba(0,60,30,.10);--shadow-lg:0 8px 40px rgba(0,60,30,.15);
  --shadow-xl:0 20px 60px rgba(0,60,30,.20);
  --radius-sm:10px;--radius-md:16px;--radius-lg:24px;
  --transition:.22s cubic-bezier(.4,0,.2,1);
}
[data-theme="dark"]{
  --bg:#0a1a12;--bg-card:#122010;--bg-input:#1a2e1e;
  --border:#1e3828;--text-primary:#e0f2e9;--text-sec:#8abfa0;--text-muted:#4a7060;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Tajawal',sans-serif;background:var(--bg);color:var(--text-primary);overflow:hidden;height:100dvh;-webkit-font-smoothing:antialiased;}
button{cursor:pointer;border:none;background:none;font-family:inherit;}

/* MAP */
#map{
  position:fixed;inset:0;
  z-index:0;
  filter:var(--map-filter,none);
}
[data-theme="dark"] #map{filter:invert(1) hue-rotate(180deg) brightness(.7) contrast(1.1);}
[data-theme="dark"] #map img{filter:invert(1) hue-rotate(180deg);}

/* TOP BAR */
.map-topbar{
  position:fixed;top:0;left:0;right:0;
  z-index:100;
  padding:12px 16px;
  background:linear-gradient(to bottom,rgba(0,0,0,.5) 0%,transparent 100%);
  display:flex;align-items:center;gap:10px;
}
.back-btn{
  width:40px;height:40px;
  background:rgba(255,255,255,.9);
  border-radius:12px;
  display:flex;align-items:center;justify-content:center;
  font-size:18px;cursor:pointer;
  box-shadow:var(--shadow-md);
  backdrop-filter:blur(8px);
  flex-shrink:0;
}
.map-title{
  flex:1;
  background:rgba(255,255,255,.9);
  border-radius:12px;
  padding:10px 14px;
  font-size:14px;font-weight:800;color:var(--text-primary);
  box-shadow:var(--shadow-md);
  backdrop-filter:blur(8px);
}
.map-title span{color:var(--red-600);}

/* FLOATING BUTTONS */
.map-fabs{
  position:fixed;bottom:260px;left:16px;
  z-index:100;
  display:flex;flex-direction:column;gap:8px;
}
[dir="ltr"] .map-fabs{left:auto;right:16px;}
.fab{
  width:44px;height:44px;
  background:var(--bg-card);
  border-radius:12px;
  display:flex;align-items:center;justify-content:center;
  font-size:20px;
  box-shadow:var(--shadow-lg);
  cursor:pointer;
  transition:var(--transition);
  border:1px solid var(--border);
}
.fab:hover{transform:scale(1.05);}

/* LOCATION PULSE */
.my-location-marker{
  width:20px;height:20px;
  background:var(--green-600);
  border-radius:50%;
  border:3px solid white;
  box-shadow:0 0 0 0 rgba(26,127,90,.4);
  animation:location-pulse 2s ease-out infinite;
}
@keyframes location-pulse{
  0%{box-shadow:0 0 0 0 rgba(26,127,90,.4);}
  70%{box-shadow:0 0 0 20px rgba(26,127,90,0);}
  100%{box-shadow:0 0 0 0 rgba(26,127,90,0);}
}

/* BOTTOM PANEL */
.bottom-panel{
  position:fixed;bottom:0;left:0;right:0;
  z-index:100;
  background:var(--bg-card);
  border-radius:28px 28px 0 0;
  padding:8px 0 max(20px,env(safe-area-inset-bottom));
  box-shadow:0 -8px 40px rgba(0,0,0,.15);
  max-height:60dvh;
  overflow-y:auto;
}
.panel-handle{
  width:40px;height:4px;background:var(--border);
  border-radius:2px;margin:6px auto 14px;
}
.panel-header{
  display:flex;align-items:center;justify-content:space-between;
  padding:0 16px 14px;
  border-bottom:1px solid var(--border);
}
.panel-title{font-size:16px;font-weight:800;}
.panel-count{
  background:var(--red-600);color:#fff;
  border-radius:20px;padding:4px 12px;
  font-size:12px;font-weight:800;
}

/* VET NEARBY CARDS */
.nearby-scroll{
  display:flex;gap:10px;
  padding:14px 16px;
  overflow-x:auto;scrollbar-width:none;
}
.nearby-scroll::-webkit-scrollbar{display:none;}
.nearby-card{
  flex:0 0 200px;
  background:var(--bg-input);
  border-radius:var(--radius-md);
  padding:14px;
  border:1px solid var(--border);
  cursor:pointer;
  transition:var(--transition);
  position:relative;
}
.nearby-card.emergency-vet{
  border-color:var(--red-500);
  background:linear-gradient(135deg,rgba(239,68,68,.05),rgba(239,68,68,.02));
}
.nearby-card:hover{transform:translateY(-2px);box-shadow:var(--shadow-md);}
.nc-avatar{
  width:44px;height:44px;border-radius:14px;
  background:var(--green-50);
  display:flex;align-items:center;justify-content:center;
  font-size:24px;margin-bottom:10px;
}
.nc-name{font-size:14px;font-weight:800;color:var(--text-primary);}
.nc-spec{font-size:11px;color:var(--green-600);font-weight:600;margin-top:2px;}
.nc-meta{display:flex;align-items:center;gap:8px;margin-top:8px;flex-wrap:wrap;}
.nc-dist{font-size:11px;color:var(--text-sec);}
.nc-avail{
  font-size:10px;font-weight:700;padding:2px 8px;border-radius:20px;
}
.nc-avail.on{background:#dcfce7;color:#15803d;}
.nc-avail.off{background:#f1f5f9;color:#64748b;}
.nc-emg-badge{
  position:absolute;top:10px;left:10px;
  background:var(--red-600);color:#fff;
  font-size:10px;font-weight:800;
  padding:2px 8px;border-radius:20px;
}
.btn-call-vet{
  width:100%;margin-top:10px;
  background:linear-gradient(135deg,var(--green-700),var(--green-500));
  color:white;border-radius:var(--radius-sm);
  padding:9px;font-size:13px;font-weight:800;
  text-align:center;transition:var(--transition);
}
.btn-call-vet:hover{opacity:.9;}
.btn-call-emg{
  background:linear-gradient(135deg,var(--red-600),var(--red-500));
}

/* Emergency send form overlay */
.emg-overlay{
  position:fixed;inset:0;z-index:200;
  background:rgba(0,0,0,.6);
  backdrop-filter:blur(4px);
  display:none;align-items:flex-end;justify-content:center;
}
.emg-overlay.open{display:flex;}
.emg-sheet{
  width:100%;max-width:480px;
  background:var(--bg-card);
  border-radius:28px 28px 0 0;
  padding:0 0 max(24px,env(safe-area-inset-bottom));
  animation:slideUp .35s ease both;
}
@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}
.emg-sheet-header{
  background:linear-gradient(135deg,var(--red-600),var(--red-500));
  border-radius:28px 28px 0 0;
  padding:18px 20px;
  display:flex;align-items:center;gap:12px;
}
.emg-sheet-title{font-size:18px;font-weight:800;color:#fff;flex:1;}
.emg-close{
  width:32px;height:32px;background:rgba(255,255,255,.2);
  border-radius:8px;display:flex;align-items:center;justify-content:center;
  font-size:16px;color:#fff;cursor:pointer;
}
.emg-body{padding:20px;}
.form-group{margin-bottom:14px;}
.form-label{font-size:13px;font-weight:700;color:var(--text-sec);margin-bottom:6px;display:block;}
.form-input,.form-textarea{
  width:100%;background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);padding:12px 14px;
  font-size:14px;color:var(--text-primary);font-family:'Tajawal',sans-serif;
  transition:var(--transition);outline:none;
}
.form-input:focus,.form-textarea:focus{border-color:var(--red-500);background:var(--bg-card);}
.form-textarea{resize:none;min-height:80px;}
.btn-send-emg{
  width:100%;background:linear-gradient(135deg,var(--red-600),var(--red-500));
  color:#fff;border-radius:var(--radius-sm);padding:15px;
  font-size:16px;font-weight:800;text-align:center;
  box-shadow:0 4px 16px var(--red-glow);
  animation:pulse-emg 2s infinite;
}
@keyframes pulse-emg{
  0%,100%{box-shadow:0 4px 16px var(--red-glow);}
  50%{box-shadow:0 4px 28px rgba(239,68,68,.5);}
}
.btn-send-emg:hover{animation:none;opacity:.9;}

/* Locate badge */
.loc-badge{
  display:flex;align-items:center;gap:8px;
  background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);padding:10px 14px;margin-bottom:14px;
  cursor:pointer;transition:var(--transition);
}
.loc-badge:hover{border-color:var(--red-500);}
.loc-icon{font-size:18px;color:var(--red-500);}
.loc-text{font-size:13px;font-weight:700;color:var(--text-sec);flex:1;}
.loc-ok{font-size:11px;color:var(--green-600);font-weight:700;background:var(--green-50);padding:3px 8px;border-radius:20px;}

/* Toast */
#toast{
  position:fixed;top:70px;left:50%;transform:translateX(-50%);
  background:var(--bg-card);border-radius:var(--radius-md);
  padding:12px 18px;display:flex;align-items:center;gap:10px;
  box-shadow:var(--shadow-xl);border:1px solid var(--border);
  font-size:13px;font-weight:700;z-index:9999;
  opacity:0;transition:opacity .3s;pointer-events:none;
  width:90%;max-width:360px;
}
#toast.show{opacity:1;pointer-events:auto;}

/* Leaflet custom marker */
.vet-marker{
  width:40px;height:40px;
  background:var(--green-600);
  border-radius:50% 50% 50% 0;
  transform:rotate(-45deg);
  border:3px solid white;
  box-shadow:0 3px 12px rgba(0,0,0,.3);
  display:flex;align-items:center;justify-content:center;
  cursor:pointer;
}
.vet-marker-inner{
  transform:rotate(45deg);
  font-size:18px;
}
.vet-marker.emg-vet{background:var(--red-600);}
</style>
</head>
<body>

<div id="toast"><span id="ti">✅</span><span id="tm"></span></div>

<!-- MAP -->
<div id="map"></div>

<!-- TOP BAR -->
<div class="map-topbar">
  <div class="back-btn" onclick="history.back()">←</div>
  <div class="map-title">🗺️ أطباء قريبون — <span>3 متاحون للطوارئ</span></div>
</div>

<!-- FLOATING BUTTONS -->
<div class="map-fabs">
  <div class="fab" onclick="locateMe()" title="موقعي">📍</div>
  <div class="fab" onclick="toggleTheme()" title="الوضع">🌙</div>
  <div class="fab" onclick="window.location.href='../index.php'" title="رجوع">🏠</div>
</div>

<!-- BOTTOM PANEL -->
<div class="bottom-panel" id="bottom-panel">
  <div class="panel-handle"></div>
  <div class="panel-header">
    <div class="panel-title">أطباء بيطريون قريبون</div>
    <div class="panel-count">4 أطباء</div>
  </div>
  <div class="nearby-scroll" id="nearby-scroll"></div>
</div>

<!-- EMERGENCY OVERLAY -->
<div class="emg-overlay" id="emg-overlay">
  <div class="emg-sheet">
    <div class="emg-sheet-header">
      <span style="font-size:24px;">🚨</span>
      <div class="emg-sheet-title">طلب طوارئ فوري</div>
      <div class="emg-close" onclick="closeEmg()">✕</div>
    </div>
    <div class="emg-body">
      <p style="font-size:13px;color:var(--text-sec);margin-bottom:14px;">
        سيتم إرسال طلبك فوراً لـ <strong id="emg-target-vet">أقرب طبيب متاح</strong>
      </p>

      <div class="loc-badge" onclick="getLocation()" id="loc-badge">
        <span class="loc-icon">📍</span>
        <span class="loc-text" id="loc-text">تحديد موقعي تلقائياً</span>
        <span class="loc-ok" id="loc-ok" style="display:none;">✓ تم</span>
      </div>

      <div class="form-group">
        <label class="form-label">نوع الحيوان</label>
        <select class="form-input" id="emg-animal">
          <option value="">اختر النوع</option>
          <option value="cat">🐱 قط</option>
          <option value="dog">🐕 كلب</option>
          <option value="cow">🐄 بقرة</option>
          <option value="sheep">🐑 خروف</option>
          <option value="horse">🐴 حصان</option>
          <option value="bird">🐦 طائر</option>
          <option value="other">🐾 أخرى</option>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">وصف المشكلة</label>
        <textarea class="form-textarea" id="emg-problem" placeholder="اكتب الأعراض بسرعة..."></textarea>
      </div>

      <button class="btn-send-emg" id="emg-send-btn" onclick="sendEmergency()">
        🚨 إرسال طلب الطوارئ
      </button>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script>
<script>
// ── THEME ──
const theme = localStorage.getItem('baitari_theme') || 'light';
document.documentElement.setAttribute('data-theme', theme);
function toggleTheme() {
  const t = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', t);
  localStorage.setItem('baitari_theme', t);
}

// ── MAP INIT ──
const DEFAULT_CENTER = [36.7538, 3.0588]; // Algiers
const map = L.map('map', {
  center: DEFAULT_CENTER,
  zoom: 13,
  zoomControl: false,
  attributionControl: false,
});

// Add tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '© OpenStreetMap',
}).addTo(map);

// Attribution (minimal)
L.control.attribution({ prefix: false, position: 'bottomleft' }).addTo(map);

// Zoom control (top-left in RTL)
L.control.zoom({ position: 'topleft' }).addTo(map);

// ── MOCK VETS ──
const NEARBY_VETS = [
  { id:1, name:'د. كريم حداد', spec:'حيوانات أليفة', emoji:'👨‍⚕️', lat:36.7490, lng:3.0430, available:true, emergency:true,  dist:1.2, fee:2000 },
  { id:2, name:'د. أمينة زروق', spec:'مواشي وأبقار',  emoji:'👩‍⚕️', lat:36.7580, lng:3.0700, available:true, emergency:false, dist:2.8, fee:1800 },
  { id:3, name:'د. سليم بوعلام', spec:'خيول ومواشي',  emoji:'🧑‍⚕️', lat:36.7420, lng:3.0550, available:false, emergency:false, dist:3.1, fee:2500 },
  { id:4, name:'د. نور الدين',   spec:'طب عام بيطري', emoji:'👨‍⚕️', lat:36.7600, lng:3.0350, available:true, emergency:true,  dist:3.4, fee:1500 },
];

let myMarker = null;
let myLat = null, myLng = null;
let selectedVetId = null;

// ── RENDER VET MARKERS ──
function createVetIcon(vet) {
  return L.divIcon({
    className: '',
    html: `<div style="
      width:44px;height:44px;
      background:${vet.emergency ? '#dc2626' : '#1a7f5a'};
      border-radius:50% 50% 50% 0;
      transform:rotate(-45deg);
      border:3px solid white;
      box-shadow:0 3px 14px rgba(0,0,0,.3);
      display:flex;align-items:center;justify-content:center;
      cursor:pointer;
    ">
      <span style="transform:rotate(45deg);font-size:20px;">${vet.emoji}</span>
    </div>`,
    iconSize: [44,54],
    iconAnchor: [22,54],
    popupAnchor: [0,-54],
  });
}

// Add markers
NEARBY_VETS.forEach(vet => {
  const marker = L.marker([vet.lat, vet.lng], { icon: createVetIcon(vet) })
    .addTo(map)
    .bindPopup(`
      <div style="font-family:'Tajawal',sans-serif;direction:rtl;min-width:180px;padding:4px;">
        <div style="font-size:15px;font-weight:800;margin-bottom:4px;">${vet.name}</div>
        <div style="font-size:12px;color:#4a7060;margin-bottom:6px;">${vet.spec}</div>
        <div style="display:flex;gap:8px;font-size:12px;flex-wrap:wrap;">
          <span style="color:${vet.available?'#16a34a':'#9ca3af'};font-weight:700;">${vet.available?'✅ متاح':'⭕ مشغول'}</span>
          <span style="color:#4a7060;">📍 ${vet.dist} كم</span>
        </div>
        <div style="margin-top:10px;display:flex;gap:6px;">
          ${vet.emergency
            ? `<button onclick="openEmgForVet(${vet.id})" style="flex:1;background:#dc2626;color:#fff;border:none;border-radius:8px;padding:7px;font-size:12px;font-weight:800;cursor:pointer;font-family:'Tajawal',sans-serif;">🚨 طوارئ</button>`
            : ''}
          <button onclick="window.location.href='../index.php'" style="flex:1;background:#1a7f5a;color:#fff;border:none;border-radius:8px;padding:7px;font-size:12px;font-weight:800;cursor:pointer;font-family:'Tajawal',sans-serif;">📅 حجز</button>
        </div>
      </div>
    `, { closeButton: false, className: 'vet-popup' });

  marker.on('click', () => {
    map.panTo([vet.lat, vet.lng]);
    highlightCard(vet.id);
  });
});

// ── RENDER BOTTOM CARDS ──
function renderCards() {
  const c = document.getElementById('nearby-scroll');
  NEARBY_VETS.forEach(vet => {
    const card = document.createElement('div');
    card.className = 'nearby-card' + (vet.emergency ? ' emergency-vet' : '');
    card.id = `vc-${vet.id}`;
    card.innerHTML = `
      ${vet.emergency ? '<div class="nc-emg-badge">🚨 طوارئ</div>' : ''}
      <div class="nc-avatar">${vet.emoji}</div>
      <div class="nc-name">${vet.name}</div>
      <div class="nc-spec">${vet.spec}</div>
      <div class="nc-meta">
        <span class="nc-dist">📍 ${vet.dist} كم</span>
        <span class="nc-avail ${vet.available?'on':'off'}">${vet.available?'متاح':'مشغول'}</span>
      </div>
      <button class="btn-call-vet ${vet.emergency?'btn-call-emg':''}"
        onclick="${vet.emergency ? `openEmgForVet(${vet.id})` : `showToast('info','حجز موعد مع ${vet.name}')`}">
        ${vet.emergency ? '🚨 طوارئ فورية' : '📅 حجز موعد'}
      </button>
    `;
    card.addEventListener('click', (e) => {
      if (e.target.tagName === 'BUTTON') return;
      map.flyTo([vet.lat, vet.lng], 15);
    });
    c.appendChild(card);
  });
}

function highlightCard(id) {
  document.querySelectorAll('.nearby-card').forEach(c => c.style.border = '');
  const card = document.getElementById(`vc-${id}`);
  if (card) {
    card.style.border = '2px solid var(--green-500)';
    card.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
  }
}

// ── LOCATE ME ──
function locateMe() {
  if (navigator.geolocation) {
    showToast('info', 'جارٍ تحديد موقعك...');
    navigator.geolocation.getCurrentPosition(pos => {
      myLat = pos.coords.latitude;
      myLng = pos.coords.longitude;
      setMyLocation(myLat, myLng);
    }, () => {
      // Fallback to Algiers
      myLat = 36.7538; myLng = 3.0588;
      setMyLocation(myLat, myLng);
      showToast('info', 'استخدام موقع الجزائر العاصمة كافتراضي');
    });
  }
}

function setMyLocation(lat, lng) {
  if (myMarker) map.removeLayer(myMarker);
  const myIcon = L.divIcon({
    className: '',
    html: `<div class="my-location-marker"></div>`,
    iconSize: [20,20], iconAnchor: [10,10],
  });
  myMarker = L.marker([lat, lng], { icon: myIcon }).addTo(map);
  map.flyTo([lat, lng], 14);
  document.getElementById('loc-text').textContent = `${lat.toFixed(4)}, ${lng.toFixed(4)}`;
  document.getElementById('loc-ok').style.display = '';
  showToast('success', 'تم تحديد موقعك ✓');
}

// ── EMERGENCY ──
function openEmgForVet(vetId) {
  selectedVetId = vetId;
  const vet = NEARBY_VETS.find(v => v.id === vetId);
  document.getElementById('emg-target-vet').textContent = vet ? vet.name : 'أقرب طبيب متاح';
  document.getElementById('emg-overlay').classList.add('open');
  document.body.style.overflow = 'hidden';
}

function openEmgGeneral() {
  selectedVetId = null;
  document.getElementById('emg-target-vet').textContent = 'أقرب طبيب متاح';
  document.getElementById('emg-overlay').classList.add('open');
  document.body.style.overflow = 'hidden';
}

function closeEmg() {
  document.getElementById('emg-overlay').classList.remove('open');
  document.body.style.overflow = '';
}

function getLocation() {
  locateMe();
}

async function sendEmergency() {
  const animal = document.getElementById('emg-animal').value;
  const problem = document.getElementById('emg-problem').value.trim();

  if (!animal) { showToast('error', 'الرجاء اختيار نوع الحيوان'); return; }
  if (!problem) { showToast('error', 'الرجاء وصف المشكلة'); return; }

  const btn = document.getElementById('emg-send-btn');
  btn.textContent = '⏳ جارٍ الإرسال...';
  btn.style.animation = 'none';
  btn.disabled = true;

  await new Promise(r => setTimeout(r, 1400));

  closeEmg();
  const vet = selectedVetId ? NEARBY_VETS.find(v => v.id === selectedVetId) : NEARBY_VETS.find(v => v.emergency && v.available);
  showToast('success', `تم الإرسال! ${vet?.name || 'طبيب'} في طريقه إليك 🚑`);

  btn.textContent = '🚨 إرسال طلب الطوارئ';
  btn.style.animation = '';
  btn.disabled = false;

  // Draw route line (mock)
  if (myLat && vet) {
    L.polyline(
      [[myLat, myLng], [vet.lat, vet.lng]],
      { color: '#dc2626', weight: 4, dashArray: '8, 8', opacity: .8 }
    ).addTo(map);
    map.fitBounds([[myLat, myLng], [vet.lat, vet.lng]], { padding: [60, 60] });
  }
}

// ── TOAST ──
function showToast(type, msg) {
  const icons = { success:'✅', error:'❌', info:'ℹ️' };
  document.getElementById('ti').textContent = icons[type];
  document.getElementById('tm').textContent = msg;
  const t = document.getElementById('toast');
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 3000);
}

// ── INIT ──
renderCards();
locateMe();

// Handle URL params
const params = new URLSearchParams(location.search);
if (params.get('action') === 'emergency') openEmgGeneral();
</script>
</body>
</html>
