<?php
require_once __DIR__ . '/../includes/config.php';
session_start_secure();

// Must be logged in as vet
$user = current_user();
if (!$user) { header('Location: ../login.php'); exit; }
if ($user['role'] !== 'vet') { header('Location: ../index.php'); exit; }

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

// Fetch vet profile + documents
$profile = db()->prepare(
    "SELECT vp.*, COUNT(vd.id) as doc_count
     FROM baitari_vet_profiles vp
     LEFT JOIN baitari_vet_documents vd ON vd.vet_id = vp.vet_id
     WHERE vp.vet_id = :uid
     GROUP BY vp.id"
);
$profile->execute([':uid' => $uid]);
$vp = $profile->fetch();

// If no profile yet, create it
if (!$vp) {
    db()->prepare(
        "INSERT INTO baitari_vet_profiles (vet_id, license_no, verification_status)
         VALUES (:uid, 'PENDING', 'pending_docs')"
    )->execute([':uid' => $uid]);
    $vp = ['verification_status' => 'pending_docs', 'doc_count' => 0,
            'rejection_reason' => null, 'license_no' => ''];
}

$status   = $vp['verification_status'] ?? 'pending_docs';
$docCount = (int)($vp['doc_count'] ?? 0);

// Fetch uploaded documents
$docs = db()->prepare(
    "SELECT * FROM baitari_vet_documents WHERE vet_id = :uid ORDER BY uploaded_at DESC"
);
$docs->execute([':uid' => $uid]);
$uploadedDocs = $docs->fetchAll();

// Required document types
$requiredDocs = [
    'national_id'       => ['label' => 'بطاقة التعريف الوطنية',     'icon' => '🪪', 'required' => true],
    'diploma'           => ['label' => 'شهادة الدكتوراه في البيطرة', 'icon' => '🎓', 'required' => true],
    'license'           => ['label' => 'ترخيص مزاولة المهنة',        'icon' => '📋', 'required' => true],
    'professional_card' => ['label' => 'بطاقة الطبيب المهنية',       'icon' => '🩺', 'required' => false],
];

// Map uploaded docs by type
$uploadedByType = [];
foreach ($uploadedDocs as $d) {
    $uploadedByType[$d['doc_type']] = $d;
}

$requiredCount  = count(array_filter($requiredDocs, fn($d) => $d['required']));
$uploadedRequired = count(array_filter(array_keys($uploadedByType), fn($k) => $requiredDocs[$k]['required'] ?? false));
$canSubmit = ($uploadedRequired >= $requiredCount);
?>
<!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@300;400;500;700;800;900&display=swap" rel="stylesheet">
<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-500:#3b82f6;--blue-600:#2563eb;
  --amber-50:#fffbeb;--amber-400:#fbbf24;--amber-500:#f59e0b;--amber-600:#d97706;
  --red-50:#fff5f5;--red-400:#f87171;--red-500:#ef4444;--red-600:#dc2626;
  --purple-50:#faf5ff;--purple-500:#8b5cf6;
  --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);
}
[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;--green-100:#112918;--blue-50:#0a1220;
  --amber-50:#1a1200;--red-50:#1a0808;--purple-50:#110a1f;
}
*,*::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;}
img{max-width:100%;display:block;}

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

/* ── HEADER ── */
.page-header{
  background:linear-gradient(135deg,var(--green-700),var(--green-500) 60%,var(--blue-500));
  padding:32px 20px 28px;text-align:center;position:relative;overflow:hidden;
}
.page-header::before{content:'';position:absolute;top:-40px;right:-40px;width:160px;height:160px;background:rgba(255,255,255,.06);border-radius:50%;}
.page-header::after{content:'';position:absolute;bottom:-60px;left:-30px;width:200px;height:200px;background:rgba(255,255,255,.04);border-radius:50%;}
.header-icon{font-size:48px;margin-bottom:12px;position:relative;z-index:1;}
.header-title{font-size:24px;font-weight:900;color:#fff;position:relative;z-index:1;}
.header-sub{font-size:14px;color:rgba(255,255,255,.8);margin-top:6px;position:relative;z-index:1;}

/* ── STATUS BANNER ── */
.status-banner{
  margin:20px 16px 0;
  border-radius:var(--radius-md);
  padding:18px 20px;
  display:flex;align-items:flex-start;gap:14px;
  border:1.5px solid;
}
.status-banner.pending_docs  {background:var(--amber-50);border-color:var(--amber-400);}
.status-banner.docs_submitted{background:var(--blue-50); border-color:var(--blue-500);}
.status-banner.under_review  {background:var(--purple-50);border-color:var(--purple-500);}
.status-banner.approved      {background:var(--green-50); border-color:var(--green-400);}
.status-banner.rejected      {background:var(--red-50);   border-color:var(--red-400);}
.status-banner.suspended     {background:var(--red-50);   border-color:var(--red-600);}

.sb-icon{font-size:28px;flex-shrink:0;margin-top:2px;}
.sb-content{flex:1;}
.sb-title{font-size:16px;font-weight:800;margin-bottom:4px;}
.sb-title.pending_docs  {color:var(--amber-600);}
.sb-title.docs_submitted{color:var(--blue-600);}
.sb-title.under_review  {color:var(--purple-500);}
.sb-title.approved      {color:var(--green-700);}
.sb-title.rejected      {color:var(--red-600);}
.sb-desc{font-size:13px;color:var(--text-sec);line-height:1.6;}
.sb-reason{
  margin-top:10px;padding:10px 12px;
  background:rgba(239,68,68,.1);border-radius:8px;
  font-size:13px;color:var(--red-600);font-weight:600;
  border-right:3px solid var(--red-500);
}

/* ── PROGRESS STEPS ── */
.steps-wrap{padding:24px 16px 0;}
.steps-row{
  display:flex;align-items:center;
  margin-bottom:32px;
}
.step-item{
  flex:1;display:flex;flex-direction:column;align-items:center;gap:6px;
  position:relative;
}
.step-item:not(:last-child)::after{
  content:'';position:absolute;
  top:18px;left:calc(50% + 20px);right:calc(-50% + 20px);
  height:2px;background:var(--border);
  transition:var(--transition);
}
.step-item.done:not(:last-child)::after{background:var(--green-400);}
.step-circle{
  width:36px;height:36px;border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  font-size:16px;font-weight:800;
  border:2px solid var(--border);
  background:var(--bg-card);
  color:var(--text-muted);
  transition:var(--transition);
  position:relative;z-index:1;
}
.step-item.done .step-circle{background:var(--green-500);border-color:var(--green-500);color:#fff;}
.step-item.active .step-circle{background:var(--green-600);border-color:var(--green-600);color:#fff;box-shadow:0 0 0 4px rgba(26,127,90,.2);}
.step-label{font-size:11px;font-weight:700;color:var(--text-muted);text-align:center;}
.step-item.done .step-label,.step-item.active .step-label{color:var(--green-700);}

/* ── SECTION ── */
.section{padding:0 16px;margin-top:24px;}
.section-title{font-size:17px;font-weight:800;margin-bottom:14px;color:var(--text-primary);}
.section-sub{font-size:13px;color:var(--text-sec);margin-bottom:16px;line-height:1.6;}

/* ── DOC CARDS ── */
.doc-card{
  background:var(--bg-card);
  border:1.5px solid var(--border);
  border-radius:var(--radius-md);
  padding:16px;
  margin-bottom:10px;
  transition:var(--transition);
}
.doc-card.uploaded{border-color:var(--green-400);}
.doc-card.rejected-doc{border-color:var(--red-400);}

.doc-top{display:flex;align-items:center;gap:12px;}
.doc-icon-wrap{
  width:48px;height:48px;border-radius:14px;
  display:flex;align-items:center;justify-content:center;
  font-size:24px;flex-shrink:0;
  background:var(--bg-input);
}
.doc-card.uploaded .doc-icon-wrap{background:var(--green-50);}
.doc-info{flex:1;min-width:0;}
.doc-name{font-size:15px;font-weight:800;color:var(--text-primary);}
.doc-required{
  font-size:11px;font-weight:700;
  padding:2px 8px;border-radius:20px;margin-top:3px;display:inline-block;
}
.doc-required.req{background:var(--red-50);color:var(--red-600);}
.doc-required.opt{background:var(--bg-input);color:var(--text-muted);}
.doc-status{flex-shrink:0;}
.doc-badge{
  display:flex;align-items:center;gap:4px;
  padding:5px 12px;border-radius:20px;
  font-size:12px;font-weight:700;
}
.doc-badge.uploaded{background:var(--green-50);color:var(--green-700);}
.doc-badge.missing{background:var(--amber-50);color:var(--amber-600);}

/* Uploaded file info */
.doc-file-info{
  margin-top:10px;padding:10px 12px;
  background:var(--bg-input);border-radius:8px;
  display:flex;align-items:center;gap:8px;
}
.dfi-name{font-size:12px;font-weight:700;color:var(--text-sec);flex:1;
  white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.dfi-size{font-size:11px;color:var(--text-muted);}
.dfi-actions{display:flex;gap:6px;}
.dfi-btn{
  padding:4px 10px;border-radius:6px;font-size:11px;font-weight:700;
  cursor:pointer;transition:var(--transition);
}
.dfi-btn-view{background:var(--blue-50);color:var(--blue-600);border:1px solid #bfdbfe;}
.dfi-btn-del{background:var(--red-50);color:var(--red-600);border:1px solid #fecaca;}
.dfi-btn-del:hover{background:#fee2e2;}

/* Upload zone */
.upload-zone{
  margin-top:10px;border:2px dashed var(--border);
  border-radius:var(--radius-sm);padding:18px;
  text-align:center;cursor:pointer;transition:var(--transition);
  background:var(--bg-input);
}
.upload-zone:hover,.upload-zone.drag-over{
  border-color:var(--green-400);background:var(--green-50);
}
.upload-zone input[type="file"]{display:none;}
.uz-icon{font-size:28px;margin-bottom:6px;}
.uz-text{font-size:13px;color:var(--text-sec);font-weight:600;}
.uz-sub{font-size:11px;color:var(--text-muted);margin-top:3px;}

/* Upload progress bar */
.upload-progress{
  display:none;margin-top:10px;
  background:var(--bg-input);border-radius:8px;padding:10px 12px;
}
.up-label{font-size:12px;font-weight:700;color:var(--text-sec);margin-bottom:6px;}
.up-track{height:6px;background:var(--border);border-radius:3px;overflow:hidden;}
.up-fill{height:100%;background:var(--green-500);border-radius:3px;width:0%;transition:width .3s;}

/* ── LICENSE FIELD ── */
.form-group{margin-bottom:14px;}
.form-label{font-size:13px;font-weight:700;color:var(--text-sec);margin-bottom:6px;display:block;}
.form-input{
  width:100%;background:var(--bg-input);border:1.5px solid var(--border);
  border-radius:var(--radius-sm);padding:12px 14px;
  font-size:15px;color:var(--text-primary);
  font-family:'Tajawal',sans-serif;transition:var(--transition);outline:none;
}
.form-input:focus{border-color:var(--green-500);background:var(--bg-card);box-shadow:0 0 0 3px rgba(26,159,106,.1);}

/* ── PROGRESS SUMMARY ── */
.progress-summary{
  background:var(--bg-card);border:1px solid var(--border);
  border-radius:var(--radius-md);padding:16px;margin:0 16px;
}
.ps-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;}
.ps-title{font-size:14px;font-weight:800;}
.ps-pct{font-size:18px;font-weight:900;color:var(--green-600);}
.ps-track{height:8px;background:var(--border);border-radius:4px;overflow:hidden;}
.ps-fill{height:100%;background:linear-gradient(90deg,var(--green-500),var(--green-400));border-radius:4px;transition:width .5s ease;}
.ps-note{font-size:12px;color:var(--text-muted);margin-top:8px;}

/* ── SUBMIT BUTTON ── */
.submit-wrap{padding:24px 16px 0;}
.btn-submit{
  width:100%;
  background:linear-gradient(135deg,var(--green-700),var(--green-500));
  color:#fff;border-radius:var(--radius-sm);
  padding:16px;font-size:17px;font-weight:800;
  text-align:center;transition:var(--transition);
  box-shadow:0 4px 20px rgba(26,127,90,.3);
  display:flex;align-items:center;justify-content:center;gap:10px;
}
.btn-submit:hover{opacity:.92;transform:translateY(-1px);}
.btn-submit:disabled{opacity:.5;pointer-events:none;background:var(--border);}
.btn-submit .spinner{
  width:20px;height:20px;border:2px solid rgba(255,255,255,.4);
  border-top-color:#fff;border-radius:50%;
  animation:spin .7s linear infinite;display:none;
}
@keyframes spin{to{transform:rotate(360deg);}}

.btn-secondary{
  width:100%;margin-top:10px;
  background:var(--bg-input);color:var(--text-sec);
  border:1.5px solid var(--border);border-radius:var(--radius-sm);
  padding:13px;font-size:15px;font-weight:700;
  text-align:center;transition:var(--transition);
}
.btn-secondary:hover{background:var(--border);}

/* ── APPROVED STATE ── */
.approved-card{
  margin:20px 16px;
  background:linear-gradient(135deg,var(--green-700),var(--green-500));
  border-radius:var(--radius-lg);padding:32px 24px;
  text-align:center;color:#fff;
}
.ac-icon{font-size:56px;margin-bottom:16px;}
.ac-title{font-size:22px;font-weight:900;margin-bottom:8px;}
.ac-sub{font-size:14px;color:rgba(255,255,255,.85);line-height:1.6;}
.btn-go-dashboard{
  margin-top:20px;
  display:inline-flex;align-items:center;gap:8px;
  background:rgba(255,255,255,.2);border:2px solid rgba(255,255,255,.4);
  border-radius:var(--radius-sm);padding:12px 28px;
  font-size:16px;font-weight:800;color:#fff;cursor:pointer;
  transition:var(--transition);
}
.btn-go-dashboard:hover{background:rgba(255,255,255,.3);}

/* ── INFO BOXES ── */
.info-box{
  margin:16px 16px 0;
  background:var(--blue-50);border:1px solid #bfdbfe;
  border-radius:var(--radius-sm);padding:14px 16px;
  display:flex;gap:10px;
}
.info-box .ib-icon{font-size:18px;flex-shrink:0;}
.info-box p{font-size:13px;color:var(--blue-600);line-height:1.6;font-weight:500;}

/* Toast */
#toast{
  position:fixed;top:16px;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;}

/* Logout bar */
.top-bar{
  background:var(--bg-card);border-bottom:1px solid var(--border);
  padding:12px 16px;display:flex;align-items:center;gap:12px;
}
.tb-logo{display:flex;align-items:center;gap:8px;}
.tb-logo-mark{width:32px;height:32px;background:linear-gradient(135deg,var(--green-600),var(--green-400));border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;}
.tb-app-name{font-size:18px;font-weight:900;color:var(--green-700);}
.tb-logout{margin-right:auto;font-size:13px;color:var(--text-muted);font-weight:700;cursor:pointer;padding:6px 12px;border-radius:8px;transition:var(--transition);}
.tb-logout:hover{background:var(--red-50);color:var(--red-600);}
</style>
</head>
<body>

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

<!-- TOP BAR -->
<div class="top-bar">
  <div class="tb-logo">
    <div class="tb-logo-mark">🐾</div>
    <div class="tb-app-name">بيطري</div>
  </div>
  <span style="font-size:13px;color:var(--text-sec);font-weight:600;">
    👨‍⚕️ <?= h($user['name']) ?>
  </span>
  <button class="tb-logout" onclick="logout()">تسجيل الخروج</button>
</div>

<div class="page-wrap">

  <?php if ($status === 'approved'): ?>
  <!-- ══ APPROVED — Go to dashboard ══ -->
  <div class="approved-card">
    <div class="ac-icon">🎉</div>
    <div class="ac-title">تم اعتماد حسابك!</div>
    <div class="ac-sub">
      مرحباً د. <?= h($user['name']) ?>، تم التحقق من وثائقك وأصبح بإمكانك استقبال المواعيد والعمل على المنصة.
    </div>
    <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;margin-top:20px;">
      <button class="btn-go-dashboard" onclick="window.location.href='../index.php'">
        🏠 الصفحة الرئيسية
      </button>
      <button class="btn-go-dashboard" onclick="window.location.href='vet-clinic-setup.php'"
        style="background:rgba(255,255,255,.15);">
        🏥 إعداد العيادة
      </button>
    </div>
  </div>

  <?php elseif ($status === 'rejected'): ?>
  <!-- ══ REJECTED — Re-upload ══ -->
  <div class="page-header">
    <div class="header-icon">📋</div>
    <div class="header-title">توثيق الحساب البيطري</div>
    <div class="header-sub">أرسل وثائقك لاعتماد حسابك</div>
  </div>

  <div class="status-banner rejected">
    <div class="sb-icon">❌</div>
    <div class="sb-content">
      <div class="sb-title rejected">تم رفض طلبك</div>
      <div class="sb-desc">يرجى مراجعة السبب وإعادة رفع الوثائق المطلوبة.</div>
      <?php if ($vp['rejection_reason']): ?>
      <div class="sb-reason">📌 سبب الرفض: <?= h($vp['rejection_reason']) ?></div>
      <?php endif; ?>
    </div>
  </div>
  <?php include __DIR__ . '/vet-docs-form.partial.php'; ?>

  <?php elseif ($status === 'under_review' || $status === 'docs_submitted'): ?>
  <!-- ══ UNDER REVIEW ══ -->
  <div class="page-header">
    <div class="header-icon">⏳</div>
    <div class="header-title">جارٍ مراجعة وثائقك</div>
    <div class="header-sub">فريق بيطري يراجع ملفك حالياً</div>
  </div>

  <div class="status-banner under_review">
    <div class="sb-icon">🔍</div>
    <div class="sb-content">
      <div class="sb-title under_review">
        <?= $status === 'docs_submitted' ? 'تم إرسال الوثائق' : 'قيد المراجعة' ?>
      </div>
      <div class="sb-desc">
        تم استلام وثائقك بنجاح. سيقوم فريقنا بمراجعتها خلال <strong>24–48 ساعة</strong>.
        ستصلك إشعار فور الانتهاء.
      </div>
    </div>
  </div>

  <div class="info-box" style="margin-top:20px;">
    <span class="ib-icon">💡</span>
    <p>في حال مرور أكثر من 48 ساعة دون رد، يمكنك التواصل معنا عبر <strong>Facebook</strong> أو <strong>البريد الإلكتروني</strong>.</p>
  </div>

  <!-- Show submitted docs summary -->
  <div class="section" style="margin-top:24px;">
    <div class="section-title">الوثائق المُرسَلة</div>
    <?php foreach ($requiredDocs as $type => $doc): ?>
    <div class="doc-card <?= isset($uploadedByType[$type]) ? 'uploaded' : '' ?>">
      <div class="doc-top">
        <div class="doc-icon-wrap"><?= $doc['icon'] ?></div>
        <div class="doc-info">
          <div class="doc-name"><?= $doc['label'] ?></div>
          <span class="doc-required <?= $doc['required'] ? 'req' : 'opt' ?>">
            <?= $doc['required'] ? 'إلزامي' : 'اختياري' ?>
          </span>
        </div>
        <div class="doc-status">
          <?php if (isset($uploadedByType[$type])): ?>
          <div class="doc-badge uploaded">✅ تم الرفع</div>
          <?php else: ?>
          <div class="doc-badge missing">⬜ لم يُرفع</div>
          <?php endif; ?>
        </div>
      </div>
      <?php if (isset($uploadedByType[$type])): ?>
      <div class="doc-file-info">
        <span style="font-size:16px;">📄</span>
        <span class="dfi-name"><?= h($uploadedByType[$type]['file_name']) ?></span>
        <span class="dfi-size"><?= round($uploadedByType[$type]['file_size']/1024) ?> KB</span>
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>

  <?php else: ?>
  <!-- ══ PENDING DOCS — Main upload form ══ -->
  <div class="page-header">
    <div class="header-icon">📋</div>
    <div class="header-title">توثيق الحساب البيطري</div>
    <div class="header-sub">أرسل وثائقك لاعتماد حسابك والبدء في استقبال المواعيد</div>
  </div>

  <!-- Status Banner -->
  <div class="status-banner pending_docs">
    <div class="sb-icon">⚠️</div>
    <div class="sb-content">
      <div class="sb-title pending_docs">حسابك بانتظار التوثيق</div>
      <div class="sb-desc">
        لا يمكنك استقبال المواعيد أو الظهور في نتائج البحث حتى يتم التحقق من هويتك ووثائقك المهنية.
      </div>
    </div>
  </div>

  <!-- Steps -->
  <div class="steps-wrap">
    <div class="steps-row">
      <?php
      $steps = [
        ['label'=>'إنشاء الحساب', 'done'=>true],
        ['label'=>'رفع الوثائق',  'done'=>$docCount>0, 'active'=>$docCount===0],
        ['label'=>'المراجعة',     'done'=>false, 'active'=>$docCount>0],
        ['label'=>'الاعتماد',     'done'=>false],
      ];
      foreach ($steps as $s):
        $cls = $s['done'] ? 'done' : (($s['active']??false) ? 'active' : '');
      ?>
      <div class="step-item <?= $cls ?>">
        <div class="step-circle"><?= $s['done'] ? '✓' : '' ?></div>
        <div class="step-label"><?= $s['label'] ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Progress summary -->
  <?php $pct = min(100, round(($uploadedRequired / $requiredCount) * 100)); ?>
  <div class="progress-summary">
    <div class="ps-header">
      <div class="ps-title">تقدّم رفع الوثائق</div>
      <div class="ps-pct"><?= $pct ?>%</div>
    </div>
    <div class="ps-track">
      <div class="ps-fill" style="width:<?= $pct ?>%"></div>
    </div>
    <div class="ps-note">
      <?= $uploadedRequired ?>/<?= $requiredCount ?> وثائق إلزامية مرفوعة
      <?= $canSubmit ? '— ✅ جاهز للإرسال' : '' ?>
    </div>
  </div>

  <!-- Info box -->
  <div class="info-box">
    <span class="ib-icon">🔒</span>
    <p>وثائقك سرية تماماً ولا تُشارك مع أي طرف ثالث. تُستخدم فقط للتحقق من هويتك.</p>
  </div>

  <!-- License number -->
  <div class="section">
    <div class="section-title">رقم ترخيص مزاولة المهنة</div>
    <div class="form-group">
      <label class="form-label">رقم الترخيص <span style="color:var(--red-500);">*</span></label>
      <input type="text" class="form-input" id="license-input"
        value="<?= h($vp['license_no'] !== 'PENDING' ? $vp['license_no'] : '') ?>"
        placeholder="مثال: VET-2024-XXXX"
        oninput="saveLicense(this.value)">
    </div>
  </div>

  <!-- Documents -->
  <div class="section">
    <div class="section-title">الوثائق المطلوبة</div>
    <div class="section-sub">
      ارفع صورة واضحة أو ملف PDF لكل وثيقة. الحجم الأقصى 5MB لكل ملف.
    </div>

    <?php foreach ($requiredDocs as $type => $doc): ?>
    <?php $uploaded = $uploadedByType[$type] ?? null; ?>
    <div class="doc-card <?= $uploaded ? 'uploaded' : '' ?>" id="dc-<?= $type ?>">
      <div class="doc-top">
        <div class="doc-icon-wrap"><?= $doc['icon'] ?></div>
        <div class="doc-info">
          <div class="doc-name"><?= $doc['label'] ?></div>
          <span class="doc-required <?= $doc['required'] ? 'req' : 'opt' ?>">
            <?= $doc['required'] ? '⭐ إلزامي' : 'اختياري' ?>
          </span>
        </div>
        <div class="doc-status">
          <?php if ($uploaded): ?>
          <div class="doc-badge uploaded">✅ مرفوع</div>
          <?php else: ?>
          <div class="doc-badge missing">📎 مطلوب</div>
          <?php endif; ?>
        </div>
      </div>

      <?php if ($uploaded): ?>
      <!-- Already uploaded -->
      <div class="doc-file-info" id="dfi-<?= $type ?>">
        <span style="font-size:16px;">📄</span>
        <span class="dfi-name"><?= h($uploaded['file_name']) ?></span>
        <span class="dfi-size"><?= round($uploaded['file_size']/1024) ?> KB</span>
        <div class="dfi-actions">
          <button class="dfi-btn dfi-btn-view"
            onclick="window.open('../uploads/vet_docs/<?= h($uploaded['file_path']) ?>')">👁 عرض</button>
          <button class="dfi-btn dfi-btn-del"
            onclick="deleteDoc(<?= $uploaded['id'] ?>, '<?= $type ?>')">🗑 حذف</button>
        </div>
      </div>
      <?php else: ?>
      <!-- Upload zone -->
      <div class="upload-zone" id="uz-<?= $type ?>"
        onclick="document.getElementById('fi-<?= $type ?>').click()"
        ondragover="event.preventDefault();this.classList.add('drag-over')"
        ondragleave="this.classList.remove('drag-over')"
        ondrop="handleDrop(event,'<?= $type ?>')">
        <input type="file" id="fi-<?= $type ?>"
          accept=".pdf,.jpg,.jpeg,.png,.webp"
          onchange="uploadDoc('<?= $type ?>',this)">
        <div class="uz-icon">📁</div>
        <div class="uz-text">اسحب الملف هنا أو انقر للاختيار</div>
        <div class="uz-sub">PDF · JPG · PNG · حتى 5 MB</div>
      </div>
      <div class="upload-progress" id="up-<?= $type ?>">
        <div class="up-label">⏳ جارٍ الرفع...</div>
        <div class="up-track"><div class="up-fill" id="upf-<?= $type ?>"></div></div>
      </div>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Submit -->
  <div class="submit-wrap">
    <button class="btn-submit" id="submit-btn"
      <?= $canSubmit ? '' : 'disabled' ?>
      onclick="submitForReview()">
      <span class="spinner" id="submit-spinner"></span>
      <span id="submit-label">
        <?= $canSubmit ? '✅ إرسال للمراجعة' : '⬆️ ارفع الوثائق الإلزامية أولاً' ?>
      </span>
    </button>
    <button class="btn-secondary" onclick="logout()">تسجيل الخروج</button>
  </div>

  <?php endif; ?>

  <div style="height:32px;"></div>
</div>

<script>
const VET_ID = <?= $uid ?>;
const REQUIRED_DOCS = <?= json_encode(array_keys(array_filter($requiredDocs, fn($d) => $d['required']))) ?>;
let uploadedRequired = <?= $uploadedRequired ?>;
let totalRequired = <?= $requiredCount ?>;

// ── UPLOAD DOCUMENT ──
async function uploadDoc(docType, input) {
  const file = input.files[0];
  if (!file) return;

  if (file.size > 5 * 1024 * 1024) {
    showToast('error', 'حجم الملف يتجاوز 5MB');
    input.value = '';
    return;
  }

  const allowed = ['application/pdf','image/jpeg','image/png','image/webp'];
  if (!allowed.includes(file.type)) {
    showToast('error', 'نوع الملف غير مدعوم. استخدم PDF أو صورة.');
    input.value = '';
    return;
  }

  // Show progress
  const upBar = document.getElementById(`up-${docType}`);
  const upFill = document.getElementById(`upf-${docType}`);
  upBar.style.display = 'block';

  // Animate progress
  let prog = 0;
  const interval = setInterval(() => {
    prog = Math.min(prog + Math.random() * 15, 90);
    upFill.style.width = prog + '%';
  }, 150);

  const formData = new FormData();
  formData.append('action', 'upload_doc');
  formData.append('doc_type', docType);
  formData.append('file', file);

  try {
    const res = await fetch('../api/vet_docs.php', {
      method: 'POST',
      body: formData,
    });
    const data = await res.json();

    clearInterval(interval);
    upFill.style.width = '100%';

    setTimeout(() => {
      upBar.style.display = 'none';
      upFill.style.width = '0%';

      if (data.success) {
        showToast('success', 'تم رفع الوثيقة بنجاح ✅');
        // Update UI
        updateDocCard(docType, data.doc);
        if (REQUIRED_DOCS.includes(docType)) {
          uploadedRequired++;
          updateProgress();
        }
      } else {
        showToast('error', data.error || 'فشل الرفع، حاول مجدداً');
      }
    }, 300);
  } catch(e) {
    clearInterval(interval);
    upBar.style.display = 'none';
    showToast('error', 'خطأ في الاتصال بالخادم');
  }
}

function handleDrop(event, docType) {
  event.preventDefault();
  document.getElementById(`uz-${docType}`).classList.remove('drag-over');
  const file = event.dataTransfer.files[0];
  if (!file) return;
  const fakeInput = { files: [file] };
  uploadDoc(docType, fakeInput);
}

// ── UPDATE DOC CARD UI ──
function updateDocCard(docType, doc) {
  const card = document.getElementById(`dc-${docType}`);
  card.classList.add('uploaded');

  const uz = document.getElementById(`uz-${docType}`);
  if (uz) {
    uz.outerHTML = `
      <div class="doc-file-info" id="dfi-${docType}">
        <span style="font-size:16px;">📄</span>
        <span class="dfi-name">${escHtml(doc.file_name)}</span>
        <span class="dfi-size">${Math.round(doc.file_size/1024)} KB</span>
        <div class="dfi-actions">
          <button class="dfi-btn dfi-btn-view" onclick="window.open('../uploads/vet_docs/${escHtml(doc.file_path)}')">👁 عرض</button>
          <button class="dfi-btn dfi-btn-del" onclick="deleteDoc(${doc.id}, '${docType}')">🗑 حذف</button>
        </div>
      </div>`;
  }

  // Update badge
  const badge = card.querySelector('.doc-badge');
  if (badge) { badge.className = 'doc-badge uploaded'; badge.textContent = '✅ مرفوع'; }
}

// ── DELETE DOC ──
async function deleteDoc(docId, docType) {
  if (!confirm('هل تريد حذف هذه الوثيقة؟')) return;

  try {
    const res = await fetch('../api/vet_docs.php', {
      method: 'POST',
      headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ action: 'delete_doc', doc_id: docId }),
    });
    const data = await res.json();
    if (data.success) {
      showToast('info', 'تم حذف الوثيقة');
      location.reload();
    } else {
      showToast('error', data.error || 'فشل الحذف');
    }
  } catch(e) {
    showToast('error', 'خطأ في الاتصال');
  }
}

// ── SAVE LICENSE ──
let licenseTimer;
function saveLicense(val) {
  clearTimeout(licenseTimer);
  licenseTimer = setTimeout(async () => {
    if (!val.trim()) return;
    try {
      await fetch('../api/vet_docs.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: new URLSearchParams({ action: 'save_license', license: val }),
      });
    } catch(e) {}
  }, 800);
}

// ── UPDATE PROGRESS ──
function updateProgress() {
  const pct = Math.min(100, Math.round((uploadedRequired / totalRequired) * 100));
  const fill = document.querySelector('.ps-fill');
  const pctEl = document.querySelector('.ps-pct');
  const noteEl = document.querySelector('.ps-note');
  if (fill) fill.style.width = pct + '%';
  if (pctEl) pctEl.textContent = pct + '%';
  if (noteEl) noteEl.textContent = `${uploadedRequired}/${totalRequired} وثائق إلزامية مرفوعة${uploadedRequired >= totalRequired ? ' — ✅ جاهز للإرسال' : ''}`;

  const btn = document.getElementById('submit-btn');
  const lbl = document.getElementById('submit-label');
  if (uploadedRequired >= totalRequired) {
    btn.disabled = false;
    lbl.textContent = '✅ إرسال للمراجعة';
  }
}

// ── SUBMIT FOR REVIEW ──
async function submitForReview() {
  const license = document.getElementById('license-input')?.value?.trim();
  if (!license) { showToast('error', 'الرجاء إدخال رقم ترخيص مزاولة المهنة'); return; }

  const btn = document.getElementById('submit-btn');
  const spinner = document.getElementById('submit-spinner');
  const lbl = document.getElementById('submit-label');

  btn.disabled = true;
  spinner.style.display = 'block';
  lbl.style.display = 'none';

  try {
    const res = await fetch('../api/vet_docs.php', {
      method: 'POST',
      headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: new URLSearchParams({ action: 'submit_review', license }),
    });
    const data = await res.json();
    if (data.success) {
      showToast('success', 'تم إرسال الوثائق للمراجعة! ✅');
      setTimeout(() => location.reload(), 1200);
    } else {
      showToast('error', data.error || 'فشل الإرسال');
      btn.disabled = false; spinner.style.display = 'none'; lbl.style.display = '';
    }
  } catch(e) {
    showToast('error', 'خطأ في الاتصال بالخادم');
    btn.disabled = false; spinner.style.display = 'none'; lbl.style.display = '';
  }
}

// ── LOGOUT ──
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 escHtml(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

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);
}
</script>
</body>
</html>
