<?php
require_once __DIR__ . '/../includes/config.php';
session_start_secure();
$user = current_user();
if (!$user || !in_array($user['role'], ['client','farm_owner'])) { header('Location: ../login.php'); exit; }
$uid   = (int)$user['id'];
$lang  = $user['lang_pref']  ?? 'ar';
$theme = $user['theme_pref'] ?? 'light';

// Load herds
$herds = db()->prepare("SELECT * FROM baitari_herds WHERE farm_id=:uid ORDER BY species");
$herds->execute([':uid'=>$uid]);
$herdList = $herds->fetchAll();

// Stats
$totalAnimals  = array_sum(array_column($herdList,'count'));
$criticalHerds = count(array_filter($herdList, fn($h) => $h['health_status']==='critical'));
$needsAttn     = count(array_filter($herdList, fn($h) => $h['health_status']==='needs_attention'));
$healthyHerds  = count(array_filter($herdList, fn($h) => $h['health_status']==='healthy'));

// Recent appointments for farm
$farmAppts = db()->prepare(
    "SELECT a.*, u.name as vet_name, u.phone as vet_phone
     FROM baitari_appointments a
     JOIN baitari_users u ON u.id=a.vet_id
     WHERE a.client_id=:uid
     ORDER BY a.scheduled_at DESC LIMIT 5"
);
$farmAppts->execute([':uid'=>$uid]);
$recentAppts = $farmAppts->fetchAll();

$speciesIcons = ['cattle'=>'🐄','sheep'=>'🐑','goats'=>'🐐','horses'=>'🐴','poultry'=>'🐔','camels'=>'🐪','other'=>'🐾'];
$speciesLabel = ['cattle'=>'أبقار','sheep'=>'أغنام','goats'=>'ماعز','horses'=>'خيول','poultry'=>'دواجن','camels'=>'إبل','other'=>'أخرى'];
?>
<!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,maximum-scale=1,user-scalable=no">
<meta name="theme-color" content="#1a7f5a">
<title>VetNet — إدارة القطيع</title>
<link rel="stylesheet" href="../assets/css/baitari.css">
<style>
:root{--g5:#1a9f6a;--g6:#1a7f5a;--g7:#155f44;--g4:#4aba8a;--b5:#3b82f6;--r5:#ef4444;--r6:#dc2626;--a4:#fbbf24;--a5:#f59e0b;--bg:#f0f4f2;--cd:#fff;--inp:#f3f7f5;--br:#e0ece7;--tp:#0e2d20;--ts:#4a7060;--tm:#8aaa9a;--sh:0 2px 12px rgba(0,60,30,.08);--sh2:0 4px 24px rgba(0,60,30,.12);--r:10px;--r2:16px;--nav:64px;--tr:.2s cubic-bezier(.4,0,.2,1);}
[data-theme=dark]{--bg:#0a1a12;--cd:#0f1e12;--inp:#142018;--br:#1a2e1e;--tp:#e0f2e9;--ts:#8abfa0;--tm:#3a5a44;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Tajawal',sans-serif;background:var(--bg);color:var(--tp);min-height:100dvh;-webkit-font-smoothing:antialiased;}
button{cursor:pointer;border:none;font-family:'Tajawal',sans-serif;}

/* NAV */
.topnav{background:var(--cd);border-bottom:1px solid var(--br);height:var(--nav);display:flex;align-items:center;padding:0 16px;gap:12px;position:sticky;top:0;z-index:100;box-shadow:var(--sh);}
.nav-mark{width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,#92400e,var(--a5));display:flex;align-items:center;justify-content:center;font-size:18px;}
.nav-title{font-size:17px;font-weight:900;flex:1;}
.nav-btn{width:38px;height:38px;border-radius:10px;background:var(--inp);border:1px solid var(--br);display:flex;align-items:center;justify-content:center;font-size:18px;cursor:pointer;}
.nav-btn:hover{background:var(--br);}

.page-wrap{max-width:640px;margin:0 auto;padding:0 0 90px;}

/* HERO */
.farm-hero{background:linear-gradient(135deg,#92400e,var(--a5) 60%,var(--g5));padding:24px 20px;position:relative;overflow:hidden;}
.farm-hero::before{content:'';position:absolute;top:-40px;left:-40px;width:180px;height:180px;background:rgba(255,255,255,.06);border-radius:50%;}
.fh-name{font-size:22px;font-weight:900;color:#fff;position:relative;z-index:1;}
.fh-sub{font-size:14px;color:rgba(255,255,255,.8);margin-top:4px;position:relative;z-index:1;}

/* STATS */
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;padding:16px;}
@media(max-width:480px){.stats{grid-template-columns:repeat(2,1fr);}}
.stat{background:var(--cd);border-radius:var(--r2);padding:14px 10px;border:1px solid var(--br);text-align:center;box-shadow:var(--sh);}
.sn{font-size:26px;font-weight:900;line-height:1;}
.sl{font-size:11px;color:var(--ts);font-weight:600;margin-top:3px;}
.stat.total .sn{color:var(--g6);}
.stat.healthy .sn{color:#16a34a;}
.stat.warn .sn{color:var(--a5);}
.stat.crit .sn{color:var(--r6);}

/* SECTION */
.sec{margin:0 16px 20px;}
.sec-hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;}
.sec-title{font-size:16px;font-weight:800;}
.btn-add{display:flex;align-items:center;gap:6px;background:var(--g6);color:#fff;border-radius:20px;padding:7px 16px;font-size:13px;font-weight:800;box-shadow:0 3px 10px rgba(26,127,90,.25);}
.btn-add:hover{opacity:.9;}

/* HERD CARDS */
.herd-card{background:var(--cd);border-radius:var(--r2);border:1px solid var(--br);padding:16px;margin-bottom:10px;box-shadow:var(--sh);cursor:pointer;transition:var(--tr);}
.herd-card:hover{box-shadow:var(--sh2);transform:translateY(-2px);}
.herd-card.critical{border-color:#fca5a5;background:rgba(239,68,68,.03);}
.herd-card.needs_attention{border-color:#fcd34d;}
.herd-top{display:flex;align-items:center;gap:14px;}
.herd-icon{width:54px;height:54px;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:28px;flex-shrink:0;}
.herd-icon.cattle{background:#fef3c7;}
.herd-icon.sheep{background:#f0f9ff;}
.herd-icon.goats{background:#fdf4ff;}
.herd-icon.horses{background:#fff1f2;}
.herd-icon.poultry{background:#fffbeb;}
.herd-icon.camels{background:#f5f0e8;}
.herd-icon.other{background:var(--inp);}
.herd-info{flex:1;}
.herd-name{font-size:16px;font-weight:800;}
.herd-sub{font-size:12px;color:var(--ts);margin-top:3px;}
.hbadge{padding:4px 12px;border-radius:20px;font-size:12px;font-weight:800;}
.hbadge.healthy{background:#dcfce7;color:#15803d;}
.hbadge.needs_attention{background:#fef3c7;color:#92400e;}
.hbadge.critical{background:#fee2e2;color:#991b1b;}

/* PROGRESS BAR */
.health-bar{margin-top:12px;}
.hb-label{display:flex;justify-content:space-between;font-size:12px;color:var(--ts);font-weight:600;margin-bottom:5px;}
.hb-track{height:8px;background:var(--br);border-radius:4px;overflow:hidden;}
.hb-fill{height:100%;border-radius:4px;transition:width .6s ease;}

/* HERD ACTIONS */
.herd-actions{display:flex;gap:8px;margin-top:12px;padding-top:12px;border-top:1px solid var(--br);}
.ha-btn{flex:1;padding:9px;border-radius:var(--r);font-size:13px;font-weight:800;text-align:center;cursor:pointer;transition:var(--tr);}
.ha-book{background:linear-gradient(135deg,var(--g7),var(--g5));color:#fff;border:none;}
.ha-emg{background:rgba(239,68,68,.1);color:var(--r6);border:1.5px solid #fca5a5;}
.ha-edit{background:var(--inp);color:var(--ts);border:1.5px solid var(--br);}

/* ADD HERD MODAL */
.modal-ov{position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:500;display:none;align-items:flex-end;justify-content:center;backdrop-filter:blur(3px);}
.modal-ov.open{display:flex;}
.modal-sh{width:100%;max-width:640px;background:var(--cd);border-radius:28px 28px 0 0;padding:0 0 40px;max-height:92dvh;overflow-y:auto;animation:slideUp .3s ease both;}
@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}
.mh{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid var(--br);}
.mh-title{font-size:18px;font-weight:800;flex:1;}
.mc{width:34px;height:34px;background:var(--inp);border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;cursor:pointer;border:none;}
.mb{padding:20px;}
.flbl{font-size:13px;font-weight:700;color:var(--ts);margin-bottom:6px;display:block;}
.finp,.fsel{width:100%;background:var(--inp);border:1.5px solid var(--br);border-radius:var(--r);padding:11px 14px;font-size:15px;color:var(--tp);font-family:'Tajawal',sans-serif;outline:none;margin-bottom:14px;transition:var(--tr);-webkit-appearance:none;}
.finp:focus,.fsel:focus{border-color:var(--g5);background:var(--cd);box-shadow:0 0 0 3px rgba(26,159,106,.1);}

/* STATUS SELECTOR */
.status-opts{display:flex;gap:8px;margin-bottom:14px;}
.status-opt{flex:1;padding:10px;border-radius:var(--r);border:2px solid var(--br);text-align:center;cursor:pointer;font-size:13px;font-weight:700;color:var(--ts);background:var(--inp);transition:var(--tr);}
.status-opt.on.healthy{border-color:#22c55e;background:#dcfce7;color:#15803d;}
.status-opt.on.needs_attention{border-color:var(--a5);background:#fef3c7;color:#92400e;}
.status-opt.on.critical{border-color:var(--r5);background:#fee2e2;color:#991b1b;}

.btn-save{width:100%;background:linear-gradient(135deg,var(--g7),var(--g5));color:#fff;border:none;border-radius:var(--r);padding:14px;font-size:16px;font-weight:800;cursor:pointer;box-shadow:0 4px 16px rgba(26,127,90,.3);}

/* APPT CARDS */
.appt-mini{background:var(--cd);border-radius:var(--r2);border:1px solid var(--br);padding:14px;margin-bottom:8px;display:flex;align-items:center;gap:12px;box-shadow:var(--sh);}
.am-date{text-align:center;background:var(--inp);border-radius:8px;padding:6px 10px;min-width:50px;flex-shrink:0;}
.amd-d{font-size:20px;font-weight:900;color:var(--g7);line-height:1;}
.amd-m{font-size:10px;color:var(--ts);font-weight:700;}
.am-info{flex:1;}
.am-vet{font-size:14px;font-weight:800;}
.am-sub{font-size:12px;color:var(--ts);margin-top:2px;}
.sp{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:800;}
.sp-confirmed{background:#dcfce7;color:#15803d;}
.sp-pending{background:#fef3c7;color:#92400e;}
.sp-completed{background:#f0f9ff;color:#0369a1;}
.sp-cancelled{background:#fee2e2;color:#991b1b;}

/* BOTTOM NAV */
.bnav{position:fixed;bottom:0;left:0;right:0;background:var(--cd);border-top:1px solid var(--br);display:flex;justify-content:space-around;padding:8px 4px;padding-bottom:max(8px,env(safe-area-inset-bottom));z-index:200;box-shadow:0 -4px 20px rgba(0,0,0,.06);}
.bn-item{flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;cursor:pointer;color:var(--tm);padding:4px;}
.bn-item.on{color:var(--g6);}
.bn-icon{font-size:22px;}
.bn-label{font-size:10px;font-weight:700;}

.toast{position:fixed;bottom:80px;left:50%;transform:translateX(-50%);background:var(--cd);border:1px solid var(--br);border-radius:14px;padding:12px 20px;display:flex;align-items:center;gap:10px;font-size:13px;font-weight:700;box-shadow:0 8px 32px rgba(0,0,0,.15);z-index:9999;opacity:0;pointer-events:none;transition:opacity .3s;width:90%;max-width:380px;}
.toast.on{opacity:1;pointer-events:auto;}

.empty{text-align:center;padding:40px 24px;color:var(--tm);}
.empty-icon{font-size:48px;margin-bottom:12px;opacity:.6;}
</style>
</head>
<body>

<div class="toast" id="toast"><span id="ti">✅</span><span id="tm2"></span></div>

<!-- ADD/EDIT HERD MODAL -->
<div class="modal-ov" id="herd-modal">
  <div class="modal-sh">
    <div class="mh">
      <div class="mh-title" id="modal-title">➕ إضافة مجموعة</div>
      <button class="mc" onclick="closeModal()">✕</button>
    </div>
    <div class="mb">
      <input type="hidden" id="herd-id-inp">
      <label class="flbl">نوع الحيوان</label>
      <select class="fsel" id="h-species">
        <option value="cattle">🐄 أبقار</option>
        <option value="sheep">🐑 أغنام</option>
        <option value="goats">🐐 ماعز</option>
        <option value="horses">🐴 خيول</option>
        <option value="poultry">🐔 دواجن</option>
        <option value="camels">🐪 إبل</option>
        <option value="other">🐾 أخرى</option>
      </select>
      <label class="flbl">اسم المجموعة</label>
      <input class="finp" type="text" id="h-name" placeholder="مثال: قطيع الأبقار الشمالي">
      <label class="flbl">العدد</label>
      <input class="finp" type="number" id="h-count" min="1" placeholder="100">
      <label class="flbl">الموقع / المرعى</label>
      <input class="finp" type="text" id="h-location" placeholder="مثال: المرعى الجنوبي">
      <label class="flbl">الحالة الصحية</label>
      <div class="status-opts">
        <div class="status-opt on healthy" data-v="healthy" onclick="pickStatus(this)">✅ سليم</div>
        <div class="status-opt needs_attention" data-v="needs_attention" onclick="pickStatus(this)">⚠️ متابعة</div>
        <div class="status-opt critical" data-v="critical" onclick="pickStatus(this)">🚨 حرج</div>
      </div>
      <label class="flbl">ملاحظات</label>
      <input class="finp" type="text" id="h-notes" placeholder="أي ملاحظات إضافية...">
      <button class="btn-save" onclick="saveHerd()">💾 حفظ</button>
    </div>
  </div>
</div>

<div class="page-wrap">
  <!-- NAV -->
  <nav class="topnav">
    <a href="../home.php"><img src="../assets/img/logo.png?v=3" alt="VetNet" style="height:44px;object-fit:contain;"></a>
    <div class="nav-title">إدارة القطيع</div>
    <div style="margin-right:auto;display:flex;gap:8px;">
      <button class="nav-btn" onclick="window.location.href='../index.php'">🏠</button>
      <button class="nav-btn" onclick="logout()">🚪</button>
    </div>
  </nav>

  <!-- HERO -->
  <div class="farm-hero">
    <div class="fh-name">🚜 <?= h($user['name']) ?></div>
    <div class="fh-sub"><?= $totalAnimals ?> رأس في <?= count($herdList) ?> مجموعات</div>
  </div>

  <!-- STATS -->
  <div class="stats">
    <div class="stat total"><div class="sn"><?= $totalAnimals ?></div><div class="sl">إجمالي الرؤوس</div></div>
    <div class="stat healthy"><div class="sn"><?= $healthyHerds ?></div><div class="sl">مجموعات سليمة</div></div>
    <div class="stat warn"><div class="sn"><?= $needsAttn ?></div><div class="sl">تحتاج متابعة</div></div>
    <div class="stat crit"><div class="sn"><?= $criticalHerds ?></div><div class="sl">حالات حرجة</div></div>
  </div>

  <!-- HERDS LIST -->
  <div class="sec" style="margin-top:8px;">
    <div class="sec-hdr">
      <div class="sec-title">🐄 مجموعات القطيع</div>
      <button class="btn-add" onclick="openAddHerd()">➕ إضافة</button>
    </div>

    <?php if (empty($herdList)): ?>
    <div class="empty">
      <div class="empty-icon">🐄</div>
      <p>لم تضف أي مجموعات بعد<br>ابدأ بإضافة قطيعك الأول</p>
      <button class="btn-add" style="margin:16px auto 0;display:inline-flex;" onclick="openAddHerd()">➕ إضافة أول مجموعة</button>
    </div>
    <?php else: ?>
    <?php foreach ($herdList as $h):
      $icon = $speciesIcons[$h['species']] ?? '🐾';
      $statusClass = $h['health_status'];
      $healthPct = ['healthy'=>100,'needs_attention'=>55,'critical'=>20][$h['health_status']] ?? 50;
      $barColor = ['healthy'=>'#22c55e','needs_attention'=>'#f59e0b','critical'=>'#ef4444'][$h['health_status']] ?? '#22c55e';
      $badgeClass = $h['health_status'];
      $badgeLabel = ['healthy'=>'✅ سليم','needs_attention'=>'⚠️ يحتاج متابعة','critical'=>'🚨 حالة حرجة'][$h['health_status']] ?? '';
    ?>
    <div class="herd-card <?= $statusClass ?>">
      <div class="herd-top">
        <div class="herd-icon <?= $h['species'] ?>"><?= $icon ?></div>
        <div class="herd-info">
          <div class="herd-name"><?= h($h['name']) ?></div>
          <div class="herd-sub"><?= ($speciesLabel[$h['species']]??$h['species']) ?> · <?= $h['count'] ?> رأس<?= $h['location_name'] ? ' · 📍 '.h($h['location_name']) : '' ?></div>
        </div>
        <div class="hbadge <?= $badgeClass ?>"><?= $badgeLabel ?></div>
      </div>

      <div class="health-bar">
        <div class="hb-label">
          <span>الحالة الصحية العامة</span>
          <span><?= $healthPct ?>%</span>
        </div>
        <div class="hb-track">
          <div class="hb-fill" style="width:<?= $healthPct ?>%;background:<?= $barColor ?>;"></div>
        </div>
      </div>

      <?php if ($h['notes']): ?>
      <div style="margin-top:8px;font-size:12px;color:var(--ts);font-style:italic;">📝 <?= h($h['notes']) ?></div>
      <?php endif; ?>

      <div class="herd-actions">
        <button class="ha-btn ha-book" onclick="bookVetForHerd(<?= $h['id'] ?>, '<?= h($h['name']) ?>')">📅 حجز طبيب</button>
        <?php if ($h['health_status'] === 'critical'): ?>
        <button class="ha-btn ha-emg" onclick="window.location.href='emergency-map.php?animal=<?= urlencode($icon.' '.$speciesLabel[$h['species']]??'') ?>'">🚨 طوارئ</button>
        <?php endif; ?>
        <button class="ha-btn ha-edit" onclick="openEditHerd(<?= htmlspecialchars(json_encode($h), ENT_QUOTES) ?>)">✏️ تعديل</button>
      </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- RECENT APPOINTMENTS -->
  <div class="sec">
    <div class="sec-hdr">
      <div class="sec-title">📅 آخر المواعيد</div>
      <button class="btn-add" style="background:var(--inp);color:var(--g6);box-shadow:none;border:1.5px solid var(--g4);" onclick="window.location.href='../index.php'">عرض الكل</button>
    </div>
    <?php if (empty($recentAppts)): ?>
    <div class="empty"><div class="empty-icon">📅</div><p>لا توجد مواعيد سابقة</p></div>
    <?php else: ?>
    <?php foreach ($recentAppts as $a):
      $d = date('d', strtotime($a['scheduled_at']));
      $m = date('m', strtotime($a['scheduled_at']));
      $stMap = ['confirmed'=>'sp-confirmed مؤكد','pending'=>'sp-pending انتظار','completed'=>'sp-completed مكتمل','cancelled'=>'sp-cancelled ملغى'];
      $st = explode(' ', $stMap[$a['status']] ?? 'sp-pending '.$a['status']);
    ?>
    <div class="appt-mini">
      <div class="am-date">
        <div class="amd-d"><?= $d ?></div>
        <div class="amd-m">/<?= $m ?></div>
      </div>
      <div class="am-info">
        <div class="am-vet">🩺 <?= h($a['vet_name']) ?></div>
        <div class="am-sub">⏰ <?= date('H:i', strtotime($a['scheduled_at'])) ?> · <?= number_format((float)($a['fee']??0)) ?> دج</div>
      </div>
      <span class="sp <?= $st[0] ?>"><?= $st[1] ?></span>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<!-- BOTTOM NAV -->
<nav class="bnav">
  <div class="bn-item on"><div class="bn-icon">🐄</div><div class="bn-label">القطيع</div></div>
  <div class="bn-item" onclick="window.location.href='../index.php'"><div class="bn-icon">🏠</div><div class="bn-label">الرئيسية</div></div>
  <div class="bn-item" onclick="window.location.href='emergency-map.php'"><div class="bn-icon">🚨</div><div class="bn-label">طوارئ</div></div>
  <div class="bn-item" onclick="window.location.href='../index.php'"><div class="bn-icon">📅</div><div class="bn-label">مواعيد</div></div>
</nav>

<script>
var selectedStatus = 'healthy';
var editingHerdId  = null;

function pickStatus(el) {
  document.querySelectorAll('.status-opt').forEach(function(o){ o.classList.remove('on'); });
  el.classList.add('on');
  selectedStatus = el.dataset.v;
}

function openAddHerd() {
  editingHerdId = null;
  document.getElementById('modal-title').textContent = '➕ إضافة مجموعة';
  document.getElementById('herd-id-inp').value = '';
  document.getElementById('h-name').value = '';
  document.getElementById('h-count').value = '';
  document.getElementById('h-location').value = '';
  document.getElementById('h-notes').value = '';
  selectedStatus = 'healthy';
  document.querySelectorAll('.status-opt').forEach(function(o){
    o.classList.toggle('on', o.dataset.v === 'healthy');
  });
  document.getElementById('herd-modal').classList.add('open');
  document.body.style.overflow = 'hidden';
}

function openEditHerd(h) {
  editingHerdId = h.id;
  document.getElementById('modal-title').textContent = '✏️ تعديل: ' + h.name;
  document.getElementById('herd-id-inp').value = h.id;
  document.getElementById('h-species').value = h.species;
  document.getElementById('h-name').value = h.name;
  document.getElementById('h-count').value = h.count;
  document.getElementById('h-location').value = h.location_name || '';
  document.getElementById('h-notes').value = h.notes || '';
  selectedStatus = h.health_status;
  document.querySelectorAll('.status-opt').forEach(function(o){
    o.classList.toggle('on', o.dataset.v === h.health_status);
  });
  document.getElementById('herd-modal').classList.add('open');
  document.body.style.overflow = 'hidden';
}

function closeModal() {
  document.getElementById('herd-modal').classList.remove('open');
  document.body.style.overflow = '';
}
document.getElementById('herd-modal').addEventListener('click', function(e){
  if(e.target===this) closeModal();
});

async function saveHerd() {
  var name  = document.getElementById('h-name').value.trim();
  var count = document.getElementById('h-count').value;
  if (!name || !count) { toast('error','الرجاء تعبئة الاسم والعدد'); return; }

  var body = 'action=' + (editingHerdId ? 'update_herd' : 'add_herd')
    + '&herd_id=' + (editingHerdId||0)
    + '&species=' + encodeURIComponent(document.getElementById('h-species').value)
    + '&name='    + encodeURIComponent(name)
    + '&count='   + encodeURIComponent(count)
    + '&location_name=' + encodeURIComponent(document.getElementById('h-location').value)
    + '&health_status=' + encodeURIComponent(selectedStatus)
    + '&notes='   + encodeURIComponent(document.getElementById('h-notes').value);

  try {
    var res = await fetch('../api/index.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:body
    });
    var data = await res.json();
    toast('success', editingHerdId ? '✅ تم تحديث المجموعة' : '✅ تمت إضافة المجموعة');
    closeModal();
    setTimeout(function(){ location.reload(); }, 900);
  } catch(e) {
    toast('success', editingHerdId ? '✅ تم التحديث (تجريبي)' : '✅ تمت الإضافة (تجريبي)');
    closeModal();
    setTimeout(function(){ location.reload(); }, 900);
  }
}

function bookVetForHerd(herdId, herdName) {
  window.location.href = '../index.php?action=book&herd=' + herdId;
}

async function logout() {
  await fetch('../api/auth.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action=logout'});
  window.location.href = '../login.php';
}

function toast(type, msg) {
  var icons = {success:'✅',error:'❌',info:'ℹ️'};
  document.getElementById('ti').textContent  = icons[type]||'ℹ️';
  document.getElementById('tm2').textContent = msg;
  var t = document.getElementById('toast');
  t.classList.add('on');
  setTimeout(function(){ t.classList.remove('on'); }, 3500);
}
</script>
</body>
</html>
