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

$pet_id = sanitize_int($_GET['pet_id'] ?? 0);
$herd_id = sanitize_int($_GET['herd_id'] ?? 0);

// Load pet info
$pet = null;
if ($pet_id) {
    $stmt = db()->prepare("SELECT * FROM baitari_pets WHERE id=:id AND owner_id=:uid");
    $stmt->execute([':id'=>$pet_id,':uid'=>$uid]);
    $pet = $stmt->fetch();
}

// Load medical records
$records = [];
if ($pet_id) {
    $stmt = db()->prepare(
        "SELECT mr.*, u.name as vet_name
         FROM baitari_medical_records mr
         JOIN baitari_users u ON u.id=mr.vet_id
         WHERE mr.pet_id=:pid
         ORDER BY mr.record_date DESC"
    );
    $stmt->execute([':pid'=>$pet_id]);
    $records = $stmt->fetchAll();
}

// Load vaccinations
$vaccinations = [];
if ($pet_id) {
    $stmt = db()->prepare("SELECT * FROM baitari_vaccinations WHERE pet_id=:pid ORDER BY given_date DESC");
    $stmt->execute([':pid'=>$pet_id]);
    $vaccinations = $stmt->fetchAll();
}

// Load all user pets for sidebar
$pets = db()->prepare("SELECT * FROM baitari_pets WHERE owner_id=:uid AND is_active=1 ORDER BY name");
$pets->execute([':uid'=>$uid]);
$allPets = $pets->fetchAll();

$speciesEmoji = ['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;--r5:#ef4444;--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);--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;}

.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-back{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;flex-shrink:0;}
.nav-back:hover{background:var(--br);}
.nav-title{font-size:17px;font-weight:800;flex:1;}

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

/* PET SELECTOR */
.pet-scroll{display:flex;gap:10px;padding:14px 16px;overflow-x:auto;scrollbar-width:none;background:var(--cd);border-bottom:1px solid var(--br);}
.pet-scroll::-webkit-scrollbar{display:none;}
.pet-chip{flex:0 0 auto;display:flex;align-items:center;gap:8px;padding:8px 14px;border-radius:20px;border:1.5px solid var(--br);background:var(--inp);cursor:pointer;transition:var(--tr);font-size:13px;font-weight:700;color:var(--ts);}
.pet-chip:hover{border-color:var(--g4);}
.pet-chip.on{border-color:var(--g6);background:var(--g6);color:#fff;}
.pet-chip .pc-emoji{font-size:18px;}

/* PET PROFILE CARD */
.pet-profile{background:linear-gradient(135deg,var(--g7),var(--g5));margin:16px;border-radius:20px;padding:20px;display:flex;align-items:center;gap:16px;box-shadow:0 4px 20px rgba(26,127,90,.25);}
.pp-avatar{width:68px;height:68px;border-radius:18px;background:rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;font-size:36px;border:2px solid rgba(255,255,255,.3);flex-shrink:0;}
.pp-info{flex:1;}
.pp-name{font-size:22px;font-weight:900;color:#fff;}
.pp-sub{font-size:13px;color:rgba(255,255,255,.8);margin-top:3px;}
.pp-badges{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap;}
.pp-badge{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:800;background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.3);}
.pp-badge.vacc{background:rgba(34,197,94,.3);border-color:rgba(34,197,94,.5);}
.pp-badge.no-vacc{background:rgba(239,68,68,.3);border-color:rgba(239,68,68,.5);}

/* TABS */
.tab-row{display:flex;background:var(--cd);border-bottom:1px solid var(--br);padding:0 16px;}
.tab-btn{flex:1;padding:12px 4px;border:none;background:none;font-size:14px;font-weight:700;color:var(--tm);cursor:pointer;position:relative;}
.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;}

.sec{margin:16px 16px 0;}
.sec-title{font-size:16px;font-weight:800;margin-bottom:12px;}

/* TIMELINE */
.timeline{position:relative;}
.timeline::before{content:'';position:absolute;right:22px;top:0;bottom:0;width:2px;background:var(--br);}
[dir=ltr] .timeline::before{right:auto;left:22px;}

.tl-item{display:flex;gap:16px;margin-bottom:20px;position:relative;}
.tl-dot{width:14px;height:14px;border-radius:50%;background:var(--g5);border:2px solid var(--cd);box-shadow:0 0 0 2px var(--g4);flex-shrink:0;margin-top:14px;position:relative;z-index:1;}
.tl-dot.emg{background:var(--r5);box-shadow:0 0 0 2px rgba(239,68,68,.4);}
.tl-dot.vacc{background:var(--b5);box-shadow:0 0 0 2px rgba(59,130,246,.4);}

.tl-card{flex:1;background:var(--cd);border-radius:var(--r2);border:1px solid var(--br);padding:14px;box-shadow:var(--sh);}
.tl-header{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:8px;}
.tl-date{font-size:12px;color:var(--tm);font-weight:700;}
.tl-type{font-size:11px;padding:3px 8px;border-radius:20px;font-weight:800;}
.tl-type.visit{background:var(--g5);color:#fff;}
.tl-type.vacc{background:#dbeafe;color:#1d4ed8;}
.tl-type.emg{background:#fee2e2;color:#991b1b;}
.tl-vet{font-size:14px;font-weight:800;margin-bottom:6px;}
.tl-field{margin-bottom:6px;}
.tl-field-label{font-size:11px;font-weight:700;color:var(--tm);margin-bottom:2px;}
.tl-field-val{font-size:13px;color:var(--ts);line-height:1.5;}
.tl-next{margin-top:8px;padding:8px 10px;background:var(--inp);border-radius:8px;font-size:12px;color:var(--g6);font-weight:700;}

/* VACCINATION TABLE */
.vacc-table{background:var(--cd);border-radius:var(--r2);border:1px solid var(--br);overflow:hidden;box-shadow:var(--sh);}
.vt-header{display:grid;grid-template-columns:1fr 90px 90px;background:var(--inp);padding:10px 14px;font-size:12px;font-weight:700;color:var(--tm);}
.vt-row{display:grid;grid-template-columns:1fr 90px 90px;padding:12px 14px;border-top:1px solid var(--br);align-items:center;}
.vt-row:hover{background:var(--inp);}
.vt-name{font-size:14px;font-weight:700;}
.vt-date{font-size:12px;color:var(--ts);}
.vt-due{font-size:12px;font-weight:700;}
.vt-due.ok{color:var(--g6);}
.vt-due.overdue{color:var(--r5);}
.vt-due.soon{color:var(--a5);}

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

.toast{position:fixed;bottom:24px;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;}
</style>
</head>
<body>
<div class="toast" id="toast"><span id="ti">✅</span><span id="tm2"></span></div>

<div class="page-wrap">
  <!-- NAV -->
  <nav class="topnav">
    <button class="nav-back" onclick="history.back()">←</button>
    <div class="nav-title">📋 السجل الطبي</div>
  </nav>

  <!-- PET SELECTOR -->
  <?php if (!empty($allPets)): ?>
  <div class="pet-scroll">
    <?php foreach ($allPets as $p):
      $emoji = $speciesEmoji[$p['species']] ?? '🐾';
      $active = ($p['id'] == $pet_id) ? 'on' : '';
    ?>
    <div class="pet-chip <?= $active ?>" onclick="window.location.href='pet-history.php?pet_id=<?= $p['id'] ?>'">
      <span class="pc-emoji"><?= $emoji ?></span>
      <?= h($p['name']) ?>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <?php if (!$pet && empty($allPets)): ?>
  <div class="empty" style="margin-top:40px;">
    <div class="empty-icon">🐾</div>
    <p>لم تضف أي حيوانات بعد</p>
    <button onclick="window.location.href='../index.php'" style="margin-top:16px;background:var(--g6);color:#fff;border-radius:20px;padding:10px 20px;font-size:14px;font-weight:800;">
      ➕ إضافة حيوان
    </button>
  </div>

  <?php elseif (!$pet): ?>
  <div class="empty" style="margin-top:40px;">
    <div class="empty-icon">👆</div>
    <p>اختر حيواناً من القائمة أعلاه</p>
  </div>

  <?php else: ?>
  <!-- PET PROFILE -->
  <div class="pet-profile">
    <?php $age = $pet['birth_date'] ? floor((time()-strtotime($pet['birth_date']))/31536000).' سنة' : '—'; ?>
    <div class="pp-avatar"><?= $speciesEmoji[$pet['species']] ?? '🐾' ?></div>
    <div class="pp-info">
      <div class="pp-name"><?= h($pet['name']) ?></div>
      <div class="pp-sub"><?= h($pet['breed'] ?? '—') ?> · <?= $age ?><?= $pet['weight_kg'] ? ' · '.$pet['weight_kg'].' كغ' : '' ?></div>
      <div class="pp-badges">
        <span class="pp-badge"><?= ['cat'=>'قط','dog'=>'كلب','horse'=>'حصان','cow'=>'بقرة','sheep'=>'خروف','bird'=>'طائر','rabbit'=>'أرنب','other'=>'أخرى'][$pet['species']] ?? $pet['species'] ?></span>
        <span class="pp-badge <?= $pet['is_vaccinated'] ? 'vacc' : 'no-vacc' ?>">
          <?= $pet['is_vaccinated'] ? '💉 ملقّح' : '⚠️ غير ملقّح' ?>
        </span>
      </div>
    </div>
  </div>

  <!-- TABS -->
  <div class="tab-row">
    <button class="tab-btn on" id="tab-history" onclick="switchTab('history')">📋 الزيارات (<?= count($records) ?>)</button>
    <button class="tab-btn" id="tab-vacc" onclick="switchTab('vacc')">💉 التطعيمات (<?= count($vaccinations) ?>)</button>
  </div>

  <!-- HISTORY TAB -->
  <div id="view-history" class="sec">
    <?php if (empty($records)): ?>
    <div class="empty"><div class="empty-icon">📋</div><p>لا توجد زيارات مسجلة لـ<?= h($pet['name']) ?> بعد</p></div>
    <?php else: ?>
    <div class="timeline">
      <?php foreach ($records as $r):
        $dateStr = date('d/m/Y', strtotime($r['record_date']));
        $isEmg   = false; // could detect by visit_reason
        $dotClass = '';
      ?>
      <div class="tl-item">
        <div class="tl-dot <?= $dotClass ?>"></div>
        <div class="tl-card">
          <div class="tl-header">
            <div class="tl-date">📅 <?= $dateStr ?></div>
            <span class="tl-type visit">كشف طبي</span>
          </div>
          <div class="tl-vet">🩺 <?= h($r['vet_name']) ?></div>
          <?php if ($r['visit_reason']): ?>
          <div class="tl-field">
            <div class="tl-field-label">سبب الزيارة</div>
            <div class="tl-field-val"><?= h($r['visit_reason']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($r['diagnosis']): ?>
          <div class="tl-field">
            <div class="tl-field-label">التشخيص</div>
            <div class="tl-field-val"><?= h($r['diagnosis']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($r['treatment']): ?>
          <div class="tl-field">
            <div class="tl-field-label">العلاج</div>
            <div class="tl-field-val"><?= h($r['treatment']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($r['prescription']): ?>
          <div class="tl-field">
            <div class="tl-field-label">💊 الوصفة</div>
            <div class="tl-field-val" style="background:var(--inp);padding:8px;border-radius:8px;"><?= h($r['prescription']) ?></div>
          </div>
          <?php endif; ?>
          <?php if ($r['next_visit']): ?>
          <div class="tl-next">📅 الموعد القادم: <?= date('d/m/Y', strtotime($r['next_visit'])) ?></div>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </div>

  <!-- VACCINATIONS TAB -->
  <div id="view-vacc" class="sec" style="display:none;">
    <?php if (empty($vaccinations)): ?>
    <div class="empty"><div class="empty-icon">💉</div><p>لا توجد تطعيمات مسجلة</p></div>
    <?php else: ?>
    <div class="vacc-table">
      <div class="vt-header">
        <span>اللقاح</span>
        <span>تاريخ الإعطاء</span>
        <span>الموعد القادم</span>
      </div>
      <?php foreach ($vaccinations as $v):
        $nextDue = $v['next_due'] ? date('d/m/Y', strtotime($v['next_due'])) : '—';
        $dueClass = '';
        $daysLeft = 9999;
        if ($v['next_due']) {
          $daysLeft = (strtotime($v['next_due']) - time()) / 86400;
          if ($daysLeft < 0)  $dueClass = 'overdue';
          elseif ($daysLeft < 30) $dueClass = 'soon';
          else $dueClass = 'ok';
        }
      ?>
      <div class="vt-row">
        <div>
          <div class="vt-name">💉 <?= h($v['vaccine_name']) ?></div>
          <?php if ($v['batch_no']): ?><div class="vt-date">دفعة: <?= h($v['batch_no']) ?></div><?php endif; ?>
        </div>
        <div class="vt-date"><?= date('d/m/Y', strtotime($v['given_date'])) ?></div>
        <div class="vt-due <?= $dueClass ?>">
          <?php if ($dueClass === 'overdue'): ?>⚠️ متأخر
          <?php elseif ($dueClass === 'soon'): ?>🔔 قريباً
          <?php else: ?><?= $nextDue ?>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- Next due reminder -->
    <?php
    $overdue = array_filter($vaccinations, function($v){ return $v['next_due'] && strtotime($v['next_due']) < time(); });
    if (!empty($overdue)):
    ?>
    <div style="margin-top:14px;background:rgba(239,68,68,.08);border:1.5px solid #fca5a5;border-radius:var(--r2);padding:14px;">
      <div style="font-size:14px;font-weight:800;color:var(--r6);margin-bottom:8px;">⚠️ تطعيمات متأخرة</div>
      <?php foreach ($overdue as $v): ?>
      <div style="font-size:13px;color:var(--ts);margin-bottom:4px;">
        • <?= h($v['vaccine_name']) ?> — كان موعده <?= date('d/m/Y', strtotime($v['next_due'])) ?>
      </div>
      <?php endforeach; ?>
      <button onclick="window.location.href='../index.php'" style="margin-top:10px;background:var(--g6);color:#fff;border-radius:20px;padding:8px 18px;font-size:13px;font-weight:800;border:none;cursor:pointer;">
        📅 احجز طبيباً الآن
      </button>
    </div>
    <?php endif; ?>
  </div>

  <?php endif; ?>

</div>

<script>
function switchTab(name) {
  document.getElementById('view-history').style.display = name==='history' ? '' : 'none';
  document.getElementById('view-vacc').style.display    = name==='vacc' ? '' : 'none';
  document.getElementById('tab-history').classList.toggle('on', name==='history');
  document.getElementById('tab-vacc').classList.toggle('on', name==='vacc');
}
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>
