<?php
// ─────────────────────────────────────────────────────────────
//  admin/booking.php — Admin: Appointments + Calendar
// ─────────────────────────────────────────────────────────────
require_once dirname(__DIR__) . '/lib.php';
session_start_safe();
if (!admin_logged_in()) { header('Location: ' . APP_URL . '/admin.php'); exit; }
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
<title>Appointments — FormBuilder Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Syne:wght@600;700;800&family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet"/>
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:#f4f5f7;--surface:#fff;--card:#fff;--card-alt:#f8f9fb;
  --border:#e8eaed;--border-hi:#d1d5db;
  --accent:#e09500;--accent-hi:#f5a623;--accent-d:#b87800;
  --accent-pale:#fff8eb;--accent-glow:rgba(224,149,0,.18);--accent-border:rgba(224,149,0,.3);
  --green:#16a34a;--green-pale:#f0fdf4;--green-border:#bbf7d0;
  --red:#dc2626;--red-pale:#fef2f2;--red-border:#fecaca;
  --amber:#d97706;--amber-pale:#fffbeb;--amber-border:#fde68a;
  --blue:#2563eb;--blue-pale:#eff6ff;--blue-border:#bfdbfe;
  --text:#111827;--text-2:#4b5563;--text-3:#9ca3af;
  --font-display:'Syne',sans-serif;--font-body:'DM Sans',sans-serif;--font-mono:'DM Mono',monospace;
  --sidebar-w:240px;--header-h:58px;
}
html,body{min-height:100vh;background:var(--bg);color:var(--text);font-family:var(--font-body);-webkit-font-smoothing:antialiased;font-size:14px}
a{text-decoration:none;color:inherit}
button,input,select,textarea{font-family:inherit}

/* ── Topbar ── */
.topbar{position:fixed;top:0;left:0;right:0;height:58px;background:#fff;border-bottom:1px solid var(--border);
  display:flex;align-items:center;padding:0 20px;gap:12px;z-index:100;box-shadow:0 1px 3px rgba(0,0,0,.04)}
.topbar-logo{display:flex;align-items:center;gap:8px;font-family:var(--font-display);font-weight:800;font-size:14px;color:var(--text)}
.topbar-logo-icon{width:26px;height:26px;background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));border-radius:7px;display:flex;align-items:center;justify-content:center}
.topbar-logo-icon svg{width:12px;height:12px;stroke:#fff;fill:none;stroke-width:2.5;stroke-linecap:round;stroke-linejoin:round}
.topbar-divider{width:1px;height:20px;background:var(--border)}
.topbar-section{font-family:var(--font-mono);font-size:10px;color:var(--text-3);text-transform:uppercase;letter-spacing:.1em}
.topbar-title{font-family:var(--font-display);font-size:15px;font-weight:700;color:var(--text);flex:1}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 16px;border-radius:9px;font-size:13px;font-weight:600;border:none;cursor:pointer;transition:all .14s;white-space:nowrap;font-family:var(--font-body)}
.btn svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.btn-primary{background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));color:#fff;box-shadow:0 1px 8px var(--accent-glow)}
.btn-primary:hover{opacity:.92;transform:translateY(-1px)}
.btn-ghost{background:transparent;color:var(--text-2);border:1px solid var(--border-hi)}
.btn-ghost:hover{border-color:var(--accent);color:var(--accent);background:var(--accent-pale)}
.btn-sm{padding:6px 12px;font-size:12px;border-radius:7px}
.btn-danger{background:var(--red-pale);color:var(--red);border:1px solid var(--red-border)}

/* ── Shell ── */
.shell{display:flex;padding-top:58px;min-height:100vh}
.sidebar{width:var(--sidebar-w);background:#fff;border-right:1px solid var(--border);position:fixed;top:58px;bottom:0;overflow-y:auto;padding:16px 12px}
.nav-label{font-family:var(--font-mono);font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-3);padding:8px 8px 4px}
.nav-item{display:flex;align-items:center;gap:10px;padding:9px 10px;border-radius:9px;font-size:13px;font-weight:500;color:var(--text-2);cursor:pointer;transition:all .14s;margin-bottom:2px;border:none;background:none;width:100%;text-align:left}
.nav-item svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
.nav-item:hover{background:var(--bg);color:var(--text)}
.nav-item.active{background:var(--accent-pale);color:var(--accent);font-weight:600}
.content{flex:1;margin-left:var(--sidebar-w);padding:28px}

/* ── Page header ── */
.page-hdr{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:24px;flex-wrap:wrap}
.page-hdr-left h1{font-family:var(--font-display);font-size:22px;font-weight:800;color:var(--text);margin-bottom:4px}
.page-hdr-left p{color:var(--text-2);font-size:13px}

/* ── Filter bar ── */
.filter-bar{display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap;align-items:center}
.filter-bar input,.filter-bar select{background:#fff;border:1.5px solid var(--border-hi);border-radius:9px;padding:8px 12px;font-size:13px;color:var(--text);outline:none;transition:border .15s;font-family:inherit}
.filter-bar input:focus,.filter-bar select:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-pale)}
.filter-bar input{flex:1;min-width:200px}

/* ── Table ── */
.tbl-wrap{background:#fff;border:1px solid var(--border);border-radius:14px;overflow:hidden}
.tbl{width:100%;border-collapse:collapse}
.tbl thead th{padding:12px 16px;text-align:left;font-family:var(--font-mono);font-size:10px;text-transform:uppercase;letter-spacing:.06em;color:var(--text-3);border-bottom:1px solid var(--border);background:var(--card-alt)}
.tbl tbody tr{border-bottom:1px solid var(--border);transition:background .1s}
.tbl tbody tr:last-child{border-bottom:none}
.tbl tbody tr:hover{background:var(--bg)}
.tbl td{padding:12px 16px;font-size:13px;color:var(--text)}
.tbl td.muted{color:var(--text-2)}
.ref-pill{font-family:var(--font-mono);font-size:11px;background:var(--accent-pale);color:var(--accent);border:1px solid var(--accent-border);padding:2px 8px;border-radius:6px}

/* ── Badge ── */
.badge{display:inline-flex;align-items:center;gap:4px;padding:3px 8px;border-radius:20px;font-family:var(--font-mono);font-size:10px;font-weight:500;text-transform:uppercase;letter-spacing:.05em}
.badge::before{content:'●';font-size:5px}
.badge-green{background:var(--green-pale);color:var(--green);border:1px solid var(--green-border)}
.badge-yellow{background:var(--amber-pale);color:var(--amber);border:1px solid var(--amber-border)}
.badge-red{background:var(--red-pale);color:var(--red);border:1px solid var(--red-border)}
.badge-gray{background:var(--bg);color:var(--text-3);border:1px solid var(--border)}
.badge-blue{background:var(--blue-pale);color:var(--blue);border:1px solid var(--blue-border)}
.badge-amber{background:var(--accent-pale);color:var(--accent);border:1px solid var(--accent-border)}

/* ── Stats row ── */
.stats-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:14px;margin-bottom:24px}
.stat-card{background:#fff;border:1px solid var(--border);border-radius:12px;padding:16px}
.stat-num{font-family:var(--font-display);font-size:28px;font-weight:800;color:var(--text);line-height:1}
.stat-label{font-size:12px;color:var(--text-2);margin-top:4px}

/* ── Modal ── */
.modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:200;display:flex;align-items:center;justify-content:center;padding:16px;opacity:0;pointer-events:none;transition:opacity .2s}
.modal-bg.open{opacity:1;pointer-events:all}
.modal{background:#fff;border-radius:18px;width:100%;max-width:540px;max-height:90vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.15)}
.modal-hdr{padding:20px 24px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.modal-hdr h2{font-family:var(--font-display);font-size:16px;font-weight:800}
.modal-body{padding:24px}
.fg{margin-bottom:16px}
.fg label{display:block;font-size:11px;font-weight:600;color:var(--text-2);text-transform:uppercase;letter-spacing:.07em;margin-bottom:6px}
.fg input,.fg select,.fg textarea{width:100%;background:var(--bg);border:1.5px solid var(--border-hi);border-radius:9px;padding:10px 13px;font-size:13px;color:var(--text);outline:none;transition:border .15s;font-family:inherit}
.fg input:focus,.fg select:focus,.fg textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-pale)}
.modal-footer{padding:16px 24px;border-top:1px solid var(--border);display:flex;gap:10px;justify-content:flex-end}

/* ── Appt detail ── */
.detail-row{display:flex;gap:10px;padding:10px 0;border-bottom:1px solid var(--border)}
.detail-row:last-child{border-bottom:none}
.detail-key{font-size:12px;font-weight:600;color:var(--text-3);text-transform:uppercase;letter-spacing:.06em;width:120px;flex-shrink:0;padding-top:1px}
.detail-val{font-size:13px;color:var(--text)}

/* ── Pagination ── */
.pagination{display:flex;gap:8px;justify-content:center;align-items:center;margin-top:20px}
.page-btn{width:34px;height:34px;border-radius:8px;border:1px solid var(--border);background:#fff;font-size:13px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .14s;font-family:inherit}
.page-btn:hover{border-color:var(--accent);color:var(--accent)}
.page-btn.active{background:var(--accent);color:#fff;border-color:var(--accent)}
.page-btn:disabled{opacity:.4;cursor:default}

/* ── Empty ── */
.empty{text-align:center;padding:60px 20px;color:var(--text-3)}
.empty svg{width:48px;height:48px;stroke:var(--border-hi);fill:none;stroke-width:1.5;margin-bottom:14px}
.empty h3{font-size:15px;color:var(--text-2);margin-bottom:6px}

/* ── Toast ── */
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%) translateY(14px);background:var(--text);color:#fff;padding:10px 18px 10px 13px;border-radius:999px;font-size:13px;font-weight:500;z-index:999;opacity:0;transition:all .28s cubic-bezier(.34,1.56,.64,1);pointer-events:none;white-space:nowrap;box-shadow:0 4px 20px rgba(0,0,0,.18);display:flex;align-items:center;gap:8px}
.toast-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
.toast.ok .toast-dot{background:#4ade80}
.toast.err .toast-dot{background:#f87171}
.toast.warn .toast-dot{background:var(--accent-hi)}
.spinner{display:inline-block;width:18px;height:18px;border:2px solid var(--accent-pale);border-top-color:var(--accent);border-radius:50%;animation:spin .7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}

@media(max-width:900px){.sidebar{display:none}.content{margin-left:0}}
@media(max-width:640px){.stats-row{grid-template-columns:1fr 1fr}.filter-bar input{min-width:120px}}
</style>
</head>
<body>

<!-- Topbar -->
<div class="topbar">
  <a href="<?= APP_URL ?>/admin.php" class="topbar-logo">
    <div class="topbar-logo-icon">
      <svg viewBox="0 0 24 24"><path d="M9 12h6M9 16h6M9 8h6M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
    </div>
    FormBuilder
  </a>
  <div class="topbar-divider"></div>
  <span class="topbar-section">Booking</span>
  <span class="topbar-title">Appointments</span>
  <a href="<?= APP_URL ?>/admin.php" class="btn btn-ghost btn-sm">← Dashboard</a>
</div>

<div class="shell">
  <!-- Sidebar nav -->
  <nav class="sidebar">
    <div class="nav-label">Booking</div>
    <button class="nav-item active" id="navAppts" onclick="showSection('appointments')">
      <svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>
      Appointments
    </button>
    <button class="nav-item" id="navMembers" onclick="showSection('memberships')">
      <svg viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
      Memberships
    </button>
    <button class="nav-item" id="navPlans" onclick="window.location='<?= APP_URL ?>/admin/booking-plans.php'">
      <svg viewBox="0 0 24 24"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>
      Plans
    </button>
    <button class="nav-item" id="navServices" onclick="window.location='<?= APP_URL ?>/admin/booking-services.php'">
      <svg viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
      Services
    </button>
    <button class="nav-item" id="navProviders" onclick="window.location='<?= APP_URL ?>/admin/booking-providers.php'">
      <svg viewBox="0 0 24 24"><circle cx="9" cy="7" r="4"/><path d="M3 20v-2a4 4 0 014-4h4a4 4 0 014 4v2M16 3.13a4 4 0 010 7.75"/><path d="M21 20v-2a4 4 0 00-3-3.87"/></svg>
      Providers
    </button>
  </nav>

  <main class="content">

    <!-- ── APPOINTMENTS SECTION ── -->
    <div id="sectionAppointments">
      <div class="page-hdr">
        <div class="page-hdr-left">
          <h1>Appointments</h1>
          <p>View and manage all bookings</p>
        </div>
      </div>

      <!-- Stats row -->
      <div class="stats-row" id="statsRow">
        <div class="stat-card"><div class="stat-num" id="statToday">…</div><div class="stat-label">Today</div></div>
        <div class="stat-card"><div class="stat-num" id="statWeek">…</div><div class="stat-label">This Week</div></div>
        <div class="stat-card"><div class="stat-num" id="statPending">…</div><div class="stat-label">Pending Today</div></div>
        <div class="stat-card"><div class="stat-num" id="statTotal">…</div><div class="stat-label">Total</div></div>
      </div>

      <!-- Filters -->
      <div class="filter-bar">
        <input type="date" id="filterDate" onchange="loadAppointments()"/>
        <select id="filterStatus" onchange="loadAppointments()">
          <option value="">All statuses</option>
          <option>pending</option><option>confirmed</option><option>completed</option>
          <option>cancelled</option><option>no_show</option>
        </select>
        <select id="filterProvider" onchange="loadAppointments()">
          <option value="">All providers</option>
        </select>
        <button class="btn btn-ghost btn-sm" onclick="document.getElementById('filterDate').value='';document.getElementById('filterStatus').value='';document.getElementById('filterProvider').value='';loadAppointments()">Clear</button>
      </div>

      <div class="tbl-wrap">
        <table class="tbl">
          <thead><tr>
            <th>Ref</th><th>Customer</th><th>Service</th><th>Provider</th>
            <th>Date & Time</th><th>Status</th><th></th>
          </tr></thead>
          <tbody id="apptTbody">
            <tr><td colspan="7" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr>
          </tbody>
        </table>
      </div>
      <div id="apptPagination" class="pagination"></div>
    </div>

    <!-- ── MEMBERSHIPS SECTION ── -->
    <div id="sectionMemberships" style="display:none">
      <div class="page-hdr">
        <div class="page-hdr-left">
          <h1>Memberships</h1>
          <p>Manage customer membership access</p>
        </div>
        <button class="btn btn-primary" onclick="openGrantModal()">
          <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
          Grant Membership
        </button>
      </div>

      <div class="filter-bar">
        <input type="text" id="memSearch" placeholder="Search by name or email…" oninput="loadMemberships()"/>
        <select id="memStatus" onchange="loadMemberships()">
          <option value="">All</option>
          <option value="active">Active</option>
          <option value="expired">Expired</option>
          <option value="cancelled">Cancelled</option>
        </select>
      </div>

      <div class="tbl-wrap">
        <table class="tbl">
          <thead><tr>
            <th>Customer</th><th>Plan</th><th>Expires</th><th>Activated</th><th>Status</th><th></th>
          </tr></thead>
          <tbody id="memTbody">
            <tr><td colspan="6" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr>
          </tbody>
        </table>
      </div>
      <div id="memPagination" class="pagination"></div>
    </div>

  </main>
</div>

<!-- Appointment Detail Modal -->
<div class="modal-bg" id="apptModal">
  <div class="modal">
    <div class="modal-hdr">
      <h2>Appointment Details</h2>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('apptModal')">✕</button>
    </div>
    <div class="modal-body" id="apptModalBody"></div>
    <div class="modal-footer">
      <select id="statusSelect" class="btn btn-ghost btn-sm" style="padding:6px 12px">
        <option value="pending">Pending</option>
        <option value="confirmed">Confirmed</option>
        <option value="completed">Completed</option>
        <option value="cancelled">Cancelled</option>
        <option value="no_show">No Show</option>
      </select>
      <button class="btn btn-primary btn-sm" onclick="updateApptStatus()">Save Status</button>
      <button class="btn btn-danger btn-sm" onclick="deleteAppt()">Delete</button>
    </div>
  </div>
</div>

<!-- Grant Membership Modal -->
<div class="modal-bg" id="grantModal">
  <div class="modal">
    <div class="modal-hdr">
      <h2>Grant Membership</h2>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('grantModal')">✕</button>
    </div>
    <div class="modal-body">
      <div class="fg">
        <label>Customer Email</label>
        <input type="email" id="grantEmail" placeholder="customer@email.com"/>
      </div>
      <div class="fg">
        <label>Plan</label>
        <select id="grantPlan"></select>
      </div>
      <div class="fg">
        <label>Start Date</label>
        <input type="datetime-local" id="grantStart"/>
      </div>
      <div class="fg">
        <label>Notes (optional)</label>
        <textarea id="grantNotes" rows="2" placeholder="Internal notes…"></textarea>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-ghost btn-sm" onclick="closeModal('grantModal')">Cancel</button>
      <button class="btn btn-primary" onclick="submitGrant()">Grant Access</button>
    </div>
  </div>
</div>

<!-- Toast -->
<div class="toast" id="toast"><div class="toast-dot"></div><span id="toastMsg"></span></div>

<script>
const BASE = <?= json_encode(APP_URL, JSON_HEX_TAG|JSON_HEX_QUOT|JSON_HEX_AMP|JSON_HEX_APOS) ?>;
const BK = BASE + '/api/booking';
let currentApptId = null;
let currentPage = 1;

function toast(msg, type='ok') {
  const t = document.getElementById('toast');
  t.className = 'toast ' + type;
  document.getElementById('toastMsg').textContent = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 2800);
}

function showSection(sec) {
  document.getElementById('sectionAppointments').style.display = sec === 'appointments' ? '' : 'none';
  document.getElementById('sectionMemberships').style.display = sec === 'memberships' ? '' : 'none';
  document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));
  document.getElementById('navAppts').classList.toggle('active', sec === 'appointments');
  document.getElementById('navMembers').classList.toggle('active', sec === 'memberships');
  if (sec === 'memberships') loadMemberships();
}

function openModal(id) { document.getElementById(id).classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }

function statusBadge(s) {
  const map = {pending:'badge-yellow',confirmed:'badge-green',completed:'badge-blue',cancelled:'badge-red',no_show:'badge-gray'};
  return `<span class="badge ${map[s]||'badge-gray'}">${s}</span>`;
}

function formatDt(dt) {
  if (!dt) return '—';
  const d = new Date(dt);
  return d.toLocaleDateString('en-GB', {day:'2-digit',month:'short',year:'numeric'}) + ' ' +
         d.toLocaleTimeString('en-GB', {hour:'2-digit',minute:'2-digit'});
}

// ── Stats ────────────────────────────────────────────────────
async function loadStats() {
  try {
    const r = await fetch(BK + '/admin/stats', {credentials:'same-origin'});
    const d = await r.json();
    if (d.ok) {
      document.getElementById('statToday').textContent = d.today;
      document.getElementById('statWeek').textContent = d.this_week;
      document.getElementById('statPending').textContent = d.pending_today;
      document.getElementById('statTotal').textContent = d.total_appointments;
    }
  } catch(e) {}
}

// ── Appointments ──────────────────────────────────────────────
async function loadAppointments(page = 1) {
  currentPage = page;
  const date     = document.getElementById('filterDate').value;
  const status   = document.getElementById('filterStatus').value;
  const provider = document.getElementById('filterProvider').value;
  const params   = new URLSearchParams();
  if (date) params.set('date', date);
  if (status) params.set('status', status);
  if (provider) params.set('provider_id', provider);
  params.set('page', page);

  const tbody = document.getElementById('apptTbody');
  tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr>';

  try {
    const r = await fetch(BK + '/admin/appointments?' + params, {credentials:'same-origin'});
    const d = await r.json();
    if (!d.ok) { tbody.innerHTML = `<tr><td colspan="7" class="muted" style="text-align:center;padding:40px">Error: ${d.error}</td></tr>`; return; }

    if (!d.appointments.length) {
      tbody.innerHTML = '<tr><td colspan="7"><div class="empty"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg><h3>No appointments found</h3></div></td></tr>';
    } else {
      tbody.innerHTML = d.appointments.map(a => `
        <tr>
          <td><span class="ref-pill">${a.ref}</span></td>
          <td><strong>${esc(a.customer_name)}</strong><br><span style="color:var(--text-3);font-size:12px">${esc(a.customer_email)}</span></td>
          <td>${esc(a.service_name)}</td>
          <td>${esc(a.provider_name)}</td>
          <td>${formatDt(a.start_datetime)}</td>
          <td>${statusBadge(a.status)}</td>
          <td><button class="btn btn-ghost btn-sm" onclick="openAppt(${a.id})">View</button></td>
        </tr>`).join('');
    }

    // Pagination
    const pg = document.getElementById('apptPagination');
    pg.innerHTML = '';
    if (d.pages > 1) {
      for (let i = 1; i <= d.pages; i++) {
        const b = document.createElement('button');
        b.className = 'page-btn' + (i === page ? ' active' : '');
        b.textContent = i;
        b.onclick = () => loadAppointments(i);
        pg.appendChild(b);
      }
    }
  } catch(e) {
    tbody.innerHTML = '<tr><td colspan="7" class="muted" style="text-align:center;padding:30px">Failed to load</td></tr>';
  }
}

async function openAppt(id) {
  currentApptId = id;
  document.getElementById('apptModalBody').innerHTML = '<div style="text-align:center;padding:30px"><div class="spinner"></div></div>';
  openModal('apptModal');
  try {
    const r = await fetch(BK + '/admin/appointments/' + id, {credentials:'same-origin'});
    const d = await r.json();
    if (!d.ok) return;
    const a = d.appointment;
    document.getElementById('statusSelect').value = a.status;
    document.getElementById('apptModalBody').innerHTML = `
      <div class="detail-row"><div class="detail-key">Reference</div><div class="detail-val"><span class="ref-pill">${a.ref}</span></div></div>
      <div class="detail-row"><div class="detail-key">Customer</div><div class="detail-val"><strong>${esc(a.customer_name)}</strong><br>${esc(a.customer_email)}${a.customer_phone ? '<br>' + esc(a.customer_phone) : ''}</div></div>
      <div class="detail-row"><div class="detail-key">Service</div><div class="detail-val">${esc(a.service_name)} (${a.duration_min} min)</div></div>
      <div class="detail-row"><div class="detail-key">Provider</div><div class="detail-val">${esc(a.provider_name)}</div></div>
      <div class="detail-row"><div class="detail-key">Date & Time</div><div class="detail-val"><strong>${formatDt(a.start_datetime)}</strong> → ${formatDt(a.end_datetime)}</div></div>
      <div class="detail-row"><div class="detail-key">Status</div><div class="detail-val">${statusBadge(a.status)}</div></div>
      ${a.notes ? `<div class="detail-row"><div class="detail-key">Notes</div><div class="detail-val">${esc(a.notes)}</div></div>` : ''}
      <div class="detail-row"><div class="detail-key">Booked</div><div class="detail-val">${formatDt(a.created_at)}</div></div>`;
  } catch(e) {}
}

async function updateApptStatus() {
  const status = document.getElementById('statusSelect').value;
  try {
    const r = await fetch(BK + '/admin/appointments/' + currentApptId, {
      method:'PUT', credentials:'same-origin',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({status})
    });
    const d = await r.json();
    if (d.ok) { toast('Status updated'); closeModal('apptModal'); loadAppointments(currentPage); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

async function deleteAppt() {
  if (!confirm('Delete this appointment? This cannot be undone.')) return;
  try {
    const r = await fetch(BK + '/admin/appointments/' + currentApptId, {
      method:'DELETE', credentials:'same-origin'
    });
    const d = await r.json();
    if (d.ok) { toast('Deleted'); closeModal('apptModal'); loadAppointments(currentPage); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

// ── Memberships ───────────────────────────────────────────────
let memPage = 1;
let memSearchTimer = null;

async function loadMemberships(page = 1) {
  memPage = page;
  const search = document.getElementById('memSearch').value;
  const status = document.getElementById('memStatus').value;
  const params = new URLSearchParams({page});
  if (search) params.set('search', search);
  if (status) params.set('status', status);

  const tbody = document.getElementById('memTbody');
  tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr>';

  try {
    const r = await fetch(BK + '/admin/memberships?' + params, {credentials:'same-origin'});
    const d = await r.json();
    if (!d.ok) return;

    if (!d.memberships.length) {
      tbody.innerHTML = '<tr><td colspan="6"><div class="empty"><svg viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg><h3>No memberships found</h3></div></td></tr>';
    } else {
      tbody.innerHTML = d.memberships.map(m => {
        const active = m.status === 'active' && new Date(m.expires_at) > new Date();
        return `
          <tr>
            <td><strong>${esc(m.customer_name)}</strong><br><span style="color:var(--text-3);font-size:12px">${esc(m.customer_email)}</span></td>
            <td>${esc(m.plan_name)}</td>
            <td>${formatDt(m.expires_at)}</td>
            <td><span style="font-family:var(--font-mono);font-size:11px">${m.activated_by}</span></td>
            <td>${active ? '<span class="badge badge-green">active</span>' : '<span class="badge badge-red">expired</span>'}</td>
            <td><button class="btn btn-danger btn-sm" onclick="cancelMembership(${m.id})">Cancel</button></td>
          </tr>`;
      }).join('');
    }

    // Pagination
    const pg = document.getElementById('memPagination');
    pg.innerHTML = '';
    if (d.pages > 1) {
      for (let i = 1; i <= d.pages; i++) {
        const b = document.createElement('button');
        b.className = 'page-btn' + (i === page ? ' active' : '');
        b.textContent = i;
        b.onclick = () => loadMemberships(i);
        pg.appendChild(b);
      }
    }
  } catch(e) {}
}

document.getElementById('memSearch').addEventListener('input', () => {
  clearTimeout(memSearchTimer);
  memSearchTimer = setTimeout(() => loadMemberships(), 400);
});

async function cancelMembership(id) {
  if (!confirm('Cancel this membership?')) return;
  try {
    const r = await fetch(BK + '/admin/memberships/' + id, {
      method:'PUT', credentials:'same-origin',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({status:'cancelled'})
    });
    const d = await r.json();
    if (d.ok) { toast('Membership cancelled'); loadMemberships(memPage); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

// ── Grant Membership ─────────────────────────────────────────
async function openGrantModal() {
  // Load plans into select
  try {
    const r = await fetch(BK + '/admin/plans', {credentials:'same-origin'});
    const d = await r.json();
    const sel = document.getElementById('grantPlan');
    sel.innerHTML = d.plans.map(p => `<option value="${p.id}">${esc(p.name)} — $${parseFloat(p.price).toFixed(2)} / ${p.duration_days}d</option>`).join('');
  } catch(e) {}
  // Default start to now
  const now = new Date();
  now.setSeconds(0,0);
  document.getElementById('grantStart').value = now.toISOString().slice(0,16);
  openModal('grantModal');
}

async function submitGrant() {
  const email    = document.getElementById('grantEmail').value.trim();
  const planId   = document.getElementById('grantPlan').value;
  const startsAt = document.getElementById('grantStart').value.replace('T', ' ') + ':00';
  const notes    = document.getElementById('grantNotes').value;
  if (!email || !planId) { toast('Email and plan required', 'err'); return; }
  try {
    const r = await fetch(BK + '/admin/memberships', {
      method:'POST', credentials:'same-origin',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({customer_email:email, plan_id:parseInt(planId), starts_at:startsAt, notes})
    });
    const d = await r.json();
    if (d.ok) { toast('Membership granted'); closeModal('grantModal'); loadMemberships(); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

// ── Load providers for filter ─────────────────────────────────
async function loadProviderFilter() {
  try {
    const r = await fetch(BK + '/admin/providers', {credentials:'same-origin'});
    const d = await r.json();
    const sel = document.getElementById('filterProvider');
    (d.providers||[]).forEach(p => {
      const o = document.createElement('option');
      o.value = p.id; o.textContent = p.name;
      sel.appendChild(o);
    });
  } catch(e) {}
}

function esc(s) {
  if (s == null) return '';
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// Close modals on bg click
document.querySelectorAll('.modal-bg').forEach(el => el.addEventListener('click', e => {
  if (e.target === el) el.classList.remove('open');
}));

// Init
loadStats();
loadAppointments();
loadProviderFilter();
</script>
</body>
</html>
