<?php
require_once __DIR__ . '/includes/config.php';

// Always destroy any existing session when visiting login page
// This ensures clean state for new login
session_name(SESSION_NAME);
if (session_status() === PHP_SESSION_NONE) session_start();
$_SESSION = [];
session_unset();
session_destroy();
setcookie(SESSION_NAME, '', time() - 86400, '/');

// Start fresh session for lang/theme preferences only
session_start_secure();
$user = null; // Always require fresh login
$lang  = $_COOKIE['baitari_lang']  ?? 'ar';
$theme = $_COOKIE['baitari_theme'] ?? 'light';
$dir   = ($lang === 'ar') ? 'rtl' : 'ltr';
?>
<!DOCTYPE html>
<html lang="<?= h($lang) ?>" dir="<?= $dir ?>" 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="#0d3d2a">
<title>VetNet — منصة الرعاية البيطرية</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&family=Cormorant+Garamond:wght@600;700&display=swap" rel="stylesheet">
<style>
/* ── TOKENS ── */
:root{
  --g3:#6ee7b7;--g4:#34d399;--g5:#10b981;--g6:#059669;--g7:#047857;--g8:#065f46;--g9:#064e3b;
  --bg:#f0f7f3;--surface:#fff;--surface2:#f6faf8;--inp:#edf4f0;
  --border:rgba(6,95,70,.12);--border2:rgba(6,95,70,.22);
  --tp:#052e1c;--ts:#2d6a4f;--tm:#74a98a;
  --gold:#b5893a;--gold2:#f0c96e;
  --r:12px;--r2:20px;--r3:28px;
  --tr:.2s cubic-bezier(.4,0,.2,1);
  --sh:0 1px 2px rgba(0,0,0,.04),0 4px 16px rgba(0,0,0,.06);
  --sh2:0 2px 8px rgba(0,0,0,.06),0 8px 32px rgba(0,0,0,.1);
  --sh3:0 8px 24px rgba(0,0,0,.1),0 24px 64px rgba(0,0,0,.14);
}
[data-theme=dark]{
  --bg:#050f09;--surface:#0b1a10;--surface2:#0f2016;--inp:#0d1c13;
  --border:rgba(110,231,183,.08);--border2:rgba(110,231,183,.16);
  --tp:#d1fae5;--ts:#6ee7b7;--tm:#34786a;
}

/* ── RESET ── */
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
html{scroll-behavior:smooth;}
body{
  font-family:'Tajawal',sans-serif;
  background:var(--bg);color:var(--tp);
  min-height:100dvh;
  -webkit-font-smoothing:antialiased;
  -webkit-tap-highlight-color:transparent;
  overflow-x:hidden;
}
button{cursor:pointer;font-family:'Tajawal',sans-serif;border:none;background:none;}
input,select{font-family:'Tajawal',sans-serif;outline:none;}
img{display:block;}

/* ── SHELL ── */
.shell{
  max-width:460px;margin:0 auto;
  min-height:100dvh;
  background:var(--bg);
  position:relative;
  display:flex;flex-direction:column;
}
@media(min-width:600px){
  body{
    background:radial-gradient(ellipse at 20% 50%,rgba(6,95,70,.15),transparent 60%),
               radial-gradient(ellipse at 80% 20%,rgba(52,211,153,.08),transparent 50%),
               #040d07;
  }
  .shell{box-shadow:0 0 0 1px rgba(110,231,183,.08),var(--sh3);}
}

/* ── HERO ── */
.hero{
  position:relative;
  height:400px;
  overflow:hidden;
  flex-shrink:0;
}
.hero-img{
  width:100%;height:100%;
  object-fit:cover;object-position:center 25%;
  transform:scale(1.06);
  transition:transform 10s cubic-bezier(.25,.46,.45,.94);
}
.hero.loaded .hero-img{transform:scale(1);}

/* Cinematic overlay stack */
.hero::after{
  content:'';position:absolute;inset:0;
  background:
    linear-gradient(0deg,var(--bg) 0%,rgba(5,15,9,0) 45%),
    linear-gradient(160deg,rgba(4,78,59,.75) 0%,rgba(4,78,59,.1) 55%,transparent 100%);
  pointer-events:none;
}

/* Noise grain texture */
.hero-grain{
  position:absolute;inset:0;z-index:1;
  opacity:.04;pointer-events:none;
  background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
  background-size:180px;
}

/* ── CTRL BAR ── */
.ctrl-bar{
  position:absolute;top:0;left:0;right:0;z-index:10;
  display:flex;align-items:center;justify-content:space-between;
  padding:18px 20px;
}

.lang-group{display:flex;gap:4px;background:rgba(0,0,0,.3);border-radius:20px;padding:3px;backdrop-filter:blur(12px);}
.lp{
  padding:5px 14px;border-radius:16px;
  color:rgba(255,255,255,.7);font-size:13px;font-weight:800;
  cursor:pointer;transition:var(--tr);letter-spacing:.03em;
  font-family:'Tajawal',sans-serif;
}
.lp:hover{color:#fff;background:rgba(255,255,255,.12);}
.lp.on{background:rgba(255,255,255,.96);color:var(--g9);box-shadow:0 1px 6px rgba(0,0,0,.2);}

.theme-btn{
  width:38px;height:38px;border-radius:50%;
  background:rgba(0,0,0,.3);
  border:1px solid rgba(255,255,255,.15);
  display:flex;align-items:center;justify-content:center;
  font-size:17px;cursor:pointer;
  backdrop-filter:blur(12px);transition:var(--tr);
}
.theme-btn:hover{background:rgba(0,0,0,.5);}

/* ── HERO BRAND ── */
.hero-content{
  position:absolute;bottom:0;left:0;right:0;z-index:5;
  padding:20px 22px 36px;
  display:flex;flex-direction:column;align-items:center;
  text-align:center;
}
.brand{display:flex;flex-direction:column;align-items:center;}

.brand-logo{
  display:flex;align-items:center;justify-content:center;
  margin-bottom:8px;
  background:none !important;
  border:none !important;
  box-shadow:none !important;
  backdrop-filter:none !important;
}

.brand-name{
  font-size:38px;font-weight:900;color:#fff;
  line-height:1;
  text-shadow:0 2px 20px rgba(0,0,0,.4);
  letter-spacing:-.5px;
}
.brand-sub{
  font-size:13px;font-weight:400;
  color:rgba(255,255,255,.8);
  margin-top:5px;letter-spacing:.01em;
  text-align:center;
}

/* Live stats */
.hero-stats{display:flex;flex-direction:row;gap:6px;justify-content:center;margin-top:10px;flex-wrap:wrap;}
.hstat{
  display:flex;align-items:center;gap:7px;
  background:rgba(0,0,0,.32);
  border:1px solid rgba(255,255,255,.12);
  border-radius:20px;padding:5px 12px;
  backdrop-filter:blur(10px);
  font-size:12px;font-weight:700;color:rgba(255,255,255,.88);
  white-space:nowrap;
}
.hstat-pulse{
  width:7px;height:7px;border-radius:50%;
  background:#4ade80;flex-shrink:0;
  box-shadow:0 0 0 0 rgba(74,222,128,.5);
  animation:livepulse 2s infinite;
}
@keyframes livepulse{
  0%{box-shadow:0 0 0 0 rgba(74,222,128,.5);}
  70%{box-shadow:0 0 0 8px rgba(74,222,128,0);}
  100%{box-shadow:0 0 0 0 rgba(74,222,128,0);}
}

/* ── PANEL ── */
.panel{
  background:var(--surface);
  border-radius:28px 28px 0 0;
  margin-top:-28px;
  padding:10px 22px 52px;
  position:relative;z-index:10;
  flex:1;
  box-shadow:0 -12px 40px rgba(0,0,0,.1);
  border-top:1px solid var(--border);
}

/* Drag handle */
.handle{
  width:36px;height:4px;border-radius:2px;
  background:var(--border2);
  margin:10px auto 22px;
}

/* ── TABS ── */
.tabs{
  position:relative;
  display:flex;
  background:var(--inp);
  border-radius:14px;
  padding:3px;
  margin-bottom:26px;
  gap:0;
}
/* Animated indicator */
.tab-indicator{
  position:absolute;top:3px;bottom:3px;
  width:calc(50% - 3px);
  background:var(--surface);
  border-radius:11px;
  box-shadow:var(--sh);
  transition:transform var(--tr);
  pointer-events:none;
}
.tabs.on-r .tab-indicator{transform:translateX(-100%);}
[dir=ltr] .tabs.on-r .tab-indicator{transform:translateX(100%);}

.tab{
  flex:1;padding:11px 8px;
  border-radius:11px;border:none;background:none;
  font-size:15px;font-weight:800;color:var(--tm);
  cursor:pointer;transition:color var(--tr);
  position:relative;z-index:1;
  font-family:'Tajawal',sans-serif;
}
.tab.on{color:var(--g7);}

/* ── FORMS ── */
.frm{display:none;}
.frm.on{display:block;animation:revealUp .3s cubic-bezier(.22,1,.36,1) both;}
@keyframes revealUp{
  from{opacity:0;transform:translateY(14px);}
  to{opacity:1;transform:translateY(0);}
}

.fld{margin-bottom:16px;}
.lbl{
  font-size:11px;font-weight:800;color:var(--tm);
  margin-bottom:7px;display:flex;align-items:center;gap:5px;
  letter-spacing:.07em;text-transform:uppercase;
}
.lbl-req{color:var(--g5);font-size:14px;line-height:1;}

/* Floating label input group */
.igrp{
  position:relative;
  background:var(--inp);
  border-radius:var(--r);
  border:1.5px solid transparent;
  transition:border-color var(--tr),box-shadow var(--tr),background var(--tr);
}
.igrp:focus-within{
  border-color:var(--g5);background:var(--surface);
  box-shadow:0 0 0 4px rgba(16,185,129,.1);
}
.igrp.err{border-color:#ef4444;box-shadow:0 0 0 3px rgba(239,68,68,.1);}
.igrp-ico{
  position:absolute;right:14px;top:50%;transform:translateY(-50%);
  font-size:18px;opacity:.45;pointer-events:none;transition:opacity var(--tr);
}
[dir=ltr] .igrp-ico{right:auto;left:14px;}
.igrp:focus-within .igrp-ico{opacity:.7;}
.igrp-eye{
  position:absolute;left:14px;top:50%;transform:translateY(-50%);
  font-size:17px;opacity:.4;cursor:pointer;transition:opacity var(--tr);
}
[dir=ltr] .igrp-eye{left:auto;right:14px;}
.igrp-eye:hover{opacity:.8;}
.inp{
  width:100%;background:none;border:none;
  padding:13px 46px 13px 16px;
  font-size:15px;color:var(--tp);
  -webkit-appearance:none;
}
[dir=ltr] .inp{padding:13px 16px 13px 46px;}
.inp::placeholder{color:var(--tm);}
.sel{
  width:100%;background:none;border:none;
  padding:13px 16px;font-size:15px;color:var(--tp);
  -webkit-appearance:none;cursor:pointer;
}

.em{font-size:12px;color:#ef4444;font-weight:700;margin-top:5px;display:none;padding-right:2px;}
.em.on{display:block;}

/* ── CHECKBOX ── */
.crow{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;}
.clbl{display:flex;align-items:center;gap:9px;cursor:pointer;font-size:13px;font-weight:600;color:var(--ts);user-select:none;}
.clbl input{display:none;}
.cbox{
  width:22px;height:22px;border-radius:7px;
  background:var(--inp);border:1.5px solid var(--border2);
  display:flex;align-items:center;justify-content:center;
  font-size:12px;transition:var(--tr);flex-shrink:0;
}
.clbl input:checked+.cbox{background:var(--g6);border-color:var(--g6);color:#fff;}
.fgt-btn{font-size:13px;color:var(--g5);font-weight:700;background:none;border:none;cursor:pointer;font-family:'Tajawal',sans-serif;transition:var(--tr);}
.fgt-btn:hover{color:var(--g7);}

/* ── MAIN BUTTON ── */
.bmain{
  width:100%;
  background:var(--g7);
  color:#fff;border:none;border-radius:var(--r);
  padding:15px;font-size:16px;font-weight:900;
  cursor:pointer;transition:var(--tr);
  font-family:'Tajawal',sans-serif;
  position:relative;overflow:hidden;
  letter-spacing:.02em;
}
.bmain::after{
  content:'';position:absolute;
  top:-50%;left:-60%;width:40%;height:200%;
  background:linear-gradient(90deg,transparent,rgba(255,255,255,.15),transparent);
  transform:skewX(-15deg);
  transition:left .5s ease;pointer-events:none;
}
.bmain:hover{background:var(--g6);transform:translateY(-1px);box-shadow:0 8px 24px rgba(4,120,87,.35);}
.bmain:hover::after{left:120%;}
.bmain:active{transform:translateY(0);box-shadow:0 2px 8px rgba(4,120,87,.2);}
.bmain:disabled{opacity:.5;pointer-events:none;}

.bsec{
  width:100%;background:var(--inp);border:1.5px solid var(--border2);
  border-radius:var(--r);padding:13px;margin-top:10px;
  font-size:14px;font-weight:700;color:var(--ts);cursor:pointer;transition:var(--tr);
  font-family:'Tajawal',sans-serif;
}
.bsec:hover{background:var(--surface2);}

/* ── DIVIDER ── */
.divr{display:flex;align-items:center;gap:12px;margin:18px 0;}
.divr::before,.divr::after{content:'';flex:1;height:1px;background:var(--border);}
.divr-txt{font-size:12px;color:var(--tm);font-weight:700;white-space:nowrap;}

/* ── SOCIAL ── */
.soc{display:flex;gap:10px;}
.bsoc{
  flex:1;display:flex;align-items:center;justify-content:center;gap:8px;
  background:var(--inp);border:1.5px solid var(--border);border-radius:var(--r);
  padding:12px;font-size:14px;font-weight:700;color:var(--ts);
  cursor:pointer;transition:var(--tr);font-family:'Tajawal',sans-serif;
}
.bsoc:hover{border-color:var(--g4);color:var(--g7);background:rgba(16,185,129,.04);}

/* ── FOOTER ── */
.foot{text-align:center;margin-top:22px;font-size:14px;color:var(--ts);}
.foot a{color:var(--g6);font-weight:800;cursor:pointer;text-decoration:none;border-bottom:1.5px solid rgba(16,185,129,.3);transition:var(--tr);}
.foot a:hover{color:var(--g8);border-color:var(--g8);}

/* ── REGISTER ── */
.prog{display:flex;gap:4px;margin-bottom:22px;}
.ps{flex:1;height:3px;border-radius:2px;background:var(--border2);overflow:hidden;}
.ps-fill{height:100%;border-radius:2px;background:var(--g5);width:0%;transition:width .4s cubic-bezier(.4,0,.2,1);}
.ps.done .ps-fill{width:100%;}
.ps.act .ps-fill{width:100%;background:var(--g7);}

/* ROLE GRID */
.roles{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:18px;}
.rc{
  padding:16px 10px;background:var(--inp);
  border:1.5px solid var(--border);border-radius:var(--r2);
  text-align:center;cursor:pointer;transition:var(--tr);
  display:flex;flex-direction:column;align-items:center;gap:5px;
  font-family:'Tajawal',sans-serif;
  position:relative;overflow:hidden;
}
.rc::before{
  content:'';position:absolute;inset:0;
  background:linear-gradient(135deg,rgba(16,185,129,.06),transparent);
  opacity:0;transition:opacity var(--tr);
}
.rc:hover{border-color:var(--g4);transform:translateY(-2px);box-shadow:0 4px 16px rgba(16,185,129,.12);}
.rc:hover::before,.rc.on::before{opacity:1;}
.rc.on{border-color:var(--g5);box-shadow:0 0 0 3px rgba(16,185,129,.15);}
.ri{font-size:28px;line-height:1;}
.rn{font-size:13px;font-weight:800;color:var(--tp);}
.rs{font-size:11px;color:var(--tm);}

/* STRENGTH */
.sbar{height:3px;background:var(--border2);border-radius:2px;margin-top:7px;overflow:hidden;}
.sfill{height:100%;border-radius:2px;transition:width .4s,background .4s;width:0%;}
.slbl{font-size:11px;font-weight:700;margin-top:4px;}

/* UPLOAD */
.uzone{
  border:2px dashed var(--border2);border-radius:var(--r);
  padding:22px;text-align:center;cursor:pointer;
  background:var(--inp);margin-top:8px;transition:var(--tr);
}
.uzone:hover{border-color:var(--g5);background:rgba(16,185,129,.03);}
.uzone input{display:none;}

/* TERMS */
.terms-row{display:flex;align-items:flex-start;gap:9px;margin-bottom:18px;font-size:13px;color:var(--ts);line-height:1.5;}
.terms-row .cbox{margin-top:1px;}
.terms-row a{color:var(--g5);font-weight:700;}

/* ── TOAST ── */
.toast{
  position:fixed;top:18px;left:50%;transform:translateX(-50%) translateY(-10px);
  background:var(--surface);border:1px solid var(--border2);border-radius:var(--r);
  padding:13px 20px;display:flex;align-items:center;gap:10px;
  font-size:13px;font-weight:700;color:var(--tp);
  box-shadow:var(--sh3);z-index:9999;
  opacity:0;pointer-events:none;
  transition:opacity .28s,transform .28s cubic-bezier(.22,1,.36,1);
  width:90%;max-width:360px;
}
.toast.on{opacity:1;transform:translateX(-50%) translateY(0);pointer-events:auto;}
</style>
</head>
<body>

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

<div class="shell">

  <!-- HERO -->
  <div class="hero" id="hero">
    <img class="hero-img" src="assets/img/hero-bg.png" alt=""
      onload="this.closest('.hero').classList.add('loaded')">
    <div class="hero-grain"></div>

    <!-- Controls -->
    <div class="ctrl-bar">
      <div class="lang-group">
        <button class="lp <?= $lang==='ar'?'on':'' ?>" onclick="changeLang('ar')">عر</button>
        <button class="lp <?= $lang==='fr'?'on':'' ?>" onclick="changeLang('fr')">Fr</button>
        <button class="lp <?= $lang==='en'?'on':'' ?>" onclick="changeLang('en')">En</button>
      </div>
      <button class="theme-btn" id="tbtn" onclick="toggleTheme()"><?= $theme==='dark'?'☀️':'🌙' ?></button>
    </div>

    <!-- Brand + Stats -->
    <div class="hero-content">
      <div class="brand">
        <a href="home.php"><img src="assets/img/logo.png?v=3" alt="VetNet" style="width:90px;height:auto;filter:drop-shadow(0 2px 12px rgba(0,0,0,.35));cursor:pointer;display:block;margin-bottom:6px;"></a>
        <div class="brand-name" style="font-size:42px;">VetNet</div>
        <div class="brand-sub" id="hsub" data-i18n="app_tagline">منصة الرعاية البيطرية في الجزائر</div>
        <div class="hero-stats">
          <div class="hstat"><div class="hstat-pulse"></div><span id="hs-vets">87 طبيب</span></div>
          <div class="hstat">🚨 <span id="hs-emg">طوارئ 24/7</span></div>
          <div class="hstat">⭐ 4.8</div>
        </div>
      </div>
    </div>
  </div>

  <!-- PANEL -->
  <div class="panel">
    <div class="handle"></div>

    <!-- Tabs -->
    <div class="tabs" id="tabs-wrap">
      <div class="tab-indicator"></div>
      <button class="tab on" id="tl" onclick="showTab('l')" data-i18n="tab_login">تسجيل الدخول</button>
      <button class="tab"    id="tr" onclick="showTab('r')" data-i18n="tab_register">حساب جديد</button>
    </div>

    <!-- LOGIN -->
    <div class="frm on" id="fl">
      <div class="fld">
        <label class="lbl" data-i18n="lbl_phone">رقم الهاتف <span class="lbl-req">*</span></label>
        <div class="igrp">
          <input class="inp" id="lp" type="tel" inputmode="tel" maxlength="10"
            data-i18n-ph="ph_phone" placeholder="05XX XX XX XX">
          <span class="igrp-ico">📱</span>
        </div>
        <div class="em" id="elp" data-i18n="msg_phone_invalid">رقم غير صحيح</div>
      </div>
      <div class="fld">
        <label class="lbl" data-i18n="lbl_password">كلمة المرور <span class="lbl-req">*</span></label>
        <div class="igrp">
          <input class="inp" id="lw" type="password" data-i18n-ph="ph_password" placeholder="••••••••">
          <span class="igrp-ico">🔒</span>
          <button class="igrp-eye" onclick="toggleEye('lw',this)">👁</button>
        </div>
        <div class="em" id="elw" data-i18n="msg_required">مطلوب</div>
      </div>
      <div class="crow">
        <label class="clbl">
          <input type="checkbox" id="rem" onchange="document.getElementById('crm').textContent=this.checked?'✓':''">
          <div class="cbox" id="crm"></div>
          <span data-i18n="lbl_remember">تذكّرني</span>
        </label>
        <button class="fgt-btn" onclick="showToast('info',t('msg_forgot_sent'))" data-i18n="lbl_forgot">نسيت كلمة المرور؟</button>
      </div>
      <button class="bmain" id="bl" onclick="doLogin()"><span data-i18n="btn_login">دخول</span></button>
      <div class="divr"><div class="divr-txt">أو</div></div>
      <div class="soc">
        <button class="bsoc" onclick="showToast('info','قريباً')">🌐 Google</button>
        <button class="bsoc" onclick="showToast('info','قريباً')">📘 Facebook</button>
      </div>
      <div class="foot">
        <span data-i18n="footer_no_account">ليس لديك حساب؟</span>
        <a onclick="showTab('r')" data-i18n="footer_signup">سجّل الآن</a>
      </div>
    </div>

    <!-- REGISTER -->
    <div class="frm" id="fr">
      <div class="prog" id="prog">
        <div class="ps act" id="p1"><div class="ps-fill"></div></div>
        <div class="ps" id="p2"><div class="ps-fill"></div></div>
        <div class="ps" id="p3"><div class="ps-fill"></div></div>
      </div>

      <!-- Step 1 -->
      <div id="s1">
        <div style="font-size:15px;font-weight:800;color:var(--tp);margin-bottom:6px;">اختر نوع حسابك</div>
        <div style="font-size:13px;color:var(--tm);margin-bottom:16px;">حساب واحد لكل احتياجاتك البيطرية</div>
        <div class="roles" style="grid-template-columns:1fr 1fr;gap:12px;">
          <button class="rc on" data-role="client" onclick="pickR(this)" style="padding:20px 12px;">
            <span class="ri">🏡</span>
            <span class="rn" style="font-size:14px;">عميل</span>
            <span class="rs" style="font-size:12px;line-height:1.4;margin-top:4px;">صاحب حيوان أليف<br>أو مربي مزرعة<br>أو الاثنان معاً</span>
          </button>
          <button class="rc" data-role="vet" onclick="pickR(this)" style="padding:20px 12px;">
            <span class="ri">👨‍⚕️</span>
            <span class="rn" style="font-size:14px;">طبيب بيطري</span>
            <span class="rs" style="font-size:12px;line-height:1.4;margin-top:4px;">مقدّم خدمة<br>يحتاج اعتماد<br>من المنصة</span>
          </button>
        </div>
        <button class="bmain" onclick="goS(2)" style="margin-top:16px;"><span data-i18n="btn_next">التالي</span></button>
      </div>

      <!-- Step 2 -->
      <div id="s2" style="display:none">
        <div class="fld">
          <label class="lbl" data-i18n="lbl_name">الاسم الكامل <span class="lbl-req">*</span></label>
          <div class="igrp"><input class="inp" id="rn" type="text" data-i18n-ph="ph_name" placeholder="سارة بن علي"><span class="igrp-ico">👤</span></div>
          <div class="em" id="ern" data-i18n="msg_required">مطلوب</div>
        </div>
        <div class="fld">
          <label class="lbl" data-i18n="lbl_phone">رقم الهاتف <span class="lbl-req">*</span></label>
          <div class="igrp"><input class="inp" id="rp" type="tel" inputmode="tel" maxlength="10" data-i18n-ph="ph_phone" placeholder="05XX XX XX XX"><span class="igrp-ico">📱</span></div>
          <div class="em" id="erp" data-i18n="msg_phone_invalid">رقم غير صحيح</div>
        </div>
        <div class="fld">
          <label class="lbl" data-i18n="lbl_email_optional">البريد الإلكتروني (اختياري)</label>
          <div class="igrp"><input class="inp" id="re" type="email" data-i18n-ph="ph_email" placeholder="example@gmail.com"><span class="igrp-ico">📧</span></div>
        </div>
        <div class="fld">
          <label class="lbl" data-i18n="lbl_wilaya">الولاية</label>
          <div class="igrp"><select class="sel" id="rw"></select></div>
        </div>
        <button class="bmain" onclick="goS(3)"><span data-i18n="btn_next">التالي</span></button>
        <button class="bsec" onclick="goS(1)"><span data-i18n="btn_back">رجوع</span></button>
      </div>

      <!-- Step 3 -->
      <div id="s3" style="display:none">
        <div class="fld">
          <label class="lbl" data-i18n="lbl_password">كلمة المرور <span class="lbl-req">*</span></label>
          <div class="igrp">
            <input class="inp" id="rpass" type="password" oninput="chkStr(this.value)" data-i18n-ph="ph_password_new" placeholder="8 أحرف على الأقل">
            <span class="igrp-ico">🔒</span>
            <button class="igrp-eye" onclick="toggleEye('rpass',this)">👁</button>
          </div>
          <div class="sbar"><div class="sfill" id="sf"></div></div>
          <div class="slbl" id="sl"></div>
          <div class="em" id="erpass" data-i18n="msg_password_short">8 أحرف على الأقل</div>
        </div>
        <div class="fld">
          <label class="lbl" data-i18n="lbl_password_confirm">تأكيد كلمة المرور <span class="lbl-req">*</span></label>
          <div class="igrp">
            <input class="inp" id="rpass2" type="password" data-i18n-ph="ph_password" placeholder="••••••••">
            <span class="igrp-ico">🔒</span>
            <button class="igrp-eye" onclick="toggleEye('rpass2',this)">👁</button>
          </div>
          <div class="em" id="erpass2" data-i18n="msg_password_mismatch">غير متطابقتين</div>
        </div>
        <div id="vex" style="display:none">
          <div class="fld">
            <label class="lbl" data-i18n="lbl_license">رقم الترخيص</label>
            <input class="inp" id="rlic" type="text" placeholder="VET-XXXX" style="background:var(--inp);border:1.5px solid transparent;border-radius:var(--r);padding:13px 16px;">
          </div>
          <div class="fld">
            <label class="lbl" data-i18n="verify_upload">الشهادة المهنية</label>
            <div class="uzone" onclick="document.getElementById('rdoc').click()">
              <div style="font-size:28px;margin-bottom:6px">📄</div>
              <div id="rdocl" style="font-size:13px;color:var(--ts);font-weight:600">انقر لرفع الشهادة</div>
              <input type="file" id="rdoc" accept=".pdf,image/*" onchange="docPick(this)">
            </div>
          </div>
        </div>
        <label class="terms-row">
          <input type="checkbox" id="rterms" onchange="document.getElementById('ctm').textContent=this.checked?'✓':''">
          <div class="cbox" id="ctm"></div>
          <span data-i18n="lbl_terms">أوافق على شروط الاستخدام</span>
        </label>
        <button class="bmain" id="br" type="button"><span data-i18n="btn_register">إنشاء الحساب</span></button>
        <button class="bsec" onclick="goS(2)"><span data-i18n="btn_back">رجوع</span></button>
      </div>

      <div class="foot">
        <span data-i18n="footer_have_account">لديك حساب؟</span>
        <a onclick="showTab('l')" data-i18n="footer_signin">سجّل الدخول</a>
      </div>
    </div>

  </div>
</div>

<script>
// ══════════════════════════════════
// STATE
// ══════════════════════════════════
var role = 'client';
var savedTheme = localStorage.getItem('baitari_theme') || 'light';

// Apply theme on load
document.documentElement.setAttribute('data-theme', savedTheme);
if (savedTheme === 'dark') {
  var tb = document.getElementById('tbtn');
  if (tb) tb.textContent = '☀️';
}

// ══════════════════════════════════
// LANG — uses i18n.js
// ══════════════════════════════════
// ── TRANSLATIONS ──
var currentLang = localStorage.getItem('baitari_lang') || 'ar';

var TX = {
  ar: {
    dir:'rtl', lang:'ar',
    tab_login:'تسجيل الدخول', tab_register:'حساب جديد',
    btn_login:'دخول', btn_register:'إنشاء الحساب',
    btn_next:'التالي', btn_back:'رجوع',
    lbl_phone:'رقم الهاتف', lbl_password:'كلمة المرور',
    lbl_password_confirm:'تأكيد كلمة المرور',
    lbl_name:'الاسم الكامل', lbl_email_optional:'البريد الإلكتروني (اختياري)',
    lbl_wilaya:'الولاية', lbl_remember:'تذكّرني',
    lbl_forgot:'نسيت كلمة المرور؟', lbl_terms:'أوافق على شروط الاستخدام',
    lbl_license:'رقم الترخيص', verify_upload:'الشهادة المهنية',
    choose_role:'اختر نوع حسابك',
    role_pet_owner:'صاحب حيوان', role_pet_owner_sub:'قط، كلب...',
    role_farm_owner:'مربي / مزرعة', role_farm_owner_sub:'أبقار، أغنام...',
    role_vet:'طبيب بيطري', role_vet_sub:'مقدّم خدمة',
    role_clinic:'عيادة / مركز', role_clinic_sub:'فريق أطباء',
    footer_no_account:'ليس لديك حساب؟', footer_signup:'سجّل الآن',
    footer_have_account:'لديك حساب؟', footer_signin:'سجّل الدخول',
    app_tagline:'منصة الرعاية البيطرية في الجزائر',
    msg_phone_invalid:'رقم غير صحيح (10 أرقام)', msg_required:'مطلوب',
    msg_password_short:'8 أحرف على الأقل', msg_password_mismatch:'غير متطابقتين',
    msg_accept_terms:'الرجاء الموافقة على الشروط',
    msg_choose_role:'الرجاء اختيار نوع الحساب',
    msg_loading:'جارٍ التحميل...', msg_forgot_sent:'سيتم إرسال رابط على هاتفك',
    pass_weak:'ضعيفة', pass_medium:'متوسطة', pass_good:'جيدة', pass_strong:'ممتازة',
    ph_phone:'05XX XX XX XX', ph_password:'••••••••',
    ph_name:'سارة بن علي', ph_email:'example@gmail.com', ph_password_new:'8 أحرف على الأقل',
  },
  fr: {
    dir:'ltr', lang:'fr',
    tab_login:'Connexion', tab_register:'Créer un compte',
    btn_login:'Se connecter', btn_register:'Créer mon compte',
    btn_next:'Suivant', btn_back:'Retour',
    lbl_phone:'Numéro de téléphone', lbl_password:'Mot de passe',
    lbl_password_confirm:'Confirmer le mot de passe',
    lbl_name:'Nom complet', lbl_email_optional:'Email (optionnel)',
    lbl_wilaya:'Wilaya', lbl_remember:'Se souvenir',
    lbl_forgot:'Mot de passe oublié ?', lbl_terms:'Accepter les conditions',
    lbl_license:'Licence professionnelle', verify_upload:'Diplôme professionnel',
    choose_role:'Choisissez votre type de compte',
    role_pet_owner:'Propriétaire', role_pet_owner_sub:'Chat, chien...',
    role_farm_owner:'Eleveur', role_farm_owner_sub:'Bovins, ovins...',
    role_vet:'Vétérinaire', role_vet_sub:'Prestataire',
    role_clinic:'Clinique', role_clinic_sub:'Equipe médicale',
    footer_no_account:'Pas de compte ?', footer_signup:'Inscription',
    footer_have_account:'Déjà un compte ?', footer_signin:'Se connecter',
    app_tagline:'Plateforme vétérinaire en Algérie',
    msg_phone_invalid:'Numéro invalide (10 chiffres)', msg_required:'Obligatoire',
    msg_password_short:'Minimum 8 caractères', msg_password_mismatch:'Ne correspondent pas',
    msg_accept_terms:'Veuillez accepter les conditions',
    msg_choose_role:'Choisissez un type de compte',
    msg_loading:'Chargement...', msg_forgot_sent:'Un lien sera envoyé',
    pass_weak:'Faible', pass_medium:'Moyen', pass_good:'Bon', pass_strong:'Excellent',
    ph_phone:'05XX XX XX XX', ph_password:'••••••••',
    ph_name:'Votre nom', ph_email:'example@gmail.com', ph_password_new:'8 caractères min.',
  },
  en: {
    dir:'ltr', lang:'en',
    tab_login:'Sign in', tab_register:'Create account',
    btn_login:'Sign in', btn_register:'Create account',
    btn_next:'Next', btn_back:'Back',
    lbl_phone:'Phone number', lbl_password:'Password',
    lbl_password_confirm:'Confirm password',
    lbl_name:'Full name', lbl_email_optional:'Email (optional)',
    lbl_wilaya:'Province', lbl_remember:'Remember me',
    lbl_forgot:'Forgot password?', lbl_terms:'I agree to the terms',
    lbl_license:'License number', verify_upload:'Professional diploma',
    choose_role:'Choose your account type',
    role_pet_owner:'Pet Owner', role_pet_owner_sub:'Cat, dog...',
    role_farm_owner:'Farm Owner', role_farm_owner_sub:'Cattle, sheep...',
    role_vet:'Veterinarian', role_vet_sub:'Service provider',
    role_clinic:'Clinic', role_clinic_sub:'Medical team',
    footer_no_account:'No account?', footer_signup:'Sign up',
    footer_have_account:'Already have an account?', footer_signin:'Sign in',
    app_tagline:'Veterinary care platform in Algeria',
    msg_phone_invalid:'Invalid number (10 digits)', msg_required:'Required',
    msg_password_short:'Minimum 8 characters', msg_password_mismatch:'Do not match',
    msg_accept_terms:'Please accept the terms',
    msg_choose_role:'Please choose an account type',
    msg_loading:'Loading...', msg_forgot_sent:'A reset link will be sent',
    pass_weak:'Weak', pass_medium:'Medium', pass_good:'Good', pass_strong:'Strong',
    ph_phone:'05XX XX XX XX', ph_password:'••••••••',
    ph_name:'Your full name', ph_email:'example@gmail.com', ph_password_new:'8 chars minimum',
  },
};

function t(key) {
  var L = TX[currentLang] || TX.ar;
  return L[key] !== undefined ? L[key] : ((TX.ar[key]) || key);
}

function changeLang(l) {
  if (!TX[l]) return;
  currentLang = l;
  localStorage.setItem('baitari_lang', l);
  document.cookie = 'baitari_lang=' + l + ';path=/;max-age=' + (365*86400);
  applyLangFull(l);
}

function applyLangFull(l) {
  var T = TX[l] || TX.ar;
  var H = document.documentElement;
  H.lang = T.lang;
  H.dir  = T.dir;
  H.setAttribute('data-lang', l);

  // Update lang buttons
  document.querySelectorAll('.lb').forEach(function(b) {
    var oc = b.getAttribute('onclick') || '';
    b.classList.toggle('on', oc.indexOf("'"+l+"'") !== -1);
  });

  // Helper
  var set = function(id, v) { var e=document.getElementById(id); if(e) e.textContent=v; };
  var setH = function(id, v) { var e=document.getElementById(id); if(e) e.innerHTML=v; };
  var setPh = function(id, v) { var e=document.getElementById(id); if(e) e.placeholder=v; };
  var setAll = function(sel, v) { document.querySelectorAll(sel).forEach(function(e){e.textContent=v;}); };

  // Hero subtitle
  set('hsub', T.app_tagline);

  // Tabs
  set('tl', T.tab_login);
  set('tr', T.tab_register);

  // Login labels
  document.querySelectorAll('[data-i18n]').forEach(function(el) {
    var k = el.getAttribute('data-i18n');
    if (T[k] !== undefined) el.textContent = T[k];
  });
  document.querySelectorAll('[data-i18n-ph]').forEach(function(el) {
    var k = el.getAttribute('data-i18n-ph');
    if (T[k] !== undefined) el.placeholder = T[k];
  });

  // Inputs placeholders (by ID)
  setPh('lp',    T.ph_phone);
  setPh('lw',    T.ph_password);
  setPh('rn',    T.ph_name);
  setPh('rp',    T.ph_phone);
  setPh('re',    T.ph_email);
  setPh('rpass', T.ph_password_new);
  setPh('rpass2',T.ph_password);

  // Hero stats translation
  var hsVets = document.getElementById('hs-vets');
  var hsEmg  = document.getElementById('hs-emg');
  if (hsVets) hsVets.textContent = T.lang==='ar' ? '87 طبيب' : T.lang==='fr' ? '87 vétérinaires' : '87 vets';
  if (hsEmg)  hsEmg.textContent  = T.lang==='ar' ? 'طوارئ 24/7' : 'Urgences 24/7';
}

// ══════════════════════════════════
// THEME
// ══════════════════════════════════
function toggleTheme() {
  var t = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', t);
  localStorage.setItem('baitari_theme', t);
  document.cookie = 'baitari_theme=' + t + ';path=/;max-age=' + (365*86400);
  document.getElementById('tbtn').textContent = t === 'dark' ? '☀️' : '🌙';
}

// ══════════════════════════════════
// TABS
// ══════════════════════════════════
function showTab(tab) {
  document.getElementById('fl').classList.toggle('on', tab === 'l');
  document.getElementById('fr').classList.toggle('on', tab === 'r');
  document.getElementById('tl').classList.toggle('on', tab === 'l');
  document.getElementById('tr').classList.toggle('on', tab === 'r');
  var tw = document.getElementById('tabs-wrap');
  if (tw) tw.classList.toggle('on-r', tab === 'r');
}

// ══════════════════════════════════
// REGISTER STEPS
// ══════════════════════════════════
function pickR(el) {
  document.querySelectorAll('.rc').forEach(function(c) { c.classList.remove('on'); });
  el.classList.add('on');
  role = el.dataset.role;
}

function goS(n) {
  if (n === 2 && !role) { role = 'client'; }
  if (n === 3) {
    var nm = document.getElementById('rn').value.trim();
    var ph = document.getElementById('rp').value.trim();
    var ok = true;
    if (!nm)              { show('ern', 1);  ok = false; } else show('ern', 0);
    if (ph.length !== 10) { show('erp', 1);  ok = false; } else show('erp', 0);
    if (!ok) return;
    document.getElementById('vex').style.display = role === 'vet' ? '' : 'none';
  }
  for (var i = 1; i <= 3; i++) {
    document.getElementById('s' + i).style.display = i === n ? '' : 'none';
    document.getElementById('p' + i).className = 'ps' + (i < n ? ' done' : i === n ? ' act' : '');
  }
}

// ══════════════════════════════════
// EYE TOGGLE
// ══════════════════════════════════
function toggleEye(id, btn) {
  var el = document.getElementById(id);
  el.type = el.type === 'password' ? 'text' : 'password';
  btn.textContent = el.type === 'password' ? '👁' : '🙈';
}

// ══════════════════════════════════
// PASSWORD STRENGTH
// ══════════════════════════════════
function chkStr(v) {
  var s = 0;
  if (v.length >= 8) s++;
  if (/[A-Z]/.test(v)) s++;
  if (/[0-9]/.test(v)) s++;
  if (/[^A-Za-z0-9]/.test(v)) s++;
  var m = [
    ['0%','',''],
    ['30%', t('pass_weak'),   '#ef4444'],
    ['55%', t('pass_medium'), '#f59e0b'],
    ['80%', t('pass_good'),   '#22c55e'],
    ['100%',t('pass_strong'), '#15803d']
  ];
  var d = m[s] || m[0];
  document.getElementById('sf').style.width = d[0];
  document.getElementById('sf').style.background = d[2];
  document.getElementById('sl').textContent = d[1];
  document.getElementById('sl').style.color = d[2];
}

// ══════════════════════════════════
// DOC UPLOAD
// ══════════════════════════════════
function docPick(inp) {
  if (inp.files && inp.files[0]) {
    document.getElementById('rdocl').textContent = '✅ ' + inp.files[0].name;
    showToast('success', t('msg_saved'));
  }
}

// ══════════════════════════════════
// LOGIN
// ══════════════════════════════════
async function doLogin() {
  var ph = document.getElementById('lp').value.trim();
  var pw = document.getElementById('lw').value;
  var ok = true;
  if (ph.length !== 10) { show('elp', 1); document.getElementById('lp').classList.add('e'); ok = false; }
  else { show('elp', 0); document.getElementById('lp').classList.remove('e'); }
  if (!pw) { show('elw', 1); document.getElementById('lw').classList.add('e'); ok = false; }
  else { show('elw', 0); document.getElementById('lw').classList.remove('e'); }
  if (!ok) return;

  var btn = document.getElementById('bl');
  btn.disabled = true; btn.querySelector('span').textContent = t('msg_loading');

  try {
    var res = await fetch('api/auth.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'action=login&phone=' + encodeURIComponent(ph) + '&password=' + encodeURIComponent(pw)
    });
    var data = await res.json();
    if (data.success) {
      showToast('success', t('msg_login_success'));
      setTimeout(function() { window.location.href = data.redirect || 'index.php'; }, 700);
    } else {
      showToast('error', data.error || t('msg_error'));
      btn.disabled = false; btn.querySelector('span').textContent = t('btn_login');
    }
  } catch (e) {
    showToast('error', 'خطأ في الاتصال. حاول مجدداً.');
    btn.disabled = false;
    btn.querySelector('span').textContent = t('btn_login');
  }
}

// ══════════════════════════════════
// REGISTER
// ══════════════════════════════════
async function doReg() {
  var p1 = document.getElementById('rpass') ? document.getElementById('rpass').value : '';
  var p2 = document.getElementById('rpass2') ? document.getElementById('rpass2').value : '';

  // Validate password
  if (p1.length < 8) { show('erpass', 1); return; }
  show('erpass', 0);
  if (p1 !== p2) { show('erpass2', 1); return; }
  show('erpass2', 0);

  // Validate terms
  var termsEl = document.getElementById('rterms');
  if (!termsEl || !termsEl.checked) {
    showToast('error', t('msg_accept_terms'));
    return;
  }

  // Validate name + phone
  var nameEl  = document.getElementById('rn');
  var phoneEl = document.getElementById('rp');
  var name  = nameEl  ? nameEl.value.trim()  : '';
  var phone = phoneEl ? phoneEl.value.trim() : '';
  if (!name)  { showToast('error', 'أدخل اسمك الكامل'); return; }
  if (phone.length !== 10) { showToast('error', t('msg_phone_invalid')); return; }

  // Disable button
  var btn = document.getElementById('br');
  var btnSpan = btn ? btn.querySelector('span') : null;
  if (btn) btn.disabled = true;
  if (btnSpan) btnSpan.textContent = t('msg_loading');

  // Build body
  var licEl   = document.getElementById('rlic');
  var wilayaEl= document.getElementById('rw');
  var emailEl = document.getElementById('re');
  var body = 'action=register'
    + '&name='    + encodeURIComponent(name)
    + '&phone='   + encodeURIComponent(phone)
    + '&email='   + encodeURIComponent(emailEl  ? emailEl.value.trim()  : '')
    + '&password='+ encodeURIComponent(p1)
    + '&role='    + encodeURIComponent(role || 'pet_owner')
    + '&wilaya='  + encodeURIComponent(wilayaEl ? wilayaEl.value : '')
    + '&license=' + encodeURIComponent(licEl    ? licEl.value           : '');

  try {
    var res  = await fetch('api/auth.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: body
    });

    // Check HTTP status first
    if (!res.ok) {
      showToast('error', 'خطأ من السيرفر: ' + res.status + ' ' + res.statusText);
      if (btn) btn.disabled = false;
      if (btnSpan) btnSpan.textContent = t('btn_register');
      return;
    }

    // Try parsing JSON
    var rawText = await res.text();
    var data;
    try {
      data = JSON.parse(rawText);
    } catch(parseErr) {
      // Show raw PHP error
      showToast('error', 'خطأ PHP: ' + rawText.substring(0, 120));
      console.error('PHP raw response:', rawText);
      if (btn) btn.disabled = false;
      if (btnSpan) btnSpan.textContent = t('btn_register');
      return;
    }

    if (data.success) {
      if (data.pending) {
        showToast('success', 'تم إنشاء الحساب بنجاح ✅');
        setTimeout(function() {
          window.location.href = 'pages/vet-onboarding.php';
        }, 1200);
      } else {
        showToast('success', t('msg_register_success'));
        setTimeout(function() { window.location.href = data.redirect || 'index.php'; }, 900);
      }
    } else {
      showToast('error', data.error || t('msg_error'));
      if (btn) btn.disabled = false;
      if (btnSpan) btnSpan.textContent = t('btn_register');
    }
  } catch (e) {
    showToast('error', 'خطأ: ' + e.message);
    console.error('doReg error:', e);
    if (btn) btn.disabled = false;
    if (btnSpan) btnSpan.textContent = t('btn_register');
  }
}

// Attach register button listener
(function() {
  var regBtn = document.getElementById('br');
  if (regBtn) {
    regBtn.addEventListener('click', function(e) {
      e.preventDefault();
      doReg();
    });
  }
})();

// ══════════════════════════════════
// WILAYAS
// ══════════════════════════════════
(function() {
  var ws = ['الجزائر','وهران','قسنطينة','عنابة','سطيف','البليدة','تلمسان','باتنة','بجاية',
    'الجلفة','سيدي بلعباس','بسكرة','مسيلة','تبسة','سكيكدة','الشلف','تيارت','بومرداس',
    'مستغانم','جيجل','تيزي وزو','المدية','الأغواط','خنشلة','أم البواقي','أدرار','بشار',
    'إليزي','تمنراست','تندوف'];
  var sel = document.getElementById('rw');
  ws.forEach(function(w) {
    var o = document.createElement('option');
    o.value = w; o.textContent = w; sel.appendChild(o);
  });
})();

// ══════════════════════════════════
// HELPERS
// ══════════════════════════════════
function show(id, v) {
  var el = document.getElementById(id);
  if (el) el.classList.toggle('on', !!v);
}

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