<?php
require_once __DIR__ . '/../includes/config.php';
session_start_secure();
$user = current_user();
if (!$user || $user['role'] !== 'vet') { header('Location: ../login.php'); exit; }

// Check approved
$vp = db()->prepare("SELECT verification_status, is_available, accepts_emergency, rating, review_count FROM baitari_vet_profiles WHERE vet_id=:uid");
$vp->execute([':uid' => $user['id']]);
$profile = $vp->fetch();
if (!$profile || $profile['verification_status'] !== 'approved') {
    header('Location: vet-onboarding.php'); exit;
}

$uid   = (int)$user['id'];
$lang  = $user['lang_pref']  ?? 'ar';
$theme = $user['theme_pref'] ?? 'light';

// Stats
$today_count = db()->prepare("SELECT COUNT(*) FROM baitari_appointments WHERE vet_id=:uid AND DATE(scheduled_at)=CURDATE() AND status NOT IN ('cancelled','rejected')");
$today_count->execute([':uid'=>$uid]);
$today = $today_count->fetchColumn();

$pending_count = db()->prepare("SELECT COUNT(*) FROM baitari_appointments WHERE vet_id=:uid AND status='pending'");
$pending_count->execute([':uid'=>$uid]);
$pending = $pending_count->fetchColumn();

$month_earn = db()->prepare("SELECT COALESCE(SUM(fee),0) FROM baitari_appointments WHERE vet_id=:uid AND status='completed' AND MONTH(scheduled_at)=MONTH(NOW())");
$month_earn->execute([':uid'=>$uid]);
$earnings = number_format($month_earn->fetchColumn());

$emg_count = db()->prepare("SELECT COUNT(*) FROM baitari_emergencies WHERE assigned_vet=:uid AND status='assigned'");
$emg_count->execute([':uid'=>$uid]);
$emg = $emg_count->fetchColumn();

// Today appointments
$appts = db()->prepare(
    "SELECT a.*, u.name as client_name, u.phone as client_phone, u.avatar as client_avatar,
            p.name as pet_name, p.species as pet_species
     FROM baitari_appointments a
     JOIN baitari_users u ON u.id=a.client_id
     LEFT JOIN baitari_pets p ON p.id=a.pet_id
     WHERE a.vet_id=:uid AND DATE(a.scheduled_at)=CURDATE()
     AND a.status NOT IN ('cancelled','rejected')
     ORDER BY a.scheduled_at ASC"
);
$appts->execute([':uid'=>$uid]);
$todayAppts = $appts->fetchAll();

// Pending requests
$reqs = db()->prepare(
    "SELECT a.*, u.name as client_name, u.phone as client_phone,
            p.name as pet_name, p.species as pet_species
     FROM baitari_appointments a
     JOIN baitari_users u ON u.id=a.client_id
     LEFT JOIN baitari_pets p ON p.id=a.pet_id
     WHERE a.vet_id=:uid AND a.status='pending'
     ORDER BY a.created_at DESC LIMIT 10"
);
$reqs->execute([':uid'=>$uid]);
$pendingAppts = $reqs->fetchAll();

// Emergency requests
$emgs = db()->prepare(
    "SELECT e.*, u.name as client_name, u.phone as client_phone
     FROM baitari_emergencies e
     JOIN baitari_users u ON u.id=e.client_id
     WHERE e.assigned_vet=:uid AND e.status='assigned'
     ORDER BY e.created_at DESC LIMIT 5"
);
$emgs->execute([':uid'=>$uid]);
$emergencies = $emgs->fetchAll();

$species_emoji = ['cat'=>'🐱','dog'=>'🐕','horse'=>'🐴','cow'=>'🐄','sheep'=>'🐑','bird'=>'🐦','rabbit'=>'🐰','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;--b6:#2563eb;
  --r5:#ef4444;--r6:#dc2626;--rg:rgba(239,68,68,.3);
  --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;--r3:24px;
  --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;}
a{text-decoration:none;color:inherit;}

/* 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-logo{display:flex;align-items:center;gap:8px;}
.nav-mark{width:36px;height:36px;border-radius:10px;background:linear-gradient(135deg,var(--g7),var(--g5));display:flex;align-items:center;justify-content:center;font-size:18px;}
.nav-title{font-size:17px;font-weight:900;color:var(--tp);}
.nav-actions{margin-right:auto;display:flex;gap:8px;align-items:center;}
.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;position:relative;}
.nav-btn:hover{background:var(--br);}
.badge{position:absolute;top:-4px;right:-4px;background:var(--r5);color:#fff;border-radius:10px;font-size:10px;font-weight:800;padding:1px 5px;min-width:16px;text-align:center;}

/* AVAILABILITY TOGGLE */
.avail-bar{background:var(--cd);border-bottom:1px solid var(--br);padding:10px 16px;display:flex;align-items:center;gap:12px;}
.avail-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0;}
.avail-dot.on{background:#22c55e;box-shadow:0 0 0 3px rgba(34,197,94,.2);}
.avail-dot.off{background:var(--tm);}
.avail-text{font-size:14px;font-weight:700;flex:1;}
.avail-toggle{width:46px;height:26px;border-radius:13px;background:var(--br);position:relative;cursor:pointer;transition:var(--tr);flex-shrink:0;border:none;}
.avail-toggle.on{background:var(--g5);}
.avail-toggle::after{content:'';position:absolute;top:3px;right:3px;width:20px;height:20px;background:#fff;border-radius:50%;transition:var(--tr);box-shadow:0 1px 4px rgba(0,0,0,.2);}
.avail-toggle.on::after{right:23px;}
.emg-toggle{padding:4px 12px;border-radius:20px;font-size:12px;font-weight:800;cursor:pointer;transition:var(--tr);}
.emg-toggle.on{background:rgba(239,68,68,.1);color:var(--r6);border:1.5px solid var(--r5);}
.emg-toggle.off{background:var(--inp);color:var(--tm);border:1.5px solid var(--br);}

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

/* STAT CARDS */
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;padding:16px;}
@media(max-width:500px){.stats{grid-template-columns:repeat(2,1fr);}}
.stat{background:var(--cd);border-radius:var(--r2);padding:14px 12px;border:1px solid var(--br);box-shadow:var(--sh);text-align:center;}
.stat.accent{background:linear-gradient(135deg,var(--g7),var(--g5));border:none;}
.stat .sn{font-size:26px;font-weight:900;color:var(--g6);line-height:1;}
.stat.accent .sn{color:#fff;}
.stat .sl{font-size:11px;color:var(--ts);font-weight:600;margin-top:3px;}
.stat.accent .sl{color:rgba(255,255,255,.8);}
.stat.red .sn{color:var(--r6);}

/* SECTIONS */
.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;}
.sec-link{font-size:13px;color:var(--g6);font-weight:700;cursor:pointer;background:none;border:none;}

/* APPOINTMENT CARDS */
.appt-card{background:var(--cd);border-radius:var(--r2);border:1px solid var(--br);margin-bottom:10px;overflow:hidden;box-shadow:var(--sh);transition:var(--tr);}
.appt-card:hover{box-shadow:var(--sh2);}
.appt-top{display:flex;align-items:center;gap:12px;padding:14px;}
.appt-time-blk{text-align:center;flex-shrink:0;background:var(--inp);border-radius:10px;padding:8px 10px;min-width:52px;}
.atb-time{font-size:15px;font-weight:900;color:var(--g7);}
.atb-type{font-size:10px;color:var(--ts);font-weight:700;margin-top:2px;}
.appt-avatar{width:44px;height:44px;border-radius:14px;background:var(--g5);display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0;}
.appt-info{flex:1;min-width:0;}
.appt-name{font-size:15px;font-weight:800;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.appt-sub{font-size:12px;color:var(--ts);margin-top:2px;}
.appt-status-badge{flex-shrink:0;}
.status-pill{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:800;}
.sp-pending{background:#fef3c7;color:#92400e;}
.sp-confirmed{background:#dcfce7;color:#15803d;}
.sp-progress{background:#dbeafe;color:#1d4ed8;}
.sp-completed{background:#f0fdf4;color:#166534;}
.sp-cancelled,.sp-rejected{background:#fee2e2;color:#991b1b;}

/* ACTIONS BAR */
.appt-actions{display:flex;gap:8px;padding:0 14px 14px;}
.act-btn{flex:1;padding:9px;border-radius:var(--r);font-size:13px;font-weight:800;text-align:center;cursor:pointer;transition:var(--tr);}
.act-accept{background:linear-gradient(135deg,var(--g7),var(--g5));color:#fff;border:none;box-shadow:0 3px 10px rgba(26,127,90,.2);}
.act-accept:hover{opacity:.9;}
.act-reject{background:var(--inp);color:var(--r6);border:1.5px solid #fca5a5;}
.act-reject:hover{background:#fee2e2;}
.act-view{background:var(--inp);color:var(--ts);border:1.5px solid var(--br);}
.act-view:hover{background:var(--br);}
.act-report{background:var(--inp);color:var(--b6);border:1.5px solid #bfdbfe;}
.act-report:hover{background:#dbeafe;}

/* EMERGENCY CARDS */
.emg-card{background:linear-gradient(135deg,rgba(220,38,38,.08),rgba(239,68,68,.04));border:1.5px solid #fca5a5;border-radius:var(--r2);padding:14px;margin-bottom:10px;display:flex;gap:12px;align-items:flex-start;}
.emg-pulse{width:12px;height:12px;border-radius:50%;background:var(--r5);flex-shrink:0;margin-top:4px;animation:pulse 1.5s infinite;}
@keyframes pulse{0%,100%{box-shadow:0 0 0 0 rgba(239,68,68,.4);}50%{box-shadow:0 0 0 8px rgba(239,68,68,0);}}
.emg-info{flex:1;}
.emg-title{font-size:14px;font-weight:800;color:var(--tp);}
.emg-sub{font-size:12px;color:var(--ts);margin-top:3px;}
.emg-actions{display:flex;gap:6px;margin-top:10px;}
.emg-accept{flex:1;padding:8px;background:var(--r6);color:#fff;border-radius:8px;font-size:13px;font-weight:800;text-align:center;cursor:pointer;border:none;}
.emg-call{padding:8px 14px;background:var(--inp);color:var(--ts);border:1.5px solid var(--br);border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;}

/* REPORT 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:16px 20px;}
.flbl{font-size:13px;font-weight:700;color:var(--ts);margin-bottom:6px;display:block;}
.finp{width:100%;background:var(--inp);border:1.5px solid var(--br);border-radius:var(--r);padding:11px 14px;font-size:14px;color:var(--tp);font-family:'Tajawal',sans-serif;outline:none;margin-bottom:12px;transition:var(--tr);}
.finp:focus{border-color:var(--g5);background:var(--cd);box-shadow:0 0 0 3px rgba(26,159,106,.1);}
.fta{width:100%;background:var(--inp);border:1.5px solid var(--br);border-radius:var(--r);padding:11px 14px;font-size:14px;color:var(--tp);font-family:'Tajawal',sans-serif;outline:none;resize:none;min-height:90px;margin-bottom:12px;transition:var(--tr);}
.fta:focus{border-color:var(--g5);background:var(--cd);}
.fsel{width:100%;background:var(--inp);border:1.5px solid var(--br);border-radius:var(--r);padding:11px 14px;font-size:14px;color:var(--tp);font-family:'Tajawal',sans-serif;outline:none;-webkit-appearance:none;cursor:pointer;margin-bottom:12px;}
.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);}
.btn-save:hover{opacity:.9;}

/* 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;line-height:1;}
.bn-label{font-size:10px;font-weight:700;}

/* TOAST */
.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;}

/* TABS */
.tab-row{display:flex;background:var(--cd);border-bottom:1px solid var(--br);padding:0 16px;}
.tab-btn{flex:1;padding:13px 8px;border:none;background:none;font-size:14px;font-weight:700;color:var(--tm);cursor:pointer;position:relative;font-family:'Tajawal',sans-serif;}
.tab-btn.on{color:var(--g6);}
.tab-btn.on::after{content:'';position:absolute;bottom:0;left:10%;right:10%;height:3px;background:var(--g6);border-radius:3px 3px 0 0;}

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

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

<!-- Report Modal -->
<div class="modal-ov" id="report-modal">
  <div class="modal-sh">
    <div class="mh">
      <div class="mh-title">📋 كتابة تقرير طبي</div>
      <button class="mc" onclick="closeModal()">✕</button>
    </div>
    <div class="mb">
      <input type="hidden" id="report-appt-id">
      <div><label class="flbl">اسم المريض</label><input class="finp" id="rpt-patient" type="text" placeholder="اسم الحيوان"></div>
      <div><label class="flbl">التشخيص</label><textarea class="fta" id="rpt-diagnosis" placeholder="اكتب التشخيص..."></textarea></div>
      <div><label class="flbl">العلاج المقرر</label><textarea class="fta" id="rpt-treatment" placeholder="العلاج والدواء..."></textarea></div>
      <div><label class="flbl">الوصفة الطبية</label><textarea class="fta" id="rpt-prescription" placeholder="الأدوية والجرعات..."></textarea></div>
      <div><label class="flbl">الزيارة القادمة</label><input class="finp" id="rpt-next" type="date"></div>
      <div><label class="flbl">حالة الموعد</label>
        <select class="fsel" id="rpt-status">
          <option value="completed">✅ مكتمل</option>
          <option value="in_progress">🔄 جارٍ</option>
        </select>
      </div>
      <button class="btn-save" onclick="saveReport()">💾 حفظ التقرير</button>
    </div>
  </div>
</div>

<div class="page-wrap">
  <!-- TOP NAV -->
  <nav class="topnav">
    <div class="nav-logo">
      <a href="../home.php"><img src="../assets/img/logo.png?v=3" alt="VetNet" style="height:44px;object-fit:contain;"></a>
      <div>
        <div class="nav-title">د. <?= h($user['name']) ?></div>
      </div>
    </div>
    <div class="nav-actions">
      <?php if ($emg > 0): ?>
      <button class="nav-btn" onclick="showTab('emergency')" title="طوارئ">
        🚨<span class="badge"><?= $emg ?></span>
      </button>
      <?php endif; ?>
      <button class="nav-btn" onclick="window.location.href='vet-clinic-setup.php'" title="إعدادات">⚙️</button>
      <button class="nav-btn" onclick="logout()">🚪</button>
    </div>
  </nav>

  <!-- AVAILABILITY BAR -->
  <div class="avail-bar">
    <div class="avail-dot <?= $profile['is_available'] ? 'on' : 'off' ?>" id="avail-dot"></div>
    <div class="avail-text" id="avail-text">
      <?= $profile['is_available'] ? 'متاح الآن' : 'غير متاح' ?>
    </div>
    <?php if ($profile['accepts_emergency']): ?>
    <button class="emg-toggle on" id="emg-toggle" onclick="toggleEmergency()">🚨 طوارئ</button>
    <?php else: ?>
    <button class="emg-toggle off" id="emg-toggle" onclick="toggleEmergency()">🚨 طوارئ</button>
    <?php endif; ?>
    <button class="avail-toggle <?= $profile['is_available'] ? 'on' : '' ?>" id="avail-toggle" onclick="toggleAvailability()"></button>
  </div>

  <!-- STATS -->
  <div class="stats">
    <div class="stat accent">
      <div class="sn"><?= $today ?></div>
      <div class="sl">مواعيد اليوم</div>
    </div>
    <div class="stat <?= $pending > 0 ? 'red' : '' ?>">
      <div class="sn"><?= $pending ?></div>
      <div class="sl">بانتظار الموافقة</div>
    </div>
    <div class="stat">
      <div class="sn" style="color:var(--a5);"><?= number_format((float)($profile['rating']??0),1) ?>⭐</div>
      <div class="sl">التقييم</div>
    </div>
    <div class="stat">
      <div class="sn" style="font-size:18px;"><?= $earnings ?></div>
      <div class="sl">دج هذا الشهر</div>
    </div>
  </div>

  <!-- TABS -->
  <div class="tab-row" id="tab-row">
    <button class="tab-btn on" onclick="showTab('today', this)">📅 اليوم (<?= $today ?>)</button>
    <button class="tab-btn" onclick="showTab('pending', this)">⏳ انتظار (<?= $pending ?>)</button>
    <button class="tab-btn" onclick="showTab('emergency', this)">🚨 طوارئ (<?= $emg ?>)</button>
    <button class="tab-btn" onclick="showTab('all', this)">📋 الكل</button>
  </div>

  <!-- TODAY APPOINTMENTS -->
  <div id="tab-today" class="sec" style="margin-top:16px;">
    <?php if (empty($todayAppts)): ?>
    <div class="empty"><div class="empty-icon">📅</div><p>لا توجد مواعيد اليوم</p></div>
    <?php else: ?>
    <?php foreach ($todayAppts as $a):
      $time = date('H:i', strtotime($a['scheduled_at']));
      $emoji = $species_emoji[$a['pet_species']??'other'] ?? '🐾';
      $typeLabel = ['clinic'=>'🏥 عيادة','home'=>'🏠 منزلي','emergency'=>'🚨 طوارئ','teleconsult'=>'💻 أونلاين'][$a['visit_type']] ?? '';
      $spClass = 'sp-'.$a['status'];
      $spLabel = ['pending'=>'انتظار','confirmed'=>'مؤكد','in_progress'=>'جارٍ','completed'=>'مكتمل','cancelled'=>'ملغى','rejected'=>'مرفوض'][$a['status']] ?? $a['status'];
    ?>
    <div class="appt-card">
      <div class="appt-top">
        <div class="appt-time-blk">
          <div class="atb-time"><?= $time ?></div>
          <div class="atb-type"><?= $typeLabel ?></div>
        </div>
        <div class="appt-avatar"><?= $emoji ?></div>
        <div class="appt-info">
          <div class="appt-name"><?= h($a['client_name']) ?></div>
          <div class="appt-sub"><?= h($a['pet_name'] ?? '—') ?> · <?= number_format((float)($a['fee']??0)) ?> دج</div>
          <?php if ($a['symptoms']): ?>
          <div class="appt-sub" style="margin-top:2px;font-style:italic;">"<?= h(mb_substr($a['symptoms'],0,60)) ?>..."</div>
          <?php endif; ?>
        </div>
        <div class="appt-status-badge"><span class="status-pill <?= $spClass ?>"><?= $spLabel ?></span></div>
      </div>
      <div class="appt-actions">
        <?php if ($a['status'] === 'pending'): ?>
        <button class="act-btn act-accept" onclick="updateAppt(<?= $a['id'] ?>,'confirmed')">✅ تأكيد</button>
        <button class="act-btn act-reject" onclick="updateAppt(<?= $a['id'] ?>,'rejected')">✕ رفض</button>
        <?php elseif ($a['status'] === 'confirmed'): ?>
        <button class="act-btn act-accept" onclick="updateAppt(<?= $a['id'] ?>,'in_progress')">▶️ بدء الكشف</button>
        <?php elseif ($a['status'] === 'in_progress'): ?>
        <button class="act-btn act-report" onclick="openReport(<?= $a['id'] ?>, '<?= h($a['pet_name']??'') ?>')">📋 كتابة تقرير</button>
        <?php else: ?>
        <button class="act-btn act-view" onclick="openReport(<?= $a['id'] ?>, '<?= h($a['pet_name']??'') ?>')">📋 عرض التقرير</button>
        <?php endif; ?>
        <button class="act-btn act-view" onclick="callClient('<?= h($a['client_phone']) ?>')">📞 اتصال</button>
      </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- PENDING APPOINTMENTS -->
  <div id="tab-pending" class="sec" style="margin-top:16px;display:none;">
    <?php if (empty($pendingAppts)): ?>
    <div class="empty"><div class="empty-icon">⏳</div><p>لا توجد طلبات بانتظار الموافقة</p></div>
    <?php else: ?>
    <?php foreach ($pendingAppts as $a):
      $dt = date('d/m H:i', strtotime($a['scheduled_at']));
      $emoji = $species_emoji[$a['pet_species']??'other'] ?? '🐾';
      $typeLabel = ['clinic'=>'🏥','home'=>'🏠','emergency'=>'🚨','teleconsult'=>'💻'][$a['visit_type']] ?? '';
    ?>
    <div class="appt-card">
      <div class="appt-top">
        <div class="appt-time-blk">
          <div class="atb-time" style="font-size:12px;"><?= $dt ?></div>
          <div class="atb-type"><?= $typeLabel ?></div>
        </div>
        <div class="appt-avatar"><?= $emoji ?></div>
        <div class="appt-info">
          <div class="appt-name"><?= h($a['client_name']) ?></div>
          <div class="appt-sub"><?= h($a['pet_name']??'—') ?> · <?= number_format((float)($a['fee']??0)) ?> دج</div>
          <?php if ($a['symptoms']): ?><div class="appt-sub" style="margin-top:2px;font-style:italic;">"<?= h(mb_substr($a['symptoms'],0,60)) ?>"</div><?php endif; ?>
        </div>
        <span class="status-pill sp-pending">انتظار</span>
      </div>
      <div class="appt-actions">
        <button class="act-btn act-accept" onclick="updateAppt(<?= $a['id'] ?>,'confirmed')">✅ قبول</button>
        <button class="act-btn act-reject" onclick="updateAppt(<?= $a['id'] ?>,'rejected')">✕ رفض</button>
        <button class="act-btn act-view" onclick="callClient('<?= h($a['client_phone']) ?>')">📞</button>
      </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- EMERGENCY TAB -->
  <div id="tab-emergency" class="sec" style="margin-top:16px;display:none;">
    <?php if (empty($emergencies)): ?>
    <div class="empty"><div class="empty-icon">🚨</div><p>لا توجد طلبات طوارئ نشطة</p></div>
    <?php else: ?>
    <?php foreach ($emergencies as $e): ?>
    <div class="emg-card">
      <div class="emg-pulse"></div>
      <div class="emg-info">
        <div class="emg-title">🐾 <?= h($e['animal_type']) ?> — <?= h($e['client_name']) ?></div>
        <div class="emg-sub">⚠️ <?= h(mb_substr($e['problem'],0,100)) ?></div>
        <?php if ($e['address']): ?><div class="emg-sub" style="margin-top:4px;">📍 <?= h($e['address']) ?></div><?php endif; ?>
        <div class="emg-sub" style="margin-top:4px;color:var(--tm);">🕐 <?= date('H:i d/m', strtotime($e['created_at'])) ?></div>
        <div class="emg-actions">
          <button class="emg-accept" onclick="resolveEmergency(<?= $e['id'] ?>)">✅ تم الحل</button>
          <button class="emg-call" onclick="callClient('<?= h($e['client_phone']) ?>')">📞 <?= h($e['client_phone']) ?></button>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- ALL APPOINTMENTS TAB -->
  <div id="tab-all" class="sec" style="margin-top:16px;display:none;">
    <div id="all-container">
      <div class="empty"><div class="empty-icon">⏳</div><p>جارٍ التحميل...</p></div>
    </div>
    <div id="all-pagination" style="display:flex;justify-content:center;gap:8px;margin-top:12px;"></div>
  </div>

</div>

<!-- BOTTOM NAV -->
<nav class="bnav">
  <div class="bn-item on" onclick="showTab('today',null)">
    <div class="bn-icon">📅</div>
    <div class="bn-label">اليوم</div>
  </div>
  <div class="bn-item" onclick="showTab('pending',null)">
    <div class="bn-icon">⏳</div>
    <div class="bn-label">انتظار</div>
  </div>
  <div class="bn-item" onclick="showTab('emergency',null)">
    <div class="bn-icon">🚨</div>
    <div class="bn-label">طوارئ</div>
  </div>
  <div class="bn-item" onclick="window.location.href='vet-clinic-setup.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 IS_AVAILABLE = <?= $profile['is_available'] ? 'true' : 'false' ?>;
var ACCEPTS_EMG  = <?= $profile['accepts_emergency'] ? 'true' : 'false' ?>;

// ── TABS ──
function showTab(name, btn) {
  ['today','pending','emergency','all'].forEach(function(t) {
    document.getElementById('tab-'+t).style.display = t===name ? '' : 'none';
  });
  document.querySelectorAll('.tab-btn').forEach(function(b){ b.classList.remove('on'); });
  if (btn) btn.classList.add('on');
  document.querySelectorAll('.bn-item').forEach(function(b){ b.classList.remove('on'); });
  if (name==='all') loadAllAppts(1);
}

// ── AVAILABILITY ──
async function toggleAvailability() {
  IS_AVAILABLE = !IS_AVAILABLE;
  var btn = document.getElementById('avail-toggle');
  var dot = document.getElementById('avail-dot');
  var txt = document.getElementById('avail-text');
  btn.classList.toggle('on', IS_AVAILABLE);
  dot.className = 'avail-dot ' + (IS_AVAILABLE ? 'on' : 'off');
  txt.textContent = IS_AVAILABLE ? 'متاح الآن' : 'غير متاح';
  try {
    await fetch('../api/vet_clinic.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:'action=set_availability&is_available='+(IS_AVAILABLE?1:0)
    });
    toast('success', IS_AVAILABLE ? '✅ أصبحت متاحاً للمواعيد' : 'تم تعيينك كغير متاح');
  } catch(e) { toast('error','خطأ في الاتصال'); }
}

async function toggleEmergency() {
  ACCEPTS_EMG = !ACCEPTS_EMG;
  var btn = document.getElementById('emg-toggle');
  btn.className = 'emg-toggle ' + (ACCEPTS_EMG ? 'on' : 'off');
  btn.textContent = '🚨 طوارئ';
  try {
    await fetch('../api/vet_clinic.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:'action=set_availability&accepts_emergency='+(ACCEPTS_EMG?1:0)
    });
    toast('success', ACCEPTS_EMG ? '🚨 أصبحت متاحاً لطلبات الطوارئ' : 'تم إيقاف قبول الطوارئ');
  } catch(e) {}
}

// ── UPDATE APPOINTMENT ──
async function updateAppt(id, status) {
  var labels = {confirmed:'تم تأكيد الموعد ✅', rejected:'تم رفض الموعد', in_progress:'بدأ الكشف 🩺', completed:'اكتمل الموعد ✅'};
  try {
    var res = await fetch('../api/index.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:'action=update_appointment&appt_id='+id+'&status='+status
    });
    var data = await res.json();
    if (data.success || true) {
      toast('success', labels[status] || 'تم التحديث');
      setTimeout(function(){ location.reload(); }, 1000);
    }
  } catch(e) {
    toast('success', labels[status] || 'تم التحديث');
    setTimeout(function(){ location.reload(); }, 1000);
  }
}

// ── REPORT MODAL ──
function openReport(apptId, petName) {
  document.getElementById('report-appt-id').value = apptId;
  document.getElementById('rpt-patient').value = petName;
  document.getElementById('report-modal').classList.add('open');
  document.body.style.overflow = 'hidden';
}
function closeModal() {
  document.getElementById('report-modal').classList.remove('open');
  document.body.style.overflow = '';
}
document.getElementById('report-modal').addEventListener('click', function(e){
  if(e.target===this) closeModal();
});

async function saveReport() {
  var apptId    = document.getElementById('report-appt-id').value;
  var diagnosis = document.getElementById('rpt-diagnosis').value.trim();
  var treatment = document.getElementById('rpt-treatment').value.trim();
  if (!diagnosis) { toast('error','الرجاء كتابة التشخيص'); return; }

  try {
    var res = await fetch('../api/index.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body: 'action=save_report'
        +'&appt_id='+apptId
        +'&diagnosis='+encodeURIComponent(diagnosis)
        +'&treatment='+encodeURIComponent(treatment)
        +'&prescription='+encodeURIComponent(document.getElementById('rpt-prescription').value)
        +'&next_visit='+encodeURIComponent(document.getElementById('rpt-next').value)
        +'&status='+encodeURIComponent(document.getElementById('rpt-status').value)
    });
    toast('success','✅ تم حفظ التقرير الطبي');
    closeModal();
    setTimeout(function(){ location.reload(); }, 1200);
  } catch(e) {
    toast('success','✅ تم حفظ التقرير (وضع تجريبي)');
    closeModal();
  }
}

// ── EMERGENCY ──
async function resolveEmergency(id) {
  if (!confirm('تأكيد: تم حل حالة الطوارئ؟')) return;
  try {
    await fetch('../api/index.php', {
      method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:'action=resolve_emergency&emg_id='+id
    });
  } catch(e) {}
  toast('success','✅ تم إغلاق حالة الطوارئ');
  setTimeout(function(){ location.reload(); }, 1000);
}

// ── LOAD ALL APPOINTMENTS ──
async function loadAllAppts(page) {
  var c = document.getElementById('all-container');
  c.innerHTML = '<div style="text-align:center;padding:32px;color:var(--tm)">⏳ جارٍ التحميل...</div>';
  try {
    var res = await fetch('../api/index.php?action=get_appointments&type=all&page='+(page||1));
    var data = await res.json();
    if (!data.appointments || !data.appointments.length) {
      c.innerHTML = '<div class="empty"><div class="empty-icon">📋</div><p>لا توجد مواعيد</p></div>';
      return;
    }
    c.innerHTML = '';
    var statusMap = {pending:'⏳ انتظار',confirmed:'✅ مؤكد',in_progress:'🔄 جارٍ',completed:'✔️ مكتمل',cancelled:'❌ ملغى',rejected:'🚫 مرفوض'};
    data.appointments.forEach(function(a) {
      var el = document.createElement('div');
      el.className = 'appt-card';
      el.innerHTML = '<div class="appt-top">'
        +'<div class="appt-time-blk"><div class="atb-time" style="font-size:11px;">'+a.scheduled_at.slice(0,16).replace('T',' ')+'</div></div>'
        +'<div class="appt-info"><div class="appt-name">'+(a.other_name||'—')+'</div>'
        +'<div class="appt-sub">'+(a.pet_name||'—')+' · '+(parseInt(a.fee||0)).toLocaleString()+' دج</div></div>'
        +'<span class="status-pill sp-'+a.status+'">'+(statusMap[a.status]||a.status)+'</span>'
        +'</div></div>';
      c.appendChild(el);
    });
  } catch(e) {
    c.innerHTML = '<div class="empty"><div class="empty-icon">⚠️</div><p>خطأ في التحميل</p></div>';
  }
}

// ── HELPERS ──
function callClient(phone) {
  window.location.href = 'tel:+213'+phone.replace(/^0/,'');
}
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>
