<?php
// ─────────────────────────────────────────────────────────────
//  admin/booking-plans.php — Admin: Plans & 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>Plans & 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{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{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-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}
.tabs{display:flex;gap:4px;margin-bottom:24px;background:#fff;border:1px solid var(--border);border-radius:10px;padding:4px;width:fit-content}
.tab{padding:7px 18px;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;border:none;background:none;color:var(--text-2);transition:all .14s;font-family:inherit}
.tab:hover{color:var(--text)}
.tab.active{background:linear-gradient(135deg,var(--accent-hi),var(--accent-d));color:#fff}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:16px}
.plan-card-admin{background:#fff;border:1px solid var(--border);border-radius:14px;overflow:hidden;transition:box-shadow .15s}
.plan-card-admin:hover{box-shadow:0 4px 20px rgba(0,0,0,.07)}
.plan-card-hdr{padding:20px;border-bottom:1px solid var(--border);display:flex;align-items:flex-start;justify-content:space-between;gap:10px}
.plan-dot{width:12px;height:12px;border-radius:50%;flex-shrink:0;margin-top:3px}
.plan-card-name{font-family:var(--font-display);font-size:16px;font-weight:800;color:var(--text)}
.plan-card-price{font-family:var(--font-display);font-size:22px;font-weight:800;color:var(--accent)}
.plan-card-body{padding:16px 20px}
.plan-card-meta{font-family:var(--font-mono);font-size:11px;color:var(--text-3);margin-bottom:10px}
.plan-card-svcs{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px}
.svc-tag{font-size:11px;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:3px 8px;color:var(--text-2)}
.plan-card-footer{padding:12px 20px;border-top:1px solid var(--border);display:flex;gap:8px}
.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-gray{background:var(--bg);color:var(--text-3);border:1px solid var(--border)}
.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)}
.svc-color{width:14px;height:14px;border-radius:50%;display:inline-block;flex-shrink:0}
.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:560px;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}
.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)}
.fg .row{display:flex;gap:12px}
.fg .row .fg{flex:1;margin-bottom:0}
.svc-checks{display:flex;flex-wrap:wrap;gap:8px;margin-top:4px}
.svc-check{display:flex;align-items:center;gap:6px;padding:6px 10px;border:1.5px solid var(--border);border-radius:8px;cursor:pointer;font-size:13px;transition:all .14s}
.svc-check:hover{border-color:var(--accent);background:var(--accent-pale)}
.svc-check.selected{border-color:var(--accent);background:var(--accent-pale);color:var(--accent);font-weight:600}
.svc-check input{display:none}
.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: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)}}
.empty{text-align:center;padding:60px 20px;color:var(--text-3)}
@media(max-width:900px){.sidebar{display:none}.content{margin-left:0}}
@media(max-width:640px){.grid{grid-template-columns:1fr}}
</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">Plans & 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 active">
      <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" 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" 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 id="pageTitle">Plans</h1>
        <p id="pageDesc">Create and manage membership plans</p>
      </div>
      <button class="btn btn-primary" id="addBtn" onclick="openAddModal()">
        <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
        <span id="addBtnLabel">New Plan</span>
      </button>
    </div>

    <div class="tabs">
      <button class="tab active" id="tabPlans" onclick="switchTab('plans')">Plans</button>
      <button class="tab" id="tabServices" onclick="switchTab('services')">Services</button>
      <button class="tab" id="tabPayments" onclick="switchTab('payments')">Payments</button>
      <button class="tab" id="tabPromos" onclick="switchTab('promos')">🏷️ Promo Codes</button>
    </div>

    <!-- Plans grid -->
    <div id="sectionPlans">
      <div class="grid" id="plansGrid"><div style="text-align:center;padding:40px;grid-column:1/-1"><div class="spinner"></div></div></div>
    </div>

    <!-- Services table -->
    <div id="sectionServices" style="display:none">
      <div class="tbl-wrap">
        <table class="tbl">
          <thead><tr><th>Color</th><th>Name</th><th>Duration</th><th>Access</th><th>Status</th><th></th></tr></thead>
          <tbody id="svcTbody"><tr><td colspan="6" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr></tbody>
        </table>
      </div>
    </div>

    <!-- Payments settings -->
    <div id="sectionPayments" style="display:none">
      <div class="tbl-wrap" style="padding:20px;max-width:860px">
        <h3 style="font-family:var(--font-display);font-size:16px;margin-bottom:6px">Stripe Configuration</h3>
        <p style="font-size:13px;color:var(--text-2);margin-bottom:16px">Manage test/live keys and choose which mode is active for membership checkout.</p>
        <div class="fg" style="max-width:220px">
          <label>Stripe Mode</label>
          <select id="stripeMode">
            <option value="test">Test mode</option>
            <option value="live">Live mode</option>
          </select>
        </div>
        <div class="fg" style="max-width:220px">
          <label>Currency</label>
          <input id="stripeCurrency" type="text" value="usd" maxlength="3" placeholder="usd"/>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div>
            <h4 style="font-size:13px;margin:6px 0 8px">Test Keys</h4>
            <div class="fg"><label>Publishable Key</label><input id="stripeTestPub" type="text" placeholder="pk_test_..."/></div>
            <div class="fg"><label>Secret Key</label><input id="stripeTestSec" type="text" placeholder="sk_test_..."/></div>
            <div class="fg"><label>Webhook Secret</label><input id="stripeTestWh" type="text" placeholder="whsec_..."/></div>
          </div>
          <div>
            <h4 style="font-size:13px;margin:6px 0 8px">Live Keys</h4>
            <div class="fg"><label>Publishable Key</label><input id="stripeLivePub" type="text" placeholder="pk_live_..."/></div>
            <div class="fg"><label>Secret Key</label><input id="stripeLiveSec" type="text" placeholder="sk_live_..."/></div>
            <div class="fg"><label>Webhook Secret</label><input id="stripeLiveWh" type="text" placeholder="whsec_..."/></div>
          </div>
        </div>
        <div style="display:flex;gap:10px;align-items:center">
          <button class="btn btn-primary" onclick="saveStripeConfig()">Save Stripe Settings</button>
          <span style="font-size:12px;color:var(--text-3)">Tip: keep mode on Test until live keys + webhook are fully verified.</span>
        </div>
      </div>
    </div>

    <!-- Promo Codes section -->
    <div id="sectionPromos" style="display:none">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
        <div>
          <h2 style="font-family:var(--font-display);font-size:18px;font-weight:800">Promo Codes</h2>
          <p style="font-size:13px;color:var(--text-3);margin-top:2px">Create discount codes for membership plans</p>
        </div>
        <button class="btn btn-primary" onclick="openPromoModal()">+ New Code</button>
      </div>
      <div class="tbl-wrap">
        <table class="tbl">
          <thead><tr><th>Code</th><th>Discount</th><th>Uses</th><th>Validity</th><th>Status</th><th></th></tr></thead>
          <tbody id="promoTbody"><tr><td colspan="6" style="text-align:center;padding:40px"><div class="spinner"></div></td></tr></tbody>
        </table>
      </div>
    </div>

  </main>
</div>

<!-- Plan Modal -->
<div class="modal-bg" id="planModal">
  <div class="modal">
    <div class="modal-hdr">
      <h2 id="planModalTitle">New Plan</h2>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('planModal')">✕</button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="planId"/>
      <div class="fg"><label>Plan Name</label><input type="text" id="planName" placeholder="e.g. Premium Membership"/></div>
      <div class="fg row">
        <div class="fg"><label>Price ($)</label><input type="number" id="planPrice" min="0" step="0.01" placeholder="0.00"/></div>
        <div class="fg"><label>Duration (days)</label><input type="number" id="planDays" min="1" value="30"/></div>
      </div>
      <div class="fg row">
        <div class="fg">
          <label>Session Limit <span style="font-weight:400;text-transform:none;color:var(--text-3)">(0 = unlimited)</span></label>
          <input type="number" id="planSessionLimit" min="0" step="1" value="0" placeholder="0"/>
        </div>
        <div class="fg">
          <label>Status</label>
          <select id="planActive"><option value="1">Active</option><option value="0">Inactive</option></select>
        </div>
      </div>
      <div class="fg"><label>Description</label><textarea id="planDesc" rows="2" placeholder="Brief description…"></textarea></div>
      <div class="fg">
        <label>Color</label><input type="color" id="planColor" value="#e09500" style="height:42px;padding:4px;width:100%"/>
      </div>
      <div class="fg">
        <label>Included Services</label>
        <div class="svc-checks" id="planSvcChecks"><span style="color:var(--text-3);font-size:13px">Loading services…</span></div>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-ghost btn-sm" id="planDeleteBtn" style="margin-right:auto" onclick="deletePlan()">Delete</button>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('planModal')">Cancel</button>
      <button class="btn btn-primary" onclick="savePlan()">Save Plan</button>
    </div>
  </div>
</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. 60-Min Consultation"/></div>
      <div class="fg row">
        <div class="fg"><label>Duration (min)</label><input type="number" id="svcDuration" min="5" step="5" value="60"/></div>
        <div class="fg"><label>Color</label><input type="color" id="svcColor" value="#e09500" style="height:42px;padding:4px"/></div>
      </div>
      <div class="fg"><label>Description</label><textarea id="svcDesc" rows="2" placeholder="What does this service include?"></textarea></div>
      <div class="fg row">
        <div class="fg"><label>Access</label>
          <select id="svcRestricted"><option value="1">Members Only</option><option value="0">Anyone</option></select>
        </div>
        <div class="fg"><label>Status</label>
          <select id="svcActive"><option value="1">Active</option><option value="0">Inactive</option></select>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-ghost btn-sm" id="svcDeleteBtn" style="margin-right:auto;display:none" onclick="deleteService()">Delete</button>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('svcModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveService()">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';
let allServices = [];
let currentTab = 'plans';

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 switchTab(tab) {
  currentTab = tab;
  ['Plans','Services','Payments','Promos'].forEach(t => {
    const el = document.getElementById('tab'+t);
    if (el) el.classList.toggle('active', tab === t.toLowerCase());
    const sec = document.getElementById('section'+t);
    if (sec) sec.style.display = tab === t.toLowerCase() ? '' : 'none';
  });
  document.getElementById('pageTitle').textContent = tab === 'plans' ? 'Plans' : (tab === 'services' ? 'Services' : 'Payments');
  document.getElementById('pageDesc').textContent = tab === 'plans'
    ? 'Create and manage membership plans'
    : (tab === 'services' ? 'Define bookable services' : tab === 'promos' ? 'Discount codes for membership checkout' : 'Stripe mode and API keys');
  const lblMap = {plans:'New Plan', services:'New Service', promos:'+ New Code'};
  document.getElementById('addBtnLabel').textContent = lblMap[tab] || 'Add';
  document.getElementById('addBtn').style.display = tab === 'payments' ? 'none' : '';
  if (tab === 'services') loadServices();
  if (tab === 'payments') loadStripeConfig();
  if (tab === 'promos') loadPromos();
}

function openAddModal() {
  if (currentTab === 'plans') openPlanModal(null);
  else if (currentTab === 'services') openSvcModal(null);
  else if (currentTab === 'promos') openPromoModal(null);
}

async function loadStripeConfig() {
  try {
    const r = await fetch(BK + '/admin/stripe-config', {credentials:'same-origin'});
    const d = await r.json();
    if (!d.ok) throw new Error('Failed');
    const s = d.stripe || {};
    document.getElementById('stripeMode').value = s.mode || 'test';
    document.getElementById('stripeCurrency').value = (s.currency || 'usd').toLowerCase();
    document.getElementById('stripeTestPub').value = s.test_publishable_key || '';
    document.getElementById('stripeTestSec').value = s.test_secret_key || '';
    document.getElementById('stripeTestWh').value = s.test_webhook_secret || '';
    document.getElementById('stripeLivePub').value = s.live_publishable_key || '';
    document.getElementById('stripeLiveSec').value = s.live_secret_key || '';
    document.getElementById('stripeLiveWh').value = s.live_webhook_secret || '';
  } catch(e) {
    toast('Failed to load Stripe settings', 'err');
  }
}

async function saveStripeConfig() {
  const body = {
    mode: document.getElementById('stripeMode').value,
    currency: document.getElementById('stripeCurrency').value.trim().toLowerCase(),
    test_publishable_key: document.getElementById('stripeTestPub').value.trim(),
    test_secret_key: document.getElementById('stripeTestSec').value.trim(),
    test_webhook_secret: document.getElementById('stripeTestWh').value.trim(),
    live_publishable_key: document.getElementById('stripeLivePub').value.trim(),
    live_secret_key: document.getElementById('stripeLiveSec').value.trim(),
    live_webhook_secret: document.getElementById('stripeLiveWh').value.trim(),
  };
  try {
    const r = await fetch(BK + '/admin/stripe-config', {
      method: 'PUT',
      credentials: 'same-origin',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify(body),
    });
    const d = await r.json();
    if (d.ok) toast('Stripe settings saved');
    else toast(d.error || 'Failed to save Stripe settings', 'err');
  } catch(e) {
    toast('Failed to save Stripe settings', 'err');
  }
}

// ── Plans ─────────────────────────────────────────────────────
async function loadPlans() {
  const grid = document.getElementById('plansGrid');
  try {
    const [pr, sr] = await Promise.all([
      fetch(BK + '/admin/plans', {credentials:'same-origin'}).then(r=>r.json()),
      fetch(BK + '/admin/services', {credentials:'same-origin'}).then(r=>r.json()),
    ]);
    allServices = sr.services || [];

    if (!pr.plans.length) {
      grid.innerHTML = '<div class="empty" style="grid-column:1/-1"><svg viewBox="0 0 24 24" style="width:48px;height:48px;stroke:var(--border-hi);fill:none;stroke-width:1.5;margin-bottom:14px"><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><h3>No plans yet</h3><p>Create your first membership plan</p></div>';
      return;
    }
    const svcMap = {};
    allServices.forEach(s => svcMap[s.id] = s.name);

    grid.innerHTML = pr.plans.map(p => `
      <div class="plan-card-admin">
        <div class="plan-card-hdr">
          <div style="display:flex;align-items:flex-start;gap:10px">
            <div class="plan-dot" style="background:${esc(p.color)};margin-top:4px"></div>
            <div>
              <div class="plan-card-name">${esc(p.name)}</div>
              <div style="font-size:12px;color:var(--text-2);margin-top:2px">${esc(p.description||'')}</div>
            </div>
          </div>
          <span class="badge ${p.is_active ? 'badge-green' : 'badge-red'}">${p.is_active ? 'active' : 'inactive'}</span>
        </div>
        <div class="plan-card-body">
          <div class="plan-card-price">$${parseFloat(p.price).toFixed(2)}</div>
          <div class="plan-card-meta">${p.duration_days} days · ${p.session_limit > 0 ? p.session_limit + ' sessions' : 'Unlimited sessions'}</div>
          <div class="plan-card-svcs">
            ${(p.service_ids||[]).map(sid => `<span class="svc-tag">${esc(svcMap[sid]||'Service '+sid)}</span>`).join('')}
            ${!(p.service_ids||[]).length ? '<span style="font-size:12px;color:var(--text-3)">No services linked</span>' : ''}
          </div>
        </div>
        <div class="plan-card-footer">
          <button class="btn btn-ghost btn-sm" onclick="openPlanModal(${p.id})">Edit</button>
        </div>
      </div>`).join('');
  } catch(e) {
    grid.innerHTML = '<div class="empty" style="grid-column:1/-1"><h3>Failed to load plans</h3></div>';
  }
}

async function openPlanModal(id) {
  // Ensure services loaded
  if (!allServices.length) {
    const r = await fetch(BK + '/admin/services', {credentials:'same-origin'}).then(r=>r.json());
    allServices = r.services || [];
  }

  // Build service checkboxes
  const checks = document.getElementById('planSvcChecks');
  checks.innerHTML = allServices.map(s => `
    <label class="svc-check" data-sid="${s.id}">
      <input type="checkbox" value="${s.id}"/>
      <span class="svc-color" style="background:${esc(s.color)}"></span>
      ${esc(s.name)} (${s.duration_min}m)
    </label>`).join('');
  checks.querySelectorAll('.svc-check').forEach(el => {
    const input = el.querySelector('input');
    // Use 'change' on the input, not 'click' on the label.
    // Clicking a <label> that wraps an <input> natively toggles the checkbox;
    // a second manual toggle in the click handler double-cancels the change.
    input.addEventListener('change', () => {
      el.classList.toggle('selected', input.checked);
    });
  });

  if (!id) {
    document.getElementById('planModalTitle').textContent = 'New Plan';
    document.getElementById('planId').value = '';
    document.getElementById('planName').value = '';
    document.getElementById('planPrice').value = '';
    document.getElementById('planDays').value = '30';
    document.getElementById('planSessionLimit').value = '0';
    document.getElementById('planDesc').value = '';
    document.getElementById('planColor').value = '#e09500';
    document.getElementById('planActive').value = '1';
    document.getElementById('planDeleteBtn').style.display = 'none';
  } else {
    document.getElementById('planModalTitle').textContent = 'Edit Plan';
    document.getElementById('planDeleteBtn').style.display = '';
    try {
      const r = await fetch(BK + '/admin/plans/' + id, {credentials:'same-origin'});
      const d = await r.json();
      if (!d.ok) return;
      const p = d.plan;
      document.getElementById('planId').value = p.id;
      document.getElementById('planName').value = p.name;
      document.getElementById('planPrice').value = parseFloat(p.price).toFixed(2);
      document.getElementById('planDays').value = p.duration_days;
      document.getElementById('planSessionLimit').value = p.session_limit || 0;
      document.getElementById('planDesc').value = p.description || '';
      document.getElementById('planColor').value = p.color || '#e09500';
      document.getElementById('planActive').value = p.is_active;
      // Check selected services
      const selectedIds = new Set((p.service_ids||[]).map(Number));
      checks.querySelectorAll('.svc-check').forEach(el => {
        const sid = parseInt(el.dataset.sid);
        if (selectedIds.has(sid)) {
          el.classList.add('selected');
          el.querySelector('input').checked = true;
        }
      });
    } catch(e) {}
  }
  openModal('planModal');
}

async function savePlan() {
  const id     = document.getElementById('planId').value;
  const name   = document.getElementById('planName').value.trim();
  const price  = document.getElementById('planPrice').value;
  const days   = document.getElementById('planDays').value;
  const desc   = document.getElementById('planDesc').value;
  const color  = document.getElementById('planColor').value;
  const active = document.getElementById('planActive').value;
  const svcIds = Array.from(document.querySelectorAll('#planSvcChecks input:checked'))
    .map(el => parseInt(el.value, 10))
    .filter(Number.isFinite);

  if (!name) { toast('Name required', 'err'); return; }

  const body = {name, price:parseFloat(price)||0, duration_days:parseInt(days)||30, session_limit:parseInt(document.getElementById('planSessionLimit').value)||0, description:desc, color, is_active:parseInt(active), service_ids:svcIds};

  try {
    const r = await fetch(BK + '/admin/plans' + (id ? '/' + id : ''), {
      method: id ? 'PUT' : 'POST', credentials:'same-origin',
      headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)
    });
    const d = await r.json();
    if (d.ok) { toast(id ? 'Plan updated' : 'Plan created'); closeModal('planModal'); loadPlans(); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

async function deletePlan() {
  const id = document.getElementById('planId').value;
  if (!id || !confirm('Delete this plan? This cannot be undone.')) return;
  try {
    const r = await fetch(BK + '/admin/plans/' + id, {method:'DELETE', credentials:'same-origin'});
    const d = await r.json();
    if (d.ok) { toast('Plan deleted'); closeModal('planModal'); loadPlans(); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

// ── Services ──────────────────────────────────────────────────
async function loadServices() {
  const tbody = document.getElementById('svcTbody');
  try {
    const r = await fetch(BK + '/admin/services', {credentials:'same-origin'});
    const d = await r.json();
    allServices = d.services || [];
    if (!allServices.length) {
      tbody.innerHTML = '<tr><td colspan="6"><div class="empty"><h3>No services yet</h3></div></td></tr>';
      return;
    }
    tbody.innerHTML = allServices.map(s => `
      <tr>
        <td><span class="svc-color" style="background:${esc(s.color)};width:18px;height:18px;border-radius:50%;display:inline-block"></span></td>
        <td><strong>${esc(s.name)}</strong>${s.description ? `<br><span style="color:var(--text-3);font-size:12px">${esc(s.description)}</span>` : ''}</td>
        <td><span style="font-family:var(--font-mono);font-size:12px">${s.duration_min} min</span></td>
        <td>${s.is_restricted ? '<span class="badge badge-gray">members only</span>' : '<span class="badge badge-green">anyone</span>'}</td>
        <td>${s.is_active ? '<span class="badge badge-green">active</span>' : '<span class="badge badge-red">inactive</span>'}</td>
        <td><button class="btn btn-ghost btn-sm" onclick="openSvcModal(${s.id})">Edit</button></td>
      </tr>`).join('');
  } catch(e) {
    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:30px;color:var(--text-3)">Failed to load</td></tr>';
  }
}

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

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

  if (!name) { toast('Name required', 'err'); return; }

  try {
    const r = await fetch(BK + '/admin/services' + (id ? '/' + id : ''), {
      method: id ? 'PUT' : 'POST', credentials:'same-origin',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({name, duration_min:dur, description:desc, color, is_restricted:restr, is_active:active})
    });
    const d = await r.json();
    if (d.ok) { toast(id ? 'Service updated' : 'Service created'); closeModal('svcModal'); loadServices(); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

async function deleteService() {
  const id = document.getElementById('svcId').value;
  if (!id || !confirm('Delete this service?')) return;
  try {
    const r = await fetch(BK + '/admin/services/' + id, {method:'DELETE', credentials:'same-origin'});
    const d = await r.json();
    if (d.ok) { toast('Service deleted'); closeModal('svcModal'); loadServices(); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

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

loadPlans();
</script>

<!-- Promo Code Modal -->
<div class="modal-bg" id="promoModal">
  <div class="modal" style="max-width:520px">
    <div class="modal-hdr">
      <h2 id="promoModalTitle">New Promo Code</h2>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('promoModal')">✕</button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="promoId"/>
      <div class="fg">
        <label>Code <span style="color:var(--text-3);font-size:11px">(uppercase letters/numbers/hyphens)</span></label>
        <input type="text" id="promoCode" placeholder="SUMMER25" style="text-transform:uppercase" oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9\-_]/g,'')"/>
      </div>
      <div class="fg">
        <label>Description <span style="color:var(--text-3);font-size:11px">(shown to user)</span></label>
        <input type="text" id="promoDesc" placeholder="Summer sale — 25% off"/>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
        <div class="fg">
          <label>Discount Type</label>
          <select id="promoType" onchange="updatePromoPlaceholder()">
            <option value="percent">Percentage (%)</option>
            <option value="fixed">Fixed Amount (€)</option>
          </select>
        </div>
        <div class="fg">
          <label id="promoValLabel">Discount Value (%)</label>
          <input type="number" id="promoValue" placeholder="25" min="0" max="100" step="0.01"/>
        </div>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
        <div class="fg">
          <label>Valid From <span style="color:var(--text-3);font-size:11px">(optional)</span></label>
          <input type="datetime-local" id="promoFrom"/>
        </div>
        <div class="fg">
          <label>Valid Until <span style="color:var(--text-3);font-size:11px">(optional)</span></label>
          <input type="datetime-local" id="promoUntil"/>
        </div>
      </div>
      <div class="fg">
        <label>Max Uses <span style="color:var(--text-3);font-size:11px">(blank = unlimited)</span></label>
        <input type="number" id="promoMaxUses" placeholder="Unlimited" min="1"/>
      </div>
      <div class="fg" style="display:flex;align-items:center;gap:10px">
        <input type="checkbox" id="promoActive" checked style="width:auto;margin:0"/>
        <label for="promoActive" style="margin:0;cursor:pointer">Active</label>
      </div>
      <div style="display:flex;gap:8px;margin-top:8px">
        <button class="btn btn-ghost" onclick="closeModal('promoModal')">Cancel</button>
        <button class="btn btn-primary" style="flex:1" onclick="savePromo()">Save Code</button>
      </div>
    </div>
  </div>
</div>

<script>
// ── Promo Codes ───────────────────────────────────────────────
const PROMO_API = BASE + '/api/booking/admin/promo-codes';

const CSRF_TOKEN='<?= csrf_token() ?>';
// apiFetch: thin wrapper around fetch with JSON body + credentials
async function apiFetch(url, opts = {}) {
  const method = (opts.method || 'GET').toUpperCase();
  const options = {
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' },
    ...opts,
  };
  if (['POST','PUT','PATCH','DELETE'].includes(method)) {
    options.headers = { ...options.headers, 'X-CSRF-Token': CSRF_TOKEN };
  }
  const r = await fetch(url, options);
  return r.json();
}

function updatePromoPlaceholder() {
  const type = document.getElementById('promoType').value;
  document.getElementById('promoValLabel').textContent = type === 'percent' ? 'Discount Value (%)' : 'Discount Value (€)';
  const inp = document.getElementById('promoValue');
  inp.max = type === 'percent' ? 100 : 99999;
  inp.placeholder = type === 'percent' ? '25' : '10.00';
}

async function loadPromos() {
  const tbody = document.getElementById('promoTbody');
  const d = await apiFetch(PROMO_API).catch(()=>null);
  if (!d?.ok) { tbody.innerHTML='<tr><td colspan="6" style="text-align:center;color:var(--red);padding:20px">Failed to load promo codes</td></tr>'; return; }
  if (!d.promos.length) {
    tbody.innerHTML='<tr><td colspan="6" style="text-align:center;color:var(--text-3);padding:40px">No promo codes yet. Create one to offer discounts on memberships.</td></tr>';
    return;
  }
  tbody.innerHTML = d.promos.map(p => {
    const disc = p.discount_type === 'percent' ? `${p.discount_value}%` : `€${parseFloat(p.discount_value).toFixed(2)}`;
    const uses = p.max_uses ? `${p.uses_count}/${p.max_uses}` : `${p.uses_count} used`;
    const expired = p.valid_until && new Date(p.valid_until) < new Date();
    const notStarted = p.valid_from && new Date(p.valid_from) > new Date();
    const validity = p.valid_from || p.valid_until
      ? `${p.valid_from ? p.valid_from.slice(0,10) : '∞'} → ${p.valid_until ? p.valid_until.slice(0,10) : '∞'}`
      : 'Always valid';
    const statusBadge = !p.is_active
      ? '<span class="badge badge-red">Inactive</span>'
      : expired ? '<span class="badge badge-amber">Expired</span>'
      : notStarted ? '<span class="badge badge-amber">Pending</span>'
      : '<span class="badge badge-green">Active</span>';
    return `<tr>
      <td><strong style="font-family:var(--font-mono);letter-spacing:.05em">${esc(p.code)}</strong><br><span style="font-size:11px;color:var(--text-3)">${esc(p.description||'')}</span></td>
      <td><strong>${disc}</strong> off</td>
      <td>${uses}</td>
      <td style="font-size:12px">${validity}</td>
      <td>${statusBadge}</td>
      <td style="display:flex;gap:6px;justify-content:flex-end">
        <button class="btn btn-ghost btn-sm" onclick="editPromo(${p.id})">Edit</button>
        <button class="btn btn-danger btn-sm" onclick="deletePromo(${p.id},'${esc(p.code)}')">Del</button>
      </td>
    </tr>`;
  }).join('');
}

function openPromoModal(data=null) {
  document.getElementById('promoId').value = data?.id || '';
  document.getElementById('promoCode').value = data?.code || '';
  document.getElementById('promoDesc').value = data?.description || '';
  document.getElementById('promoType').value = data?.discount_type || 'percent';
  document.getElementById('promoValue').value = data?.discount_value || '';
  document.getElementById('promoFrom').value = data?.valid_from ? data.valid_from.replace(' ','T').slice(0,16) : '';
  document.getElementById('promoUntil').value = data?.valid_until ? data.valid_until.replace(' ','T').slice(0,16) : '';
  document.getElementById('promoMaxUses').value = data?.max_uses || '';
  document.getElementById('promoActive').checked = data ? !!+data.is_active : true;
  document.getElementById('promoModalTitle').textContent = data ? 'Edit Promo Code' : 'New Promo Code';
  updatePromoPlaceholder();
  document.getElementById('promoModal').classList.add('open');
}

async function editPromo(id) {
  const d = await apiFetch(PROMO_API + '/' + id).catch(()=>null);
  if (d?.ok) openPromoModal(d.promo);
}

async function savePromo() {
  const id = document.getElementById('promoId').value;
  const payload = {
    code: document.getElementById('promoCode').value.trim().toUpperCase(),
    description: document.getElementById('promoDesc').value.trim(),
    discount_type: document.getElementById('promoType').value,
    discount_value: parseFloat(document.getElementById('promoValue').value) || 0,
    valid_from: document.getElementById('promoFrom').value.replace('T',' ') || null,
    valid_until: document.getElementById('promoUntil').value.replace('T',' ') || null,
    max_uses: document.getElementById('promoMaxUses').value ? parseInt(document.getElementById('promoMaxUses').value) : null,
    is_active: document.getElementById('promoActive').checked ? 1 : 0,
  };
  if (!payload.code) { alert('Code is required'); return; }
  const url = id ? PROMO_API + '/' + id : PROMO_API;
  const method = id ? 'PUT' : 'POST';
  const d = await apiFetch(url, {method, body: JSON.stringify(payload)}).catch(()=>null);
  if (d?.ok) { closeModal('promoModal'); loadPromos(); toast(id ? 'Code updated' : 'Code created'); }
  else toast(d?.error || 'Failed to save', 'err');
}

async function deletePromo(id, code) {
  if (!confirm(`Delete promo code "${code}"?`)) return;
  const d = await apiFetch(PROMO_API + '/' + id, {method:'DELETE'}).catch(()=>null);
  if (d?.ok) { loadPromos(); toast('Code deleted'); }
  else toast('Failed to delete', 'err');
}

// Hook into switchTab to load promos
const _origSwitch = window.switchTab;
window.switchTab = function(tab) {
  _origSwitch(tab);
  document.getElementById('sectionPromos').style.display = tab === 'promos' ? '' : 'none';
  document.getElementById('tabPromos').classList.toggle('active', tab === 'promos');
  if (tab === 'promos') loadPromos();
  if (tab !== 'promos') document.getElementById('sectionPromos').style.display = 'none';
};
</script>
</body>
</html>
