<?php
require_once dirname(__DIR__).'/config.php';
$u = current_user();
if (!$u) { header('Location: ' . url('?login=1')); exit; }
$plan      = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';
$planLabel = ['free'=>'مجاني','plus'=>'Plus','pro'=>'Pro','corp'=>'شركات'][$plan] ?? $plan;
$planColor = ['free'=>'#64748b','plus'=>'#00d97e','pro'=>'#f59e0b','corp'=>'#a78bfa'][$plan] ?? '#64748b';
$firstName = explode(' ', trim($u['full_name'] ?? 'مستخدم'))[0];
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
  <title>ملفي — سودانا</title>
  <style>
    :root{--g:#00d97e;--dark:#073328;--bg:#f0fdf4;--card:#fff;--text:#1e293b;--muted:#64748b;--border:#e2e8f0;--gold:#f59e0b;--safe-bottom:env(safe-area-inset-bottom,0px)}
    *{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent}
    body{font-family:'Cairo','Noto Sans Arabic',system-ui,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;padding-bottom:calc(70px + var(--safe-bottom))}
    .hdr{background:var(--dark);height:56px;display:flex;align-items:center;justify-content:space-between;padding:0 16px;position:sticky;top:0;z-index:100}
    .logo{color:#fff;font-weight:900;font-size:1rem}
    .back{color:rgba(255,255,255,.6);font-size:.82rem;text-decoration:none}
    .hero{background:linear-gradient(135deg,var(--dark),#0a2a1a);padding:28px 16px;text-align:center;position:relative}
    .hero::after{content:'';position:absolute;bottom:-1px;left:0;right:0;height:20px;background:var(--bg);border-radius:20px 20px 0 0}
    .avatar-lg{width:72px;height:72px;background:linear-gradient(135deg,var(--g),#0ea5e9);border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:900;font-size:2rem;margin:0 auto 12px}
    .user-name{color:#fff;font-size:1.2rem;font-weight:900;margin-bottom:4px}
    .plan-badge{display:inline-block;border-radius:20px;padding:4px 14px;font-size:.75rem;font-weight:700;border:1px solid;margin-bottom:4px}
    .user-joined{color:rgba(255,255,255,.5);font-size:.75rem}
    .container{max-width:640px;margin:0 auto;padding:16px}
    .section{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:16px;margin-bottom:14px;box-shadow:0 1px 6px rgba(0,0,0,.04)}
    .sec-title{font-size:.9rem;font-weight:800;color:var(--dark);margin-bottom:14px;display:flex;align-items:center;gap:6px}
    .stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:4px}
    .stat-box{background:#f8fafc;border:1px solid var(--border);border-radius:12px;padding:14px 8px;text-align:center}
    .stat-val{font-size:1.5rem;font-weight:900;color:var(--g)}
    .stat-lbl{font-size:.67rem;color:var(--muted);margin-top:3px}
    .field{margin-bottom:14px}
    .field label{display:block;font-size:.75rem;font-weight:700;color:var(--muted);margin-bottom:5px}
    .field input,.field select{width:100%;background:#f8fafc;border:1.5px solid var(--border);border-radius:10px;padding:11px 14px;font-family:inherit;font-size:16px;color:var(--text)}
    .field input:focus,.field select:focus{outline:none;border-color:var(--g);background:#fff}
    .btn-save{background:linear-gradient(135deg,var(--g),#059669);color:#fff;border:none;border-radius:12px;padding:13px;width:100%;font-family:inherit;font-weight:800;font-size:.92rem;cursor:pointer;margin-top:6px}
    .badge-item{display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid var(--border);font-size:.82rem}
    .badge-item:last-child{border:none}
    .badge-icon{font-size:1.6rem}
    .badge-locked{opacity:.35;filter:grayscale(1)}
    .plan-card{background:linear-gradient(135deg,var(--dark),#0a2a1a);border-radius:14px;padding:16px;color:#fff;margin-bottom:8px}
    .plan-name{font-size:1.1rem;font-weight:900;margin-bottom:4px}
    .plan-desc{font-size:.78rem;color:rgba(255,255,255,.65);line-height:1.6}
    .btn-upgrade{background:var(--gold);color:#000;border:none;border-radius:10px;padding:10px 20px;font-family:inherit;font-weight:800;font-size:.85rem;cursor:pointer;margin-top:12px;width:100%}
    .btn-logout{background:#fee2e2;color:#dc2626;border:1px solid #fca5a5;border-radius:10px;padding:11px;width:100%;font-family:inherit;font-weight:700;font-size:.88rem;cursor:pointer}
    .bottom-nav{position:fixed;bottom:0;left:0;right:0;background:#fff;border-top:1px solid var(--border);display:flex;padding:8px 0 calc(8px + var(--safe-bottom));z-index:100}
    .nav-item{flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;text-decoration:none;color:var(--muted);font-size:.62rem;padding:4px 0}
    .nav-item.active{color:var(--g)}
    .nav-icon{font-size:1.2rem}
    .toast{position:fixed;bottom:80px;left:50%;transform:translateX(-50%);background:var(--dark);color:#fff;padding:10px 20px;border-radius:10px;font-size:.82rem;font-weight:700;z-index:999;display:none}
    .skel{background:linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%);background-size:200% 100%;animation:sk 1.4s infinite;border-radius:8px;height:14px;margin-bottom:8px}
    @keyframes sk{0%{background-position:200% 0}100%{background-position:-200% 0}}
    @media(max-width:400px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
  </style>
</head>
<body>
<header class="hdr">
  <div class="logo">👤 ملفي</div>
  <a href="/app/dashboard.php" class="back">← الرئيسية</a>
</header>

<div class="hero">
  <div class="avatar-lg"><?php echo mb_substr($firstName,0,1); ?></div>
  <div class="user-name"><?php echo htmlspecialchars($u['full_name']??''); ?></div>
  <div class="plan-badge" style="color:<?php echo $planColor;?>;border-color:<?php echo $planColor;?>"><?php echo $planLabel;?></div>
  <div class="user-joined">عضو منذ <?php echo date('M Y', strtotime($u['created_at']??'now')); ?></div>
</div>

<div class="container">

  <div class="section">
    <div class="sec-title">📊 إحصاءاتي</div>
    <div class="stats-grid">
      <div class="stat-box"><div class="stat-val" id="s-ai">-</div><div class="stat-lbl">طلبات AI</div></div>
      <div class="stat-box"><div class="stat-val" id="s-bk">-</div><div class="stat-lbl">حجوزاتي</div></div>
      <div class="stat-box"><div class="stat-val" id="s-pts">-</div><div class="stat-lbl">نقاطي</div></div>
    </div>
  </div>

  <div class="section">
    <div class="sec-title">✏️ بيانات الحساب</div>
    <form id="profile-form">
      <div class="field"><label>الاسم الكامل</label>
        <input type="text" id="f-name" value="<?php echo htmlspecialchars($u['full_name']??''); ?>"></div>
      <div class="field"><label>رقم الهاتف</label>
        <input type="tel" id="f-phone" value="<?php echo htmlspecialchars($u['phone']??''); ?>"></div>
      <div class="field"><label>البريد الإلكتروني</label>
        <input type="email" id="f-email" value="<?php echo htmlspecialchars($u['email']??''); ?>"></div>
      <div class="field"><label>المهنة (اختياري)</label>
        <select id="f-occupation">
          <option value="">اختر مهنتك</option>
          <option value="medical">طبيب / صيدلاني / ممرض</option>
          <option value="legal">محامٍ / قانوني</option>
          <option value="education">مدرِّس / أستاذ</option>
          <option value="engineering">مهندس</option>
          <option value="business">صاحب عمل / تاجر</option>
          <option value="craft">حرفي / صانع</option>
          <option value="food">طباخ / صانع غذاء</option>
          <option value="beauty">تجميل / حناء</option>
          <option value="agriculture">مزارع / ثروة حيوانية</option>
          <option value="student">طالب / طالبة</option>
          <option value="other">أخرى</option>
        </select></div>
      <button type="button" class="btn-save" onclick="saveProfile()">💾 حفظ التعديلات</button>
    </form>
  </div>

  <div class="section">
    <div class="sec-title">🏅 إنجازاتي</div>
    <div id="badges-list"><div class="skel"></div><div class="skel"></div></div>
  </div>

  <div class="section">
    <div class="sec-title">💳 خطة الاشتراك</div>
    <div class="plan-card">
      <div class="plan-name" style="color:<?php echo $planColor;?>"><?php echo $planLabel;?></div>
      <div class="plan-desc" id="plan-desc">جاري التحميل...</div>
      <?php if ($plan === 'free' || $plan === 'plus'): ?>
      <button class="btn-upgrade" onclick="window.location.href='/#pricing'">
        ⭐ ترقية الخطة
      </button>
      <?php endif; ?>
    </div>
  </div>

  <div class="section">
    <button class="btn-logout" onclick="logout()">🚪 تسجيل الخروج</button>
  </div>

</div>

<nav class="bottom-nav">
  <a href="/app/dashboard.php"   class="nav-item"><span class="nav-icon">🏠</span><span>الرئيسية</span></a>
  <a href="/app/services.php"    class="nav-item"><span class="nav-icon">⚡</span><span>الخدمات</span></a>
  <a href="/app/suggestions.php" class="nav-item"><span class="nav-icon">💡</span><span>اقتراح</span></a>
  <a href="/app/notifications.php" class="nav-item"><span class="nav-icon">🔔</span><span>إشعارات</span></a>
  <a href="/app/profile.php"     class="nav-item active"><span class="nav-icon">👤</span><span>حسابي</span></a>
</nav>
<div class="toast" id="toast"></div>

<script>
function showToast(msg){
  const t=document.getElementById('toast');
  t.textContent=msg; t.style.display='block';
  setTimeout(()=>t.style.display='none',2500);
}

async function loadStats(){
  try{
    const r=await fetch('/api/user/context.php');
    const d=await r.json();
    document.getElementById('s-ai').textContent=d.stats?.ai_today??0;
    document.getElementById('s-bk').textContent=d.stats?.bookings_total??0;
    document.getElementById('s-pts').textContent=(d.user?.points??0).toLocaleString('ar-SA');
    // Dynamic plan description from limits in context
    const plan = d.user?.plan || 'free';
    const lim  = d.limits || {};
    let desc;
    if (plan === 'corp') {
      desc = 'شركات — غير محدود · جميع الخدمات';
    } else if (plan === 'free') {
      desc = `مجاني — ${lim.ai_daily||20} سؤال/يوم · ${lim.bookings_daily||2} حجوزات/يوم`;
    } else {
      const planName = plan === 'plus' ? 'Plus' : 'Pro';
      desc = `${planName} — ${lim.ai_daily} سؤال/يوم · ${lim.bookings_daily} حجوزات/يوم` +
             (lim.doc_credit_sdg ? ` · رصيد وثائق ${Number(lim.doc_credit_sdg).toLocaleString('ar-SD')} SDG` : '');
    }
    document.getElementById('plan-desc').textContent = desc;
  }catch(e){}
}

async function loadBadges(){
  try{
    const r=await fetch('/api/achievements/leaderboard.php');
    const d=await r.json();
    const badges=[
      {key:'first_booking',icon:'📅',name:'أول حجز',desc:'أجريت أول حجز'},
      {key:'ai_explorer',icon:'🤖',name:'مستكشف الذكاء',desc:'10 أسئلة للـ AI'},
      {key:'idea_maker',icon:'💡',name:'صانع الأفكار',desc:'تم قبول اقتراحك'},
      {key:'doc_creator',icon:'📄',name:'موثِّق محترف',desc:'5 وثائق تجارية'},
      {key:'loyal_member',icon:'🏅',name:'عضو وفي',desc:'30 يوم متتالي'},
      {key:'top_voter',icon:'🗳️',name:'مُقيِّم نشط',desc:'20 تصويت'},
    ];
    const earned=new Set((d.user_badges||[]).map(b=>b.badge_key));
    document.getElementById('badges-list').innerHTML=badges.map(b=>`
      <div class="badge-item ${earned.has(b.key)?'':'badge-locked'}">
        <div class="badge-icon">${b.icon}</div>
        <div><div style="font-weight:700">${b.name}</div>
        <div style="font-size:.72rem;color:var(--muted)">${b.desc}</div></div>
        ${earned.has(b.key)?'<span style="margin-right:auto;color:var(--g);font-size:.75rem">✅</span>':''}
      </div>`).join('');
  }catch(e){
    document.getElementById('badges-list').innerHTML='<p style="color:var(--muted);font-size:.82rem">لا إنجازات بعد — ابدأ الاستخدام!</p>';
  }
}

async function saveProfile(){
  const body={
    full_name: document.getElementById('f-name').value.trim(),
    email:     document.getElementById('f-email').value.trim(),
    occupation:document.getElementById('f-occupation').value,
  };
  try{
    const r=await fetch('/api/auth/profile.php',{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify(body)
    });
    const d=await r.json();
    showToast(d.ok?'✅ تم الحفظ':'❌ حدث خطأ');
  }catch(e){showToast('❌ تعذّر الحفظ');}
}

async function logout(){
  await fetch('/api/auth/logout.php',{method:'POST'});
  window.location.href='/';
}

loadStats();
loadBadges();

// ── Profile: Pay + Bank ──────────────────────────────────────
(async function loadProfilePay(){
  try {
    const [rp, rb] = await Promise.all([
      fetch('/api/user/profile.php'),
      fetch('/api/pay/dashboard.php')
    ]);
    const dp = await rp.json();
    const db2 = await rb.json();
    const bal = db2.data?.available ?? 0;
    const el = document.getElementById('profile-pay-balance');
    if(el) el.textContent = Number(bal).toLocaleString('ar-SA') + ' SDG';
    const nameEl = document.getElementById('profile-name');
    if(nameEl && dp.data?.name) nameEl.textContent = dp.data.name;
  } catch(e){}
})();
</script>

<script>
(async function loadProfilePayData(){
  try {
    // رصيد Pay
    const r = await fetch('/api/pay/dashboard.php');
    const d = await r.json();
    const bal = d.data?.available ?? d.data?.balance ?? 0;
    const el = document.getElementById('profile-pay-balance');
    if(el) el.textContent = Number(bal).toLocaleString('ar-SA') + ' SDG';
    // KYC level
    const kycLevels = {1:'KYC L1 — حد 500K SDG/يوم', 2:'KYC L2 — حد 5M SDG/يوم', 3:'KYC L3 — غير محدود'};
    const kycEl = document.getElementById('profile-kyc-level');
    if(kycEl) kycEl.textContent = kycLevels[d.data?.kyc_level||1] || 'KYC L1';
  } catch(e){}

  try {
    // آخر 5 معاملات
    const r2 = await fetch('/api/pay/history.php?limit=5');
    const d2 = await r2.json();
    const txns = d2.data || d2.transactions || [];
    const statusColor = {completed:'#059669', failed:'#dc2626', pending:'#d97706', processing:'#d97706'};
    const statusAr = {completed:'مكتملة', failed:'فاشلة', pending:'معلقة', processing:'قيد المعالجة'};
    const container = document.getElementById('profile-txn-list');
    if(container) {
      if(!txns.length) {
        container.innerHTML = '<p style="text-align:center;color:#64748b;font-size:.78rem;padding:12px">لا معاملات بعد</p>';
      } else {
        container.innerHTML = txns.map(t => `
          <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid #f1f5f9">
            <div>
              <div style="font-size:.82rem;font-weight:600">${t.type==='transfer'?'تحويل':t.type==='bill'?'فاتورة':t.type==='gov'?'حكومي':'معاملة'}</div>
              <div style="font-size:.68rem;color:#64748b">${(t.created_at||'').substring(0,16)} · ${t.txn_ref||''}</div>
            </div>
            <div style="text-align:left">
              <div style="font-weight:800;font-size:.88rem;color:${statusColor[t.status]||'#1e293b'}">${Number(t.amount_sdg||0).toLocaleString('ar-SA')} SDG</div>
              <div style="font-size:.65rem;color:${statusColor[t.status]||'#64748b'}">${statusAr[t.status]||t.status}</div>
            </div>
          </div>`).join('');
      }
    }
  } catch(e){}

  try {
    // عدد التكتات المفتوحة
    const r3 = await fetch('/api/support/ticket.php?action=list');
    const d3 = await r3.json();
    const openCount = (d3.tickets||[]).filter(t=>t.status!=='resolved').length;
    const countEl = document.getElementById('open-tickets-count');
    if(countEl) countEl.innerHTML = openCount > 0
      ? `<span style="color:#dc2626">${openCount} تكت مفتوح</span>`
      : '<span style="color:#059669">لا تكتات مفتوحة ✅</span>';
  } catch(e){}
})();
</script>


<div id="support-section" style="display:none"><!-- support --></div>

<!-- ══ Pay + History + Support Section ════════════════════════ -->
<div id="pay-profile-section" style="margin:16px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:16px;padding:16px">
  <div style="font-weight:900;font-size:.95rem;color:#073328;margin-bottom:12px">💳 Sudanna Pay</div>
  <!-- الرصيد -->
  <div style="background:#073328;border-radius:12px;padding:14px;margin-bottom:12px;display:flex;justify-content:space-between;align-items:center">
    <div><div style="font-size:.7rem;color:rgba(255,255,255,.5);margin-bottom:2px">الرصيد المتاح</div>
    <div style="font-size:1.4rem;font-weight:900;color:#fff" id="prof-balance">— SDG</div></div>
    <a href="/app/pay.php" style="background:#00d97e;color:#000;border-radius:10px;padding:8px 14px;font-size:.78rem;font-weight:700;text-decoration:none">فتح Pay</a>
  </div>
  <!-- KYC Level -->
  <div style="background:#fff;border-radius:10px;padding:12px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center">
    <div><div style="font-size:.7rem;color:#64748b">مستوى التحقق (KYC)</div>
    <div style="font-weight:700;color:#073328" id="kyc-level">جاري التحميل...</div></div>
    <div style="font-size:.72rem;color:#64748b" id="kyc-limit">—</div>
  </div>
  <!-- آخر المعاملات -->
  <div style="background:#fff;border-radius:10px;padding:12px;margin-bottom:10px">
    <div style="font-weight:700;font-size:.82rem;color:#073328;margin-bottom:8px">آخر المعاملات</div>
    <div id="prof-txns"><div style="color:#64748b;text-align:center;padding:12px;font-size:.78rem">جاري التحميل...</div></div>
    <a href="/app/pay-history.php" style="display:block;text-align:center;margin-top:8px;font-size:.75rem;color:#00d97e;text-decoration:none">السجل الكامل ←</a>
  </div>
  <!-- الدعم -->
  <div style="background:#fff;border-radius:10px;padding:12px">
    <div style="font-weight:700;font-size:.82rem;color:#073328;margin-bottom:8px">🎫 الدعم والمساعدة</div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
      <a href="/app/support.php" style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:10px;padding:10px;text-align:center;font-size:.75rem;font-weight:600;color:#073328;text-decoration:none">
        &#127993; تكتاتي
      </a>
      <a href="/app/support.php" style="background:#073328;border-radius:10px;padding:10px;text-align:center;font-size:.75rem;font-weight:600;color:#fff;text-decoration:none">
        &#43; مشكلة جديدة
      </a>
    </div>
  </div>
</div>

<script>
(async function loadProfilePay(){
  try {
    const r  = await fetch('/api/pay/dashboard.php');
    const d  = await r.json();
    const dd = d.data||{};
    const fmt = n => Number(n||0).toLocaleString('ar-SA');
    // Balance
    const balEl = document.getElementById('prof-balance');
    if(balEl) balEl.textContent = fmt(dd.available||dd.balance) + ' SDG';
    // KYC
    const kyc = dd.kyc_level||1;
    const kycEl = document.getElementById('kyc-level');
    const kycLim = document.getElementById('kyc-limit');
    if(kycEl) kycEl.textContent = 'المستوى ' + kyc;
    const limits = {1:'حد يومي: 500,000 SDG',2:'حد يومي: 5,000,000 SDG',3:'غير محدود'};
    if(kycLim) kycLim.textContent = limits[kyc]||'—';
    // Transactions
    const txns = dd.recent_transactions||[];
    const txnEl = document.getElementById('prof-txns');
    if(txnEl && txns.length) {
      txnEl.innerHTML = txns.slice(0,5).map(t=>`
        <div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #f1f5f9;font-size:.75rem">
          <div style="color:#334155">${t.narration||t.type||'معاملة'}</div>
          <div style="font-weight:700;color:${t.direction==='in'?'#059669':'#dc2626'}">${t.direction==='in'?'+':'-'}${fmt(t.amount_sdg)} SDG</div>
        </div>`).join('');
    } else if(txnEl) {
      txnEl.innerHTML = '<p style="color:#94a3b8;text-align:center;font-size:.75rem">لا معاملات بعد</p>';
    }
  } catch(e){}
})();
</script>

<script src="/assets/pricing-loader.js" defer></script>
</body>
</html>