<?php
require_once dirname(__DIR__).'/config.php';
$u = current_user();
if (!$u) { header('Location: ' . url('?login=1')); exit; }
$uid = (int)$u['id'];
?><!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}.back{color:rgba(255,255,255,.6);font-size:.82rem;text-decoration:none}
    .tabs{display:flex;gap:0;background:var(--dark);padding:0 16px 12px}
    .tab-btn{flex:1;background:rgba(255,255,255,.08);border:none;border-radius:8px;padding:8px;color:rgba(255,255,255,.65);font-family:inherit;font-size:.78rem;cursor:pointer;transition:.2s;margin:0 3px}
    .tab-btn.active{background:var(--g);color:#000;font-weight:700}
    .container{max-width:720px;margin:0 auto;padding:16px}
    .bk-card{background:var(--card);border:1px solid var(--border);border-radius:14px;padding:14px;margin-bottom:12px;box-shadow:0 1px 4px rgba(0,0,0,.04)}
    .bk-top{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:8px}
    .bk-service{font-weight:800;font-size:.9rem}
    .bk-status{border-radius:20px;padding:3px 10px;font-size:.7rem;font-weight:700}
    .status-confirmed{background:#d1fae5;color:#065f46}
    .status-pending{background:#fef3c7;color:#92400e}
    .status-cancelled{background:#fee2e2;color:#991b1b}
    .status-completed{background:#dbeafe;color:#1d4ed8}
    .bk-provider{font-size:.8rem;color:var(--muted);margin-bottom:4px}
    .bk-time{font-size:.78rem;color:var(--text);font-weight:600}
    .bk-amount{font-size:.78rem;color:var(--g);font-weight:700;margin-top:4px}
    .bk-actions{display:flex;gap:8px;margin-top:10px}
    .btn-sm{border:none;border-radius:8px;padding:7px 14px;font-family:inherit;font-size:.75rem;font-weight:700;cursor:pointer}
    .btn-cancel{background:#fee2e2;color:#dc2626}
    .btn-rate{background:#f0fdf4;color:#065f46;border:1px solid #bbf7d0}
    .empty-state{text-align:center;padding:40px 16px;color:var(--muted)}
    .empty-icon{font-size:3rem;margin-bottom:12px}
    .btn-new{background:var(--g);color:#000;border:none;border-radius:12px;padding:12px 24px;font-family:inherit;font-weight:800;font-size:.9rem;cursor:pointer;margin-top:8px}
    .skel{background:linear-gradient(90deg,#f0f0f0 25%,#e8e8e8 50%,#f0f0f0 75%);background-size:200% 100%;animation:sk 1.4s infinite;border-radius:8px;height:80px;margin-bottom:10px}
    @keyframes sk{0%{background-position:200% 0}100%{background-position:-200% 0}}
    .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}
    .nav-item.active{color:var(--g)}.nav-icon{font-size:1.2rem}
  </style>
</head>
<body>
<header class="hdr">
  <div class="logo">📅 حجوزاتي</div>
  <a href="/app/dashboard.php" class="back">← الرئيسية</a>
</header>
<div class="tabs">
  <button class="tab-btn active" onclick="loadTab('upcoming',this)">القادمة</button>
  <button class="tab-btn" onclick="loadTab('completed',this)">المكتملة</button>
  <button class="tab-btn" onclick="loadTab('cancelled',this)">الملغية</button>
</div>
<div class="container">
  <div id="bookings-list">
    <div class="skel"></div><div class="skel"></div>
  </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/bookings.php"  class="nav-item active"><span class="nav-icon">📅</span><span>حجوزاتي</span></a>
  <a href="/wallet.php"        class="nav-item"><span class="nav-icon">💰</span><span>محفظة</span></a>
  <a href="/app/profile.php"   class="nav-item"><span class="nav-icon">👤</span><span>حسابي</span></a>
</nav>
<script>
const svcIcons={medical:'⚕️',legal:'⚖️',education:'🎓',pharmacy:'💊',engineering:'🔧',general:'📋'};
const statusLabel={confirmed:'مؤكد',pending:'قيد المراجعة',cancelled:'ملغي',completed:'مكتمل'};
const statusClass={confirmed:'status-confirmed',pending:'status-pending',cancelled:'status-cancelled',completed:'status-completed'};

async function loadTab(filter, btn) {
  document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active');
  const el = document.getElementById('bookings-list');
  el.innerHTML = '<div class="skel"></div><div class="skel"></div>';
  try {
    const statusMap={upcoming:'confirmed,pending',completed:'completed',cancelled:'cancelled'};
    const r = await fetch('/api/booking/status.php?filter='+filter);
    const d = await r.json();
    const bks = d.bookings || d.data || [];
    if (!bks.length) {
      el.innerHTML = '<div class="empty-state"><div class="empty-icon">📅</div><p>لا حجوزات في هذا القسم</p><button class="btn-new" onclick="window.location.href='/app/services.php'">احجز خدمة جديدة</button></div>';
      return;
    }
    el.innerHTML = bks.map(b=>`
      <div class="bk-card">
        <div class="bk-top">
          <div class="bk-service">${svcIcons[b.service_type]||'📋'} ${b.service_type||''}</div>
          <span class="bk-status ${statusClass[b.status]||''}">${statusLabel[b.status]||b.status}</span>
        </div>
        <div class="bk-provider">👤 ${b.provider_name||'المزود'}</div>
        <div class="bk-time">📅 ${formatDate(b.slot_time)}</div>
        ${b.amount_sdg?`<div class="bk-amount">💰 ${Number(b.amount_sdg).toLocaleString('ar-SA')} SDG</div>`:''}
        <div class="bk-actions">
          ${b.status==='pending'?`<button class="btn-sm btn-cancel" onclick="cancelBk(${b.id})">إلغاء</button>`:''}
          ${b.status==='completed'&&!b.rated?`<button class="btn-sm btn-rate" onclick="rateBk(${b.id})">⭐ قيِّم</button>`:''}
        </div>
      </div>`).join('');
  } catch(e) {
    el.innerHTML = '<p style="color:var(--muted);text-align:center;padding:20px">تعذّر التحميل</p>';
  }
}

function formatDate(dt) {
  if (!dt) return '';
  const d = new Date(dt.replace(' ','T'));
  return d.toLocaleDateString('ar-SA',{weekday:'long',day:'numeric',month:'long',hour:'2-digit',minute:'2-digit'});
}

async function cancelBk(id) {
  if (!confirm('هل تريد إلغاء هذا الحجز؟')) return;
  try {
    await fetch('/api/booking/create.php',{method:'DELETE',headers:{'Content-Type':'application/json'},body:JSON.stringify({booking_id:id})});
    loadTab('upcoming', document.querySelector('.tab-btn.active'));
  } catch(e) {}
}

function rateBk(id) { window.location.href='/app/flow.php?rate='+id; }

loadTab('upcoming', document.querySelector('.tab-btn.active'));

// ── Booking Payment ──────────────────────────────────────────
async function payBooking(bookingId, amount, pin) {
  const r = await fetch('/api/bookings/pay.php', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify({booking_id: bookingId, pin: pin})
  });
  const d = await r.json();
  if(d.ok) {
    alert('✅ تم الدفع بنجاح! المرجع: ' + d.txn_ref);
    location.reload();
  } else {
    alert('❌ ' + (d.message || d.error || 'حدث خطأ'));
  }
}
</script>
</body>
</html>