<?php
// ============================================
// BAITARI — Vet Clinic Setup
// pages/vet-clinic-setup.php
// ============================================
require_once __DIR__ . '/../includes/config.php';
session_start_secure();

$user = current_user();
if (!$user || $user['role'] !== 'vet') {
    header('Location: ../login.php'); exit;
}
$uid   = (int)$user['id'];
$lang  = $user['lang_pref']  ?? 'ar';
$theme = $user['theme_pref'] ?? 'light';

// Load current profile
$stmt = db()->prepare(
    "SELECT vp.*, u.name, u.phone, u.wilaya
     FROM baitari_vet_profiles vp
     JOIN baitari_users u ON u.id = vp.vet_id
     WHERE vp.vet_id = :uid"
);
$stmt->execute([':uid' => $uid]);
$vp = $stmt->fetch();

// Handle save (AJAX handled by api/vet_clinic.php, but also support direct POST)
$saved = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clinic_name'])) {
    $stmt2 = db()->prepare(
        "UPDATE baitari_vet_profiles SET
            clinic_name    = :cn,
            clinic_address = :ca,
            clinic_lat     = :lat,
            clinic_lng     = :lng,
            specialities   = :spec,
            bio            = :bio,
            experience_years = :exp,
            fee_clinic     = :fc,
            fee_home       = :fh,
            home_visits    = :hv,
            teleconsult    = :tc
         WHERE vet_id = :uid"
    );
    $stmt2->execute([
        ':cn'  => sanitize_str($_POST['clinic_name']    ?? ''),
        ':ca'  => sanitize_str($_POST['clinic_address'] ?? '', 500),
        ':lat' => (float)($_POST['clinic_lat'] ?? 0) ?: null,
        ':lng' => (float)($_POST['clinic_lng'] ?? 0) ?: null,
        ':spec'=> json_encode(array_filter(explode(',', sanitize_str($_POST['specialities'] ?? '')))),
        ':bio' => sanitize_str($_POST['bio'] ?? '', 1000),
        ':exp' => (int)($_POST['experience_years'] ?? 0),
        ':fc'  => (float)($_POST['fee_clinic'] ?? 0),
        ':fh'  => (float)($_POST['fee_home']   ?? 0),
        ':hv'  => isset($_POST['home_visits']) ? 1 : 0,
        ':tc'  => isset($_POST['teleconsult'])  ? 1 : 0,
        ':uid' => $uid,
    ]);
    $saved = true;
    // Refresh
    $stmt->execute([':uid' => $uid]);
    $vp = $stmt->fetch();
}

$specialities = json_decode($vp['specialities'] ?? '[]', true) ?: [];
?>
<!DOCTYPE html>
<html lang="<?= h($lang) ?>" dir="rtl" data-theme="<?= h($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="#1a7f5a">
<title>بيطري — إعداد العيادة</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;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-50:#f0faf5;--green-100:#d6f2e5;--green-200:#aae3cb;
  --green-400:#4aba8a;--green-500:#1a9f6a;--green-600:#1a7f5a;--green-700:#155f44;
  --blue-50:#eff6ff;--blue-400:#60a5fa;--blue-500:#3b82f6;--blue-600:#2563eb;
  --amber-400:#fbbf24;--amber-500:#f59e0b;
  --red-500:#ef4444;--red-600:#dc2626;
  --bg:#f7faf9;--bg-card:#fff;--bg-input:#f3f7f5;
  --border:#e0ece7;--text-primary:#0e2d20;--text-sec:#4a7060;--text-muted:#8aaa9a;
  --shadow-sm:0 1px 4px rgba(0,60,30,.06);--shadow-md:0 4px 20px rgba(0,60,30,.10);
  --shadow-lg:0 8px 40px rgba(0,60,30,.15);
  --radius-sm:10px;--radius-md:16px;--radius-lg:24px;
  --transition:.22s cubic-bezier(.4,0,.2,1);
  --nav-h:64px;
}
[data-theme="dark"]{
  --bg:#0a1a12;--bg-card:#122010;--bg-input:#1a2e1e;
  --border:#1e3828;--text-primary:#e0f2e9;--text-sec:#8abfa0;--text-muted:#4a7060;
  --green-50:#0d1f14;--blue-50:#0a1220;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Tajawal',sans-serif;background:var(--bg);color:var(--text-primary);min-height:100dvh;-webkit-font-smoothing:antialiased;}
button{cursor:pointer;border:none;background:none;font-family:inherit;}
input,select,textarea{font-family:inherit;outline:none;}

/* TOP BAR */
.top-bar{
  background:var(--bg-card);border-bottom:1px solid var(--border);
  height:var(--nav-h);display:flex;align-items:center;
  padding:0 16px;gap:12px;position:sticky;top:0;z-index:100;
  box-shadow:var(--shadow-sm);
}
.tb-back{
  width:38px;height:38px;border-radius:10px;background:var(--bg-input);
  display:flex;align-items:center;justify-content:center;font-size:18px;cursor:pointer;
  flex-shrink:0;transition:var(--transition);border:1px solid var(--border);
}
.tb-back:hover{background:var(--green-50);color:var(--green-700);}
.tb-title{font-size:17px;font-weight:800;flex:1;}
.tb-save-btn{
  background:linear-gradient(135deg,var(--green-700),var(--green-500));
  color:#fff;border-radius:10px;padding:8px 18px;
  font-size:14px;font-weight:800;transition:var(--transition);
  box-shadow:0 3px 10px rgba(26,127,90,.25);
}
.tb-save-btn:hover{opacity:.9;}

/* PAGE */
.page-wrap{max-width:640px;margin:0 auto;padding:0 0 80px;}

/* SECTIONS */
.form-section{
  background:var(--bg-card);border-radius:var(--radius-lg);
  border:1px solid var(--border);
  margin:16px;overflow:hidden;
  box-shadow:var(--shadow-sm);
}
.fs-header{
  padding:16px 20px;border-bottom:1px solid var(--border);
  display:flex;align-items:center;gap:12px;
}
.fs-icon{
  width:40px;height:40px;border-radius:12px;
  display:flex;align-items:center;justify-content:center;
  font-size:20px;flex-shrink:0;
}
.fs-title{font-size:16px;font-weight:800;color:var(--text-primary);}
.fs-sub{font-size:12px;color:var(--text-muted);margin-top:2px;}
.fs-body{padding:16px 20px;}

/* FORM ELEMENTS */
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px;}
@media(max-width:480px){.form-row{grid-template-columns:1fr;}}
.form-group{margin-bottom:14px;}
.form-label{
  font-size:13px;font-weight:700;color:var(--text-sec);
  margin-bottom:6px;display:flex;align-items:center;gap:6px;
}
.form-label .req{color:var(--red-500);font-size:11px;}
.form-input,.form-select,.form-textarea{
  width:100%;background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);padding:11px 14px;
  font-size:14px;color:var(--text-primary);
  transition:var(--transition);
}
.form-input:focus,.form-select:focus,.form-textarea:focus{
  border-color:var(--green-500);background:var(--bg-card);
  box-shadow:0 0 0 3px rgba(26,159,106,.1);
}
.form-textarea{resize:none;min-height:90px;}
.form-select{cursor:pointer;appearance:none;}
.input-prefix{
  display:flex;align-items:center;
  background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);overflow:hidden;
  transition:var(--transition);
}
.input-prefix:focus-within{border-color:var(--green-500);background:var(--bg-card);}
.input-prefix .prefix{
  padding:11px 12px;background:var(--border);
  font-size:13px;font-weight:700;color:var(--text-sec);white-space:nowrap;
  border-left:1.5px solid var(--border);
}
[dir="ltr"] .input-prefix .prefix{border-left:none;border-right:1.5px solid var(--border);}
.input-prefix input{flex:1;background:none;border:none;padding:11px 12px;font-size:14px;color:var(--text-primary);}

/* CHARACTER COUNTER */
.char-count{font-size:11px;color:var(--text-muted);text-align:left;margin-top:4px;}

/* TOGGLE ROW */
.toggle-row{
  display:flex;align-items:center;justify-content:space-between;
  padding:12px 0;border-bottom:1px solid var(--border);
}
.toggle-row:last-child{border:none;padding-bottom:0;}
.tr-text{flex:1;}
.tr-label{font-size:14px;font-weight:700;}
.tr-sub{font-size:12px;color:var(--text-muted);margin-top:2px;}
.toggle-sw{
  width:46px;height:26px;border-radius:13px;
  background:var(--border);position:relative;cursor:pointer;
  transition:var(--transition);flex-shrink:0;
}
.toggle-sw.on{background:var(--green-500);}
.toggle-sw::after{
  content:'';position:absolute;top:3px;right:3px;
  width:20px;height:20px;background:#fff;border-radius:50%;
  transition:var(--transition);box-shadow:0 1px 4px rgba(0,0,0,.2);
}
[dir="ltr"] .toggle-sw::after{right:auto;left:3px;}
.toggle-sw.on::after{right:23px;}
[dir="ltr"] .toggle-sw.on::after{right:auto;left:23px;}

/* SPECIALITY CHIPS */
.chips-wrap{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px;}
.spec-chip{
  padding:7px 14px;border-radius:20px;
  border:1.5px solid var(--border);background:var(--bg-input);
  font-size:13px;font-weight:700;color:var(--text-sec);
  cursor:pointer;transition:var(--transition);
}
.spec-chip.selected{background:var(--green-600);border-color:var(--green-600);color:#fff;}
.spec-chip:hover:not(.selected){border-color:var(--green-400);color:var(--green-700);}

/* ── MAP SECTION ── */
.map-wrap{
  position:relative;border-radius:var(--radius-md);overflow:hidden;
  border:1.5px solid var(--border);
}
#clinic-map{
  height:260px;width:100%;
  transition:filter .3s;
}
[data-theme="dark"] #clinic-map{
  filter:invert(1) hue-rotate(180deg) brightness(.7) contrast(1.1);
}
[data-theme="dark"] #clinic-map img{filter:invert(1) hue-rotate(180deg);}

.map-overlay-hint{
  position:absolute;top:10px;left:50%;transform:translateX(-50%);
  background:rgba(0,0,0,.65);color:#fff;
  border-radius:20px;padding:7px 16px;
  font-size:12px;font-weight:700;
  pointer-events:none;backdrop-filter:blur(4px);
  white-space:nowrap;z-index:10;
  transition:opacity .3s;
}
.map-overlay-hint.hidden{opacity:0;}

.map-actions{
  display:flex;gap:8px;margin-top:10px;
}
.btn-locate{
  flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
  background:var(--green-600);color:#fff;border-radius:var(--radius-sm);
  padding:11px;font-size:14px;font-weight:800;transition:var(--transition);
}
.btn-locate:hover{opacity:.9;}
.btn-locate.locating{opacity:.7;pointer-events:none;}
.btn-search-addr{
  flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
  background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);padding:11px;
  font-size:14px;font-weight:800;color:var(--text-sec);
  transition:var(--transition);
}
.btn-search-addr:hover{border-color:var(--green-400);color:var(--green-700);}

/* Coords display */
.coords-row{
  display:flex;align-items:center;gap:8px;margin-top:8px;
  background:var(--bg-input);border-radius:var(--radius-sm);
  padding:10px 12px;
}
.coord-item{flex:1;text-align:center;}
.coord-label{font-size:10px;color:var(--text-muted);font-weight:700;margin-bottom:2px;}
.coord-val{font-size:13px;font-weight:800;color:var(--green-700);font-variant-numeric:tabular-nums;}
.coord-status{
  display:flex;align-items:center;gap:4px;
  font-size:11px;font-weight:700;
}
.coord-status.set{color:var(--green-600);}
.coord-status.unset{color:var(--text-muted);}

/* Address search dropdown */
.addr-search-wrap{position:relative;margin-bottom:10px;}
.addr-results{
  position:absolute;top:100%;left:0;right:0;z-index:200;
  background:var(--bg-card);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);box-shadow:var(--shadow-lg);
  max-height:200px;overflow-y:auto;display:none;
}
.addr-results.show{display:block;}
.addr-result-item{
  padding:12px 14px;cursor:pointer;transition:var(--transition);
  border-bottom:1px solid var(--border);font-size:13px;
}
.addr-result-item:last-child{border:none;}
.addr-result-item:hover{background:var(--green-50);color:var(--green-700);}
.addr-result-name{font-weight:700;}
.addr-result-sub{font-size:11px;color:var(--text-muted);margin-top:2px;}

/* SAVED BANNER */
.saved-banner{
  margin:0 16px 0;
  background:var(--green-50);border:1px solid var(--green-200);
  border-radius:var(--radius-sm);padding:12px 16px;
  display:flex;align-items:center;gap:10px;
  font-size:14px;font-weight:700;color:var(--green-700);
  animation:fadeIn .4s ease both;
}
@keyframes fadeIn{from{opacity:0;transform:translateY(-8px);}to{opacity:1;transform:translateY(0);}}

/* PREVIEW CARD */
.preview-card{
  margin:0 16px;
  background:var(--bg-card);border:1px solid var(--border);
  border-radius:var(--radius-lg);padding:16px;
  box-shadow:var(--shadow-sm);
}
.preview-card-title{font-size:14px;font-weight:700;color:var(--text-muted);margin-bottom:12px;}
.pc-row{display:flex;align-items:flex-start;gap:12px;margin-bottom:10px;}
.pc-row:last-child{margin-bottom:0;}
.pc-icon{font-size:18px;flex-shrink:0;margin-top:1px;}
.pc-text{font-size:13px;font-weight:700;color:var(--text-primary);}
.pc-sub{font-size:11px;color:var(--text-muted);margin-top:2px;}

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

/* BOTTOM SAVE BAR */
.bottom-save-bar{
  position:fixed;bottom:0;left:50%;transform:translateX(-50%);
  width:100%;max-width:640px;
  background:var(--bg-card);border-top:1px solid var(--border);
  padding:12px 16px;padding-bottom:max(12px,env(safe-area-inset-bottom));
  z-index:100;box-shadow:0 -4px 20px rgba(0,0,0,.08);
  display:flex;gap:10px;
}
.btn-save-main{
  flex:1;background:linear-gradient(135deg,var(--green-700),var(--green-500));
  color:#fff;border-radius:var(--radius-sm);padding:14px;
  font-size:16px;font-weight:800;text-align:center;
  box-shadow:0 4px 16px rgba(26,127,90,.3);transition:var(--transition);
}
.btn-save-main:hover{opacity:.9;transform:translateY(-1px);}
.btn-save-main:disabled{opacity:.5;pointer-events:none;}
.btn-preview{
  width:50px;background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;
  font-size:20px;transition:var(--transition);
}
.btn-preview:hover{background:var(--green-50);border-color:var(--green-400);}
</style>
</head>
<body>

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

<!-- TOP BAR -->
<div class="top-bar">
  <div class="tb-back" onclick="history.back()">←</div>
  <div class="tb-title">🏥 إعداد العيادة</div>
</div>

<div class="page-wrap">

  <?php if ($saved): ?>
  <div class="saved-banner" style="margin-top:16px;">
    ✅ تم حفظ معلومات العيادة بنجاح
  </div>
  <?php endif; ?>

  <!-- ── 1. BASIC INFO ── -->
  <div class="form-section" style="margin-top:16px;">
    <div class="fs-header">
      <div class="fs-icon" style="background:var(--green-50);">🏥</div>
      <div>
        <div class="fs-title">معلومات العيادة الأساسية</div>
        <div class="fs-sub">تظهر في ملفك الشخصي</div>
      </div>
    </div>
    <div class="fs-body">
      <div class="form-row">
        <div class="form-group">
          <label class="form-label">اسم العيادة <span class="req">*</span></label>
          <input type="text" class="form-input" id="clinic-name"
            value="<?= h($vp['clinic_name'] ?? '') ?>"
            placeholder="عيادة الشفاء البيطرية">
        </div>
        <div class="form-group">
          <label class="form-label">سنوات الخبرة</label>
          <input type="number" class="form-input" id="exp-years"
            value="<?= (int)($vp['experience_years'] ?? 0) ?>"
            min="0" max="60" placeholder="10">
        </div>
      </div>
      <div class="form-group">
        <label class="form-label">نبذة مهنية <span style="color:var(--text-muted);font-weight:500;">(تظهر للمستخدمين)</span></label>
        <textarea class="form-textarea" id="bio-text" maxlength="500"
          oninput="document.getElementById('bio-count').textContent=this.value.length+'/500'"
          placeholder="اكتب نبذة عن خبرتك وتخصصاتك..."><?= h($vp['bio'] ?? '') ?></textarea>
        <div class="char-count" id="bio-count"><?= strlen($vp['bio'] ?? '') ?>/500</div>
      </div>
    </div>
  </div>

  <!-- ── 2. SPECIALITIES ── -->
  <div class="form-section">
    <div class="fs-header">
      <div class="fs-icon" style="background:var(--blue-50);">🩺</div>
      <div>
        <div class="fs-title">التخصصات</div>
        <div class="fs-sub">اختر كل ما ينطبق عليك</div>
      </div>
    </div>
    <div class="fs-body">
      <div class="chips-wrap" id="spec-chips"></div>
    </div>
  </div>

  <!-- ── 3. FEES & VISITS ── -->
  <div class="form-section">
    <div class="fs-header">
      <div class="fs-icon" style="background:var(--amber-400);opacity:.9;">💰</div>
      <div>
        <div class="fs-title">الأسعار والخدمات</div>
      </div>
    </div>
    <div class="fs-body">
      <div class="form-row">
        <div class="form-group">
          <label class="form-label">رسوم الكشف بالعيادة</label>
          <div class="input-prefix">
            <span class="prefix">دج</span>
            <input type="number" id="fee-clinic"
              value="<?= (int)($vp['fee_clinic'] ?? 0) ?>"
              min="0" placeholder="2000">
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">رسوم الزيارة المنزلية</label>
          <div class="input-prefix">
            <span class="prefix">دج</span>
            <input type="number" id="fee-home"
              value="<?= (int)($vp['fee_home'] ?? 0) ?>"
              min="0" placeholder="3500">
          </div>
        </div>
      </div>
      <div class="toggle-row">
        <div class="tr-text">
          <div class="tr-label">🏠 زيارات منزلية</div>
          <div class="tr-sub">أقبل طلبات الزيارة للمنزل</div>
        </div>
        <div class="toggle-sw <?= $vp['home_visits'] ? 'on' : '' ?>"
          id="toggle-home" onclick="this.classList.toggle('on')"></div>
      </div>
      <div class="toggle-row">
        <div class="tr-text">
          <div class="tr-label">🚨 قبول طلبات الطوارئ</div>
          <div class="tr-sub">أظهر في قائمة أطباء الطوارئ</div>
        </div>
        <div class="toggle-sw <?= $vp['accepts_emergency'] ? 'on' : '' ?>"
          id="toggle-emg" onclick="this.classList.toggle('on')"></div>
      </div>
      <div class="toggle-row">
        <div class="tr-text">
          <div class="tr-label">💻 استشارة عن بُعد</div>
          <div class="tr-sub">أقبل الاستشارات الإلكترونية</div>
        </div>
        <div class="toggle-sw <?= $vp['teleconsult'] ? 'on' : '' ?>"
          id="toggle-tele" onclick="this.classList.toggle('on')"></div>
      </div>
    </div>
  </div>

  <!-- ── 4. LOCATION ── -->
  <div class="form-section">
    <div class="fs-header">
      <div class="fs-icon" style="background:var(--red-50);">📍</div>
      <div>
        <div class="fs-title">موقع العيادة على الخريطة</div>
        <div class="fs-sub">يظهر للمستخدمين لمعرفة المسافة واتجاهات الوصول</div>
      </div>
    </div>
    <div class="fs-body">

      <!-- Address search -->
      <div class="form-group">
        <label class="form-label">عنوان العيادة <span class="req">*</span></label>
        <div class="addr-search-wrap">
          <input type="text" class="form-input" id="addr-input"
            value="<?= h($vp['clinic_address'] ?? '') ?>"
            placeholder="مثال: حيدرة، الجزائر العاصمة"
            oninput="searchAddress(this.value)"
            autocomplete="off">
          <div class="addr-results" id="addr-results"></div>
        </div>
      </div>

      <!-- Map -->
      <div class="map-wrap">
        <div id="clinic-map"></div>
        <div class="map-overlay-hint" id="map-hint">📍 انقر على الخريطة لتحديد موقع العيادة</div>
      </div>

      <!-- Map actions -->
      <div class="map-actions" style="margin-top:10px;">
        <button class="btn-locate" id="locate-btn" onclick="locateMe()">
          📡 تحديد موقعي تلقائياً
        </button>
        <button class="btn-search-addr" onclick="document.getElementById('addr-input').focus()">
          🔍 بحث بالعنوان
        </button>
      </div>

      <!-- Coords display -->
      <div class="coords-row">
        <div class="coord-item">
          <div class="coord-label">خط العرض</div>
          <div class="coord-val" id="lat-display"><?= $vp['clinic_lat'] ? number_format((float)$vp['clinic_lat'],6) : '—' ?></div>
        </div>
        <div style="width:1px;background:var(--border);"></div>
        <div class="coord-item">
          <div class="coord-label">خط الطول</div>
          <div class="coord-val" id="lng-display"><?= $vp['clinic_lng'] ? number_format((float)$vp['clinic_lng'],6) : '—' ?></div>
        </div>
        <div style="width:1px;background:var(--border);"></div>
        <div class="coord-item">
          <div class="coord-label">الحالة</div>
          <div class="coord-status <?= $vp['clinic_lat'] ? 'set' : 'unset' ?>" id="coord-status">
            <?= $vp['clinic_lat'] ? '✅ محدد' : '⭕ غير محدد' ?>
          </div>
        </div>
      </div>

      <!-- Hidden inputs -->
      <input type="hidden" id="lat-val" value="<?= h($vp['clinic_lat'] ?? '') ?>">
      <input type="hidden" id="lng-val" value="<?= h($vp['clinic_lng'] ?? '') ?>">

    </div>
  </div>

  <!-- ── 5. PREVIEW ── -->
  <div class="preview-card">
    <div class="preview-card-title">👁 معاينة ما يراه المستخدم</div>
    <div class="pc-row">
      <span class="pc-icon">🏥</span>
      <div>
        <div class="pc-text" id="prev-clinic-name"><?= h($vp['clinic_name'] ?? 'اسم العيادة') ?></div>
        <div class="pc-sub">اسم العيادة</div>
      </div>
    </div>
    <div class="pc-row">
      <span class="pc-icon">📍</span>
      <div>
        <div class="pc-text" id="prev-address"><?= h($vp['clinic_address'] ?? 'العنوان لم يُحدد بعد') ?></div>
        <div class="pc-sub">العنوان المعروض</div>
      </div>
    </div>
    <div class="pc-row">
      <span class="pc-icon">💰</span>
      <div>
        <div class="pc-text" id="prev-fees">
          عيادة: <?= number_format((int)($vp['fee_clinic']??0)) ?> دج
          <?= $vp['home_visits'] ? '· منزلي: '.number_format((int)($vp['fee_home']??0)).' دج' : '' ?>
        </div>
        <div class="pc-sub">الأسعار</div>
      </div>
    </div>
    <div class="pc-row">
      <span class="pc-icon">🗺️</span>
      <div>
        <div class="pc-text" id="prev-map-status">
          <?= $vp['clinic_lat'] ? '✅ موقع العيادة محدد على الخريطة' : '⭕ الموقع لم يُحدد بعد' ?>
        </div>
        <div class="pc-sub">حالة الخريطة</div>
      </div>
    </div>
  </div>

</div><!-- /page-wrap -->

<!-- BOTTOM SAVE BAR -->
<div class="bottom-save-bar">
  <button class="btn-preview" onclick="showToast('info','المعاينة محدّثة أعلاه')" title="معاينة">👁</button>
  <button class="btn-save-main" id="save-btn" onclick="saveClinic()">
    💾 حفظ معلومات العيادة
  </button>
</div>

<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script>
<script>
// ── STATE ──
let clinicLat = <?= $vp['clinic_lat'] ? (float)$vp['clinic_lat'] : 'null' ?>;
let clinicLng = <?= $vp['clinic_lng'] ? (float)$vp['clinic_lng'] : 'null' ?>;
const DEFAULT_CENTER = [36.7538, 3.0588]; // Algiers

// ── SPECIALITIES ──
const ALL_SPECS = [
  {id:'pets',      label:'حيوانات أليفة 🐾'},
  {id:'cattle',    label:'أبقار ومواشي 🐄'},
  {id:'horses',    label:'خيول 🐴'},
  {id:'sheep',     label:'أغنام وماعز 🐑'},
  {id:'poultry',   label:'دواجن 🐔'},
  {id:'surgery',   label:'جراحة 🔪'},
  {id:'dentistry', label:'طب الأسنان 🦷'},
  {id:'nutrition', label:'تغذية 🥗'},
  {id:'emergency', label:'طوارئ 🚨'},
  {id:'lab',       label:'مختبر تشخيصي 🔬'},
];
const SAVED_SPECS = <?= json_encode($specialities) ?>;

function initSpecChips() {
  const wrap = document.getElementById('spec-chips');
  ALL_SPECS.forEach(s => {
    const chip = document.createElement('div');
    chip.className = 'spec-chip' + (SAVED_SPECS.includes(s.id) ? ' selected' : '');
    chip.textContent = s.label;
    chip.dataset.id = s.id;
    chip.onclick = () => chip.classList.toggle('selected');
    wrap.appendChild(chip);
  });
}

function getSelectedSpecs() {
  return [...document.querySelectorAll('.spec-chip.selected')].map(c => c.dataset.id);
}

// ── MAP ──
const map = L.map('clinic-map', {
  center: clinicLat ? [clinicLat, clinicLng] : DEFAULT_CENTER,
  zoom: clinicLat ? 15 : 12,
  zoomControl: true,
  attributionControl: false,
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom:19 }).addTo(map);

// Custom marker icon
const VET_ICON = L.divIcon({
  className:'',
  html:`<div style="
    width:42px;height:42px;
    background:linear-gradient(135deg,#155f44,#1a9f6a);
    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;">
    <span style="transform:rotate(45deg);font-size:20px;">🏥</span>
  </div>`,
  iconSize:[42,52], iconAnchor:[21,52], popupAnchor:[0,-52],
});

let marker = null;

function setMarker(lat, lng, address) {
  clinicLat = lat; clinicLng = lng;
  document.getElementById('lat-val').value = lat;
  document.getElementById('lng-val').value = lng;
  document.getElementById('lat-display').textContent = lat.toFixed(6);
  document.getElementById('lng-display').textContent = lng.toFixed(6);
  document.getElementById('coord-status').textContent = '✅ محدد';
  document.getElementById('coord-status').className = 'coord-status set';
  document.getElementById('prev-map-status').textContent = '✅ موقع العيادة محدد على الخريطة';
  document.getElementById('map-hint').classList.add('hidden');

  if (marker) map.removeLayer(marker);
  marker = L.marker([lat, lng], {icon: VET_ICON, draggable: true}).addTo(map);

  if (address) {
    marker.bindPopup(`<div style="font-family:'Tajawal',sans-serif;direction:rtl;font-weight:700;font-size:13px;">📍 ${address}</div>`)
          .openPopup();
    document.getElementById('addr-input').value = address;
    document.getElementById('prev-address').textContent = address;
  }

  // Drag to update coords
  marker.on('dragend', e => {
    const pos = e.target.getLatLng();
    setMarker(pos.lat, pos.lng, document.getElementById('addr-input').value);
    reverseGeocode(pos.lat, pos.lng);
  });
}

// Click on map = set marker
map.on('click', e => setMarker(e.latlng.lat, e.latlng.lng, document.getElementById('addr-input').value));

// Init existing marker
if (clinicLat) setMarker(clinicLat, clinicLng, <?= json_encode($vp['clinic_address'] ?? '') ?>);

// ── LOCATE ME ──
function locateMe() {
  const btn = document.getElementById('locate-btn');
  btn.classList.add('locating');
  btn.textContent = '⏳ جارٍ التحديد...';

  if (!navigator.geolocation) {
    showToast('error', 'المتصفح لا يدعم تحديد الموقع');
    btn.classList.remove('locating');
    btn.textContent = '📡 تحديد موقعي تلقائياً';
    return;
  }
  navigator.geolocation.getCurrentPosition(pos => {
    const {latitude: lat, longitude: lng} = pos.coords;
    map.flyTo([lat, lng], 16);
    setMarker(lat, lng, '');
    reverseGeocode(lat, lng);
    btn.classList.remove('locating');
    btn.textContent = '📡 تحديد موقعي تلقائياً';
    showToast('success', 'تم تحديد موقعك ✅');
  }, () => {
    showToast('error', 'تعذّر تحديد الموقع — حرّك المؤشر على الخريطة');
    btn.classList.remove('locating');
    btn.textContent = '📡 تحديد موقعي تلقائياً';
  }, {timeout:8000, enableHighAccuracy:true});
}

// ── REVERSE GEOCODE ──
async function reverseGeocode(lat, lng) {
  try {
    const res = await fetch(
      `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&accept-language=ar`,
      {headers:{'Accept-Language':'ar'}}
    );
    const data = await res.json();
    const addr = data.display_name || '';
    if (addr) {
      document.getElementById('addr-input').value = addr;
      document.getElementById('prev-address').textContent = addr;
      marker?.bindPopup(`<div style="font-family:'Tajawal',sans-serif;direction:rtl;font-weight:700;font-size:13px;">📍 ${addr.slice(0,80)}...</div>`).openPopup();
    }
  } catch(e) {}
}

// ── ADDRESS SEARCH (Nominatim) ──
let addrTimer;
async function searchAddress(q) {
  clearTimeout(addrTimer);
  document.getElementById('prev-address').textContent = q || '—';
  if (q.length < 4) { document.getElementById('addr-results').classList.remove('show'); return; }

  addrTimer = setTimeout(async () => {
    try {
      const res = await fetch(
        `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q+' الجزائر')}&format=json&limit=5&accept-language=ar`,
        {headers:{'Accept-Language':'ar'}}
      );
      const results = await res.json();
      const box = document.getElementById('addr-results');
      box.innerHTML = '';
      if (!results.length) { box.classList.remove('show'); return; }

      results.forEach(r => {
        const item = document.createElement('div');
        item.className = 'addr-result-item';
        const short = r.display_name.split(',').slice(0,3).join('،');
        item.innerHTML = `
          <div class="addr-result-name">📍 ${escHtml(short)}</div>
          <div class="addr-result-sub">${escHtml(r.display_name.slice(0,100))}...</div>`;
        item.onclick = () => {
          map.flyTo([parseFloat(r.lat), parseFloat(r.lon)], 16);
          setMarker(parseFloat(r.lat), parseFloat(r.lon), r.display_name.split(',').slice(0,3).join('،'));
          box.classList.remove('show');
        };
        box.appendChild(item);
      });
      box.classList.add('show');
    } catch(e) {}
  }, 600);
}

// Close address dropdown on outside click
document.addEventListener('click', e => {
  if (!e.target.closest('.addr-search-wrap'))
    document.getElementById('addr-results').classList.remove('show');
});

// Live preview updates
document.getElementById('clinic-name').addEventListener('input', e => {
  document.getElementById('prev-clinic-name').textContent = e.target.value || 'اسم العيادة';
});

// ── SAVE ──
async function saveClinic() {
  const clinicName = document.getElementById('clinic-name').value.trim();
  const address    = document.getElementById('addr-input').value.trim();

  if (!clinicName) { showToast('error', 'الرجاء إدخال اسم العيادة'); return; }
  if (!clinicLat)  { showToast('error', 'الرجاء تحديد موقع العيادة على الخريطة'); return; }

  const btn = document.getElementById('save-btn');
  btn.disabled = true;
  btn.textContent = '⏳ جارٍ الحفظ...';

  const payload = {
    action:          'save_clinic',
    clinic_name:     clinicName,
    clinic_address:  address,
    clinic_lat:      clinicLat,
    clinic_lng:      clinicLng,
    bio:             document.getElementById('bio-text').value,
    experience_years:document.getElementById('exp-years').value,
    fee_clinic:      document.getElementById('fee-clinic').value,
    fee_home:        document.getElementById('fee-home').value,
    home_visits:     document.getElementById('toggle-home').classList.contains('on') ? 1 : 0,
    accepts_emergency: document.getElementById('toggle-emg').classList.contains('on') ? 1 : 0,
    teleconsult:     document.getElementById('toggle-tele').classList.contains('on') ? 1 : 0,
    specialities:    getSelectedSpecs().join(','),
  };

  try {
    const res = await fetch('../api/vet_clinic.php', {
      method: 'POST',
      headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams(payload),
    });
    const data = await res.json();
    if (data.success) {
      showToast('success', '✅ تم حفظ معلومات العيادة بنجاح!');
      // Update preview fees
      const fc = parseInt(payload.fee_clinic)||0;
      const fh = parseInt(payload.fee_home)||0;
      document.getElementById('prev-fees').textContent =
        `عيادة: ${fc.toLocaleString()} دج${payload.home_visits=='1' ? ' · منزلي: '+fh.toLocaleString()+' دج' : ''}`;
    } else {
      showToast('error', data.error || 'فشل الحفظ');
    }
  } catch(e) {
    // Fallback: direct form POST if no API
    showToast('info', 'جارٍ الحفظ...');
    const form = document.createElement('form');
    form.method = 'POST'; form.action = 'vet-clinic-setup.php';
    Object.entries(payload).forEach(([k,v]) => {
      const i = document.createElement('input');
      i.type='hidden'; i.name=k; i.value=v; form.appendChild(i);
    });
    document.body.appendChild(form); form.submit();
  }

  btn.disabled = false;
  btn.textContent = '💾 حفظ معلومات العيادة';
}

function escHtml(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

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'), 3500);
}

// Theme
document.documentElement.setAttribute('data-theme', localStorage.getItem('baitari_theme')||'light');

// Init
initSpecChips();
</script>
</body>
</html>
