<?php
// ─────────────────────────────────────────────────────────────
//  admin/booking-services.php — Admin: Services Management
// ─────────────────────────────────────────────────────────────
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>Services — 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;
  --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;
}
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}

/* ── Buttons ──────────────────────────────────────────────── */
.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)}

/* ── Layout ───────────────────────────────────────────────── */
.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}

/* ── Services table ──────────────────────────────────────── */
.tbl-wrap{background:#fff;border:1px solid var(--border);border-radius:14px;overflow:hidden}
.tbl-toolbar{padding:14px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px}
.tbl-search{flex:1;background:var(--bg);border:1.5px solid var(--border-hi);border-radius:9px;padding:8px 13px;font-size:13px;color:var(--text);outline:none;transition:border .15s}
.tbl-search:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-pale)}
.tbl{width:100%;border-collapse:collapse}
.tbl th{padding:10px 16px;text-align:left;font-family:var(--font-mono);font-size:10px;font-weight:500;color:var(--text-3);text-transform:uppercase;letter-spacing:.07em;border-bottom:1px solid var(--border);white-space:nowrap}
.tbl td{padding:13px 16px;border-bottom:1px solid var(--border);vertical-align:middle}
.tbl tr:last-child td{border-bottom:none}
.tbl tr:hover td{background:var(--bg)}
.svc-color-dot{width:32px;height:32px;border-radius:8px;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0}
.svc-color-dot svg{width:15px;height:15px;stroke:#fff;fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.svc-name-cell{display:flex;align-items:center;gap:10px}
.svc-name{font-weight:600;color:var(--text);font-size:13px}
.svc-desc{font-size:12px;color:var(--text-3);margin-top:1px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;max-width:240px}
.code-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}

/* ── Badges ──────────────────────────────────────────────── */
.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-red{background:var(--red-pale);color:var(--red);border:1px solid var(--red-border)}
.badge-amber{background:var(--accent-pale);color:var(--accent);border:1px solid var(--accent-border)}
.badge-gray{background:var(--bg);color:var(--text-3);border:1px solid var(--border)}

/* ── 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:520px;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}
.modal-footer{padding:16px 24px;border-top:1px solid var(--border);display:flex;gap:10px;justify-content:flex-end}

/* ── Form fields ─────────────────────────────────────────── */
.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,box-shadow .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)}
.fg .hint{font-size:11px;color:var(--text-3);margin-top:4px}
.fg-row{display:flex;gap:12px}
.fg-row .fg{flex:1;margin-bottom:0}

/* ── Color picker row ────────────────────────────────────── */
.color-swatches{display:flex;gap:8px;flex-wrap:wrap;margin-top:4px}
.color-swatch{width:28px;height:28px;border-radius:7px;cursor:pointer;border:2px solid transparent;transition:all .14s;flex-shrink:0}
.color-swatch.active{border-color:var(--text);transform:scale(1.15)}
.color-custom-wrap{display:flex;align-items:center;gap:8px;margin-top:8px}
.color-custom-wrap input[type=color]{width:32px;height:32px;border:1.5px solid var(--border-hi);border-radius:7px;padding:2px;cursor:pointer;background:var(--bg)}
.color-custom-wrap span{font-size:12px;color:var(--text-2)}

/* ── Toggle ──────────────────────────────────────────────── */
.toggle-row{display:flex;align-items:center;justify-content:space-between;padding:12px 0;border-top:1px solid var(--border);margin-top:4px}
.toggle-row:first-child{border-top:none;margin-top:0}
.toggle-label{font-size:13px;color:var(--text);font-weight:500}
.toggle-hint{font-size:11px;color:var(--text-3);margin-top:1px}
.toggle-btn{width:44px;height:24px;border-radius:12px;border:none;cursor:pointer;position:relative;transition:background .2s;flex-shrink:0}
.toggle-btn.on{background:var(--green)}
.toggle-btn.off{background:var(--border-hi)}
.toggle-btn::after{content:'';position:absolute;width:18px;height:18px;background:#fff;border-radius:50%;top:3px;transition:left .2s;box-shadow:0 1px 3px rgba(0,0,0,.2)}
.toggle-btn.on::after{left:23px}
.toggle-btn.off::after{left:3px}

/* ── Toast / Spinner ─────────────────────────────────────── */
.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}
.spinner{display:inline-block;width:20px;height:20px;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)}}
.empty{text-align:center;padding:60px 20px;color:var(--text-3)}
.empty svg{margin-bottom:14px}
.empty h3{font-family:var(--font-display);font-size:16px;font-weight:700;color:var(--text-2);margin-bottom:6px}
.empty p{font-size:13px}

/* ── Stats bar ───────────────────────────────────────────── */
.stats-bar{display:flex;gap:12px;margin-bottom:22px;flex-wrap:wrap}
.stat-pill{background:#fff;border:1px solid var(--border);border-radius:10px;padding:10px 16px;display:flex;align-items:center;gap:10px;font-size:13px}
.stat-pill-num{font-family:var(--font-display);font-size:20px;font-weight:800;color:var(--text);line-height:1}
.stat-pill-label{font-size:11px;color:var(--text-3);font-family:var(--font-mono);text-transform:uppercase;letter-spacing:.05em}

/* ── Responsive ──────────────────────────────────────────── */
@media(max-width:900px){.sidebar{display:none}.content{margin-left:0;padding:20px}}
@media(max-width:640px){
  .content{padding:16px}
  .tbl th:nth-child(3),.tbl td:nth-child(3){display:none}
  .tbl th:nth-child(4),.tbl td:nth-child(4){display:none}
  .svc-desc{display:none}
  .fg-row{flex-direction:column}
  .fg input,.fg select,.fg textarea{font-size:16px}
}
</style>
</head>
<body>

<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">Services</span>
  <a href="<?= APP_URL ?>/admin.php" class="btn btn-ghost btn-sm">← Dashboard</a>
</div>

<div class="shell">
  <nav class="sidebar">
    <div class="nav-label">Booking</div>
    <button class="nav-item" onclick="window.location='<?= APP_URL ?>/admin/booking.php'">
      <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" onclick="window.location='<?= APP_URL ?>/admin/booking.php'">
      <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" 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 active">
      <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" 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">

    <div class="page-hdr">
      <div class="page-hdr-left">
        <h1>Services</h1>
        <p>Define bookable services, set duration and access restrictions</p>
      </div>
      <button class="btn btn-primary" onclick="openSvcModal(null)">
        <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
        New Service
      </button>
    </div>

    <!-- Stats bar -->
    <div class="stats-bar" id="statsBar" style="display:none">
      <div class="stat-pill">
        <div>
          <div class="stat-pill-num" id="statTotal">—</div>
          <div class="stat-pill-label">Total</div>
        </div>
      </div>
      <div class="stat-pill">
        <div>
          <div class="stat-pill-num" id="statActive">—</div>
          <div class="stat-pill-label">Active</div>
        </div>
      </div>
      <div class="stat-pill">
        <div>
          <div class="stat-pill-num" id="statMembers">—</div>
          <div class="stat-pill-label">Members Only</div>
        </div>
      </div>
      <div class="stat-pill">
        <div>
          <div class="stat-pill-num" id="statPublic">—</div>
          <div class="stat-pill-label">Public</div>
        </div>
      </div>
    </div>

    <!-- Table -->
    <div class="tbl-wrap">
      <div class="tbl-toolbar">
        <input type="search" class="tbl-search" id="searchInput" placeholder="Search services…" oninput="filterServices()"/>
        <select id="filterStatus" onchange="filterServices()" style="background:var(--bg);border:1.5px solid var(--border-hi);border-radius:9px;padding:8px 12px;font-size:13px;color:var(--text);outline:none;cursor:pointer">
          <option value="">All Status</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
        <select id="filterAccess" onchange="filterServices()" style="background:var(--bg);border:1.5px solid var(--border-hi);border-radius:9px;padding:8px 12px;font-size:13px;color:var(--text);outline:none;cursor:pointer">
          <option value="">All Access</option>
          <option value="members">Members Only</option>
          <option value="public">Public</option>
        </select>
      </div>
      <table class="tbl">
        <thead>
          <tr>
            <th>Service</th>
            <th>Duration</th>
            <th>Access</th>
            <th>Status</th>
            <th style="width:80px"></th>
          </tr>
        </thead>
        <tbody id="svcTableBody">
          <tr><td colspan="5" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr>
        </tbody>
      </table>
    </div>

  </main>
</div>

<!-- Service Modal -->
<div class="modal-bg" id="svcModal">
  <div class="modal">
    <div class="modal-hdr">
      <h2 id="svcModalTitle">New Service</h2>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('svcModal')">✕</button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="svcId"/>

      <div class="fg">
        <label>Service Name</label>
        <input type="text" id="svcName" placeholder="e.g. Aqua Combat Training"/>
      </div>

      <div class="fg">
        <label>Description <span style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--text-3)">(optional)</span></label>
        <textarea id="svcDesc" rows="2" placeholder="Brief description shown to customers…"></textarea>
      </div>

      <div class="fg-row">
        <div class="fg">
          <label>Duration (minutes)</label>
          <input type="number" id="svcDuration" value="60" min="5" step="5" placeholder="60"/>
          <div class="hint">Slots will be generated based on this duration</div>
        </div>
        <div class="fg">
          <label>Color</label>
          <div class="color-swatches" id="colorSwatches"></div>
          <div class="color-custom-wrap">
            <input type="color" id="svcColorPicker" value="#e09500"/>
            <span>Custom color</span>
          </div>
        </div>
      </div>

      <div class="toggle-row">
        <div>
          <div class="toggle-label">Members Only</div>
          <div class="toggle-hint">Require an active membership to book this service</div>
        </div>
        <button type="button" class="toggle-btn on" id="svcRestricted" onclick="toggleField('svcRestricted')"></button>
      </div>

      <div class="toggle-row">
        <div>
          <div class="toggle-label">Active</div>
          <div class="toggle-hint">Show this service in the booking widget</div>
        </div>
        <button type="button" class="toggle-btn on" id="svcActive" onclick="toggleField('svcActive')"></button>
      </div>

    </div>
    <div class="modal-footer">
      <button class="btn btn-danger btn-sm" id="svcDeleteBtn" style="margin-right:auto;display:none" onclick="deleteSvc()">Delete</button>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('svcModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveSvc()">
        <svg viewBox="0 0 24 24"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
        Save Service
      </button>
    </div>
  </div>
</div>

<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';
const CSRF_TOKEN='<?= csrf_token() ?>';
function csrfFetch(url,opts={}){
  const m=(opts.method||'GET').toUpperCase();
  const h={'Content-Type':'application/json',...(opts.headers||{})};
  if(['POST','PUT','PATCH','DELETE'].includes(m)) h['X-CSRF-Token']=CSRF_TOKEN;
  return fetch(url,{credentials:'same-origin',...opts,headers:h});
}

const PRESET_COLORS = [
  '#e09500','#f5a623','#16a34a','#2563eb','#7c3aed',
  '#db2777','#dc2626','#0891b2','#059669','#9333ea'
];

let allServices = [];

// ── Utilities ──────────────────────────────────────────────────
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 openModal(id) { document.getElementById(id).classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }

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

function toggleField(id) {
  const btn = document.getElementById(id);
  const isOn = btn.classList.contains('on');
  btn.classList.toggle('on', !isOn);
  btn.classList.toggle('off', isOn);
}

function setToggle(id, val) {
  const btn = document.getElementById(id);
  btn.classList.toggle('on', !!val);
  btn.classList.toggle('off', !val);
}

function getToggle(id) {
  return document.getElementById(id).classList.contains('on') ? 1 : 0;
}

// ── Color picker ───────────────────────────────────────────────
function buildColorSwatches(currentColor) {
  const wrap = document.getElementById('colorSwatches');
  wrap.innerHTML = PRESET_COLORS.map(c => `
    <div class="color-swatch ${c === currentColor ? 'active' : ''}"
         style="background:${c}"
         data-color="${c}"
         onclick="selectSwatch(this, '${c}')"></div>
  `).join('');
  document.getElementById('svcColorPicker').value = currentColor || '#e09500';
}

function selectSwatch(el, color) {
  document.querySelectorAll('#colorSwatches .color-swatch').forEach(s => s.classList.remove('active'));
  el.classList.add('active');
  document.getElementById('svcColorPicker').value = color;
}

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('svcColorPicker').addEventListener('input', function() {
    document.querySelectorAll('#colorSwatches .color-swatch').forEach(s => s.classList.remove('active'));
  });
});

function getSelectedColor() {
  const active = document.querySelector('#colorSwatches .color-swatch.active');
  return active ? active.dataset.color : document.getElementById('svcColorPicker').value;
}

// ── Load & render ──────────────────────────────────────────────
async function loadServices() {
  try {
    const r = await fetch(BK + '/admin/services', {credentials: 'same-origin'});
    const d = await r.json();
    allServices = d.services || [];
    renderTable(allServices);
    renderStats(allServices);
  } catch(e) {
    document.getElementById('svcTableBody').innerHTML =
      '<tr><td colspan="5"><div class="empty"><h3>Failed to load</h3><p>Check your connection and try again</p></div></td></tr>';
  }
}

function renderStats(svcs) {
  const bar = document.getElementById('statsBar');
  bar.style.display = 'flex';
  document.getElementById('statTotal').textContent = svcs.length;
  document.getElementById('statActive').textContent = svcs.filter(s => s.is_active == 1).length;
  document.getElementById('statMembers').textContent = svcs.filter(s => s.is_restricted == 1).length;
  document.getElementById('statPublic').textContent = svcs.filter(s => s.is_restricted == 0).length;
}

function filterServices() {
  const q = document.getElementById('searchInput').value.toLowerCase();
  const st = document.getElementById('filterStatus').value;
  const ac = document.getElementById('filterAccess').value;
  const filtered = allServices.filter(s => {
    if (q && !s.name.toLowerCase().includes(q) && !(s.description||'').toLowerCase().includes(q)) return false;
    if (st === 'active' && s.is_active != 1) return false;
    if (st === 'inactive' && s.is_active != 0) return false;
    if (ac === 'members' && s.is_restricted != 1) return false;
    if (ac === 'public' && s.is_restricted != 0) return false;
    return true;
  });
  renderTable(filtered);
}

function renderTable(svcs) {
  const tbody = document.getElementById('svcTableBody');
  if (!svcs.length) {
    tbody.innerHTML = `
      <tr><td colspan="5">
        <div class="empty">
          <svg viewBox="0 0 24 24" style="width:48px;height:48px;stroke:var(--border-hi);fill:none;stroke-width:1.5;display:block;margin:0 auto">
            <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>
          <h3>No services found</h3>
          <p>Add your first service to get started</p>
        </div>
      </td></tr>`;
    return;
  }
  tbody.innerHTML = svcs.map(s => `
    <tr>
      <td>
        <div class="svc-name-cell">
          <div class="svc-color-dot" style="background:${esc(s.color)}">
            <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>
          </div>
          <div>
            <div class="svc-name">${esc(s.name)}</div>
            ${s.description ? `<div class="svc-desc">${esc(s.description)}</div>` : ''}
          </div>
        </div>
      </td>
      <td><span class="code-pill">${s.duration_min} min</span></td>
      <td>
        <span class="badge ${s.is_restricted ? 'badge-amber' : 'badge-gray'}">
          ${s.is_restricted ? 'Members' : 'Public'}
        </span>
      </td>
      <td>
        <span class="badge ${s.is_active ? 'badge-green' : 'badge-red'}">
          ${s.is_active ? 'Active' : 'Off'}
        </span>
      </td>
      <td>
        <button class="btn btn-ghost btn-sm" onclick="openSvcModal(${s.id})">Edit</button>
      </td>
    </tr>`).join('');
}

// ── Service modal ──────────────────────────────────────────────
function openSvcModal(id) {
  if (!id) {
    document.getElementById('svcModalTitle').textContent = 'New Service';
    document.getElementById('svcId').value = '';
    document.getElementById('svcName').value = '';
    document.getElementById('svcDesc').value = '';
    document.getElementById('svcDuration').value = '60';
    buildColorSwatches('#e09500');
    setToggle('svcRestricted', true);
    setToggle('svcActive', true);
    document.getElementById('svcDeleteBtn').style.display = 'none';
  } else {
    const svc = allServices.find(s => s.id == id);
    if (!svc) return;
    document.getElementById('svcModalTitle').textContent = 'Edit Service';
    document.getElementById('svcId').value = svc.id;
    document.getElementById('svcName').value = svc.name;
    document.getElementById('svcDesc').value = svc.description || '';
    document.getElementById('svcDuration').value = svc.duration_min;
    buildColorSwatches(svc.color || '#e09500');
    setToggle('svcRestricted', svc.is_restricted == 1);
    setToggle('svcActive', svc.is_active == 1);
    document.getElementById('svcDeleteBtn').style.display = '';
  }
  openModal('svcModal');
}

async function saveSvc() {
  const id       = document.getElementById('svcId').value;
  const name     = document.getElementById('svcName').value.trim();
  const desc     = document.getElementById('svcDesc').value.trim();
  const duration = parseInt(document.getElementById('svcDuration').value) || 60;
  const color    = getSelectedColor();
  const restr    = getToggle('svcRestricted');
  const active   = getToggle('svcActive');

  if (!name) { toast('Service name is required', 'err'); document.getElementById('svcName').focus(); return; }
  if (duration < 5) { toast('Duration must be at least 5 minutes', 'err'); return; }

  const body = {name, description: desc, duration_min: duration, color, is_restricted: restr, is_active: active};

  try {
    const r = await csrfFetch(BK + '/admin/services' + (id ? '/' + id : ''), {
      method: id ? 'PUT' : 'POST', body: JSON.stringify(body)
    });
    const d = await r.json();
    if (!d.ok) { toast(d.error || 'Save failed', 'err'); return; }
    toast(id ? 'Service updated' : 'Service created');
    closeModal('svcModal');
    loadServices();
  } catch(e) {
    toast('Connection error', 'err');
  }
}

async function deleteSvc() {
  const id = document.getElementById('svcId').value;
  if (!id) return;
  const svc = allServices.find(s => s.id == id);
  if (!confirm(`Delete "${svc ? svc.name : 'this service'}"? This cannot be undone.`)) return;

  try {
    const r = await csrfFetch(BK + '/admin/services/' + id, {method: 'DELETE'});
    const d = await r.json();
    if (d.ok) {
      toast('Service deleted');
      closeModal('svcModal');
      loadServices();
    } else {
      toast(d.error || 'Delete failed', 'err');
    }
  } catch(e) {
    toast('Connection error', 'err');
  }
}

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

// Kick off
loadServices();
</script>
</body>
</html>
