<?php
// ─────────────────────────────────────────────────────────────
//  admin/booking-providers.php — Admin: Providers + Hours
// ─────────────────────────────────────────────────────────────
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>Providers — 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;
  --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}
.providers-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px}
.prov-card{background:#fff;border:1px solid var(--border);border-radius:14px;overflow:hidden;transition:box-shadow .15s}
.prov-card:hover{box-shadow:0 4px 20px rgba(0,0,0,.07)}
.prov-card-hdr{padding:20px;display:flex;align-items:center;gap:14px;border-bottom:1px solid var(--border)}
.prov-avatar{width:48px;height:48px;border-radius:50%;background:var(--accent-pale);flex-shrink:0;display:flex;align-items:center;justify-content:center;font-family:var(--font-display);font-size:18px;font-weight:800;color:var(--accent)}
.prov-name{font-family:var(--font-display);font-size:15px;font-weight:800;color:var(--text)}
.prov-branch{font-size:12px;color:var(--text-2);margin-top:1px}
.prov-card-body{padding:14px 20px}
.prov-info{font-size:12px;color:var(--text-2);display:flex;align-items:center;gap:6px;margin-bottom:6px}
.prov-info svg{width:13px;height:13px;stroke:var(--text-3);fill:none;stroke-width:2;flex-shrink:0}
.prov-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)}
.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:600px;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}
.modal-section{font-family:var(--font-display);font-size:13px;font-weight:700;color:var(--text);margin:20px 0 12px;padding-top:16px;border-top:1px solid var(--border)}
/* Hours grid */
.hours-grid{display:grid;gap:8px}
.hours-row{display:grid;grid-template-columns:80px 1fr 1fr 60px;gap:8px;align-items:center}
.hours-row .day-label{font-size:12px;font-weight:600;color:var(--text-2)}
.hours-row input[type=time]{background:var(--bg);border:1.5px solid var(--border-hi);border-radius:8px;padding:7px 10px;font-size:12px;color:var(--text);outline:none;font-family:inherit}
.hours-row input[type=time]:focus{border-color:var(--accent)}
.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}
/* Svc checkboxes */
.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){.providers-grid{grid-template-columns:1fr}.hours-row{grid-template-columns:70px 1fr 1fr 50px}}
</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">Providers</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 & Services
    </button>
    <button class="nav-item active">
      <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>Providers</h1>
        <p>Manage staff, their services, and working hours</p>
      </div>
      <button class="btn btn-primary" onclick="openProvModal(null)">
        <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
        New Provider
      </button>
    </div>

    <div class="providers-grid" id="provGrid">
      <div style="text-align:center;padding:40px;grid-column:1/-1"><div class="spinner"></div></div>
    </div>
  </main>
</div>

<!-- Provider Modal -->
<div class="modal-bg" id="provModal">
  <div class="modal">
    <div class="modal-hdr">
      <h2 id="provModalTitle">New Provider</h2>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('provModal')">✕</button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="provId"/>
      <div class="fg-row">
        <div class="fg" style="flex:2"><label>Full Name</label><input type="text" id="provName" placeholder="e.g. Dr. Sarah Johnson"/></div>
        <div class="fg" style="flex:1"><label>Branch / Location</label><input type="text" id="provBranch" placeholder="Main Office"/></div>
      </div>
      <div class="fg-row">
        <div class="fg"><label>Email</label><input type="email" id="provEmail" placeholder="provider@email.com"/></div>
        <div class="fg"><label>Phone</label><input type="tel" id="provPhone" placeholder="+1 555 0000"/></div>
      </div>
      <div class="fg"><label>Bio (optional)</label><textarea id="provBio" rows="2" placeholder="Brief bio shown to customers…"></textarea></div>
      <div class="fg-row">
        <div class="fg"><label>Timezone</label>
          <select id="provTimezone">
            <option value="UTC">UTC</option>
            <option value="America/New_York">Eastern (ET)</option>
            <option value="America/Chicago">Central (CT)</option>
            <option value="America/Denver">Mountain (MT)</option>
            <option value="America/Los_Angeles">Pacific (PT)</option>
            <option value="Europe/London">London (GMT/BST)</option>
            <option value="Europe/Paris">Paris (CET)</option>
            <option value="Asia/Dubai">Dubai (GST)</option>
            <option value="Asia/Kolkata">India (IST)</option>
            <option value="Asia/Dhaka">Dhaka (BST+6)</option>
            <option value="Asia/Tokyo">Tokyo (JST)</option>
            <option value="Australia/Sydney">Sydney (AEST)</option>
          </select>
        </div>
        <div class="fg"><label>Status</label>
          <select id="provActive"><option value="1">Active</option><option value="0">Inactive</option></select>
        </div>
      </div>

      <div class="modal-section">Services Offered</div>
      <div class="svc-checks" id="provSvcChecks"><span style="color:var(--text-3);font-size:13px">Loading…</span></div>

      <div class="modal-section">Working Hours</div>
      <div class="hours-grid" id="hoursGrid"></div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-danger btn-sm" id="provDeleteBtn" style="margin-right:auto;display:none" onclick="deleteProvider()">Delete</button>
      <button class="btn btn-ghost btn-sm" onclick="closeModal('provModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveProvider()">Save Provider</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 DAYS = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
let allServices = [];
let hoursState = {}; // {dayIndex: {active, start, end}}

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 initials(name) {
  return name.split(' ').map(w => w[0]).join('').toUpperCase().slice(0,2);
}

// ── Load providers ────────────────────────────────────────────
async function loadProviders() {
  const grid = document.getElementById('provGrid');
  try {
    const r = await fetch(BK + '/admin/providers', {credentials:'same-origin'});
    const d = await r.json();
    if (!d.providers.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"><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.75M21 20v-2a4 4 0 00-3-3.87"/></svg><h3>No providers yet</h3><p>Add your first staff member</p></div>';
      return;
    }
    grid.innerHTML = d.providers.map(p => `
      <div class="prov-card">
        <div class="prov-card-hdr">
          <div class="prov-avatar">${initials(p.name)}</div>
          <div style="flex:1;min-width:0">
            <div class="prov-name">${esc(p.name)}</div>
            ${p.branch_name ? `<div class="prov-branch">${esc(p.branch_name)}</div>` : ''}
          </div>
          <span class="badge ${p.is_active ? 'badge-green' : 'badge-red'}">${p.is_active ? 'active' : 'off'}</span>
        </div>
        <div class="prov-card-body">
          ${p.email ? `<div class="prov-info"><svg viewBox="0 0 24 24"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>${esc(p.email)}</div>` : ''}
          ${p.phone ? `<div class="prov-info"><svg viewBox="0 0 24 24"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.49 9.82 19.79 19.79 0 01.46 1.2 2 2 0 012.44 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.91 7.91a16 16 0 006.72 6.72l.72-.72a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/></svg>${esc(p.phone)}</div>` : ''}
          ${p.bio ? `<div style="font-size:12px;color:var(--text-2);margin-top:6px;line-height:1.5;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical">${esc(p.bio)}</div>` : ''}
        </div>
        <div class="prov-card-footer">
          <button class="btn btn-ghost btn-sm" onclick="openProvModal(${p.id})">Edit</button>
          <button class="btn btn-ghost btn-sm" onclick="openHoursModal(${p.id}, '${esc(p.name)}')">
            <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            Hours
          </button>
        </div>
      </div>`).join('');
  } catch(e) {
    grid.innerHTML = '<div class="empty" style="grid-column:1/-1"><h3>Failed to load</h3></div>';
  }
}

// ── Provider modal ─────────────────────────────────────────────
async function openProvModal(id) {
  // Load services
  try {
    const sr = await fetch(BK + '/admin/services', {credentials:'same-origin'}).then(r=>r.json());
    allServices = sr.services || [];
  } catch(e) {}

  const checks = document.getElementById('provSvcChecks');
  checks.innerHTML = allServices.map(s => `
    <label class="svc-check" data-sid="${s.id}">
      <input type="checkbox" value="${s.id}"/>
      <span style="width:10px;height:10px;border-radius:50%;background:${esc(s.color)};flex-shrink:0;display:inline-block"></span>
      ${esc(s.name)}
    </label>`).join('');
  checks.querySelectorAll('.svc-check').forEach(el => {
    const input = el.querySelector('input');
    input.addEventListener('change', () => {
      el.classList.toggle('selected', input.checked);
    });
  });

  // Reset hours
  buildHoursGrid([]);

  if (!id) {
    document.getElementById('provModalTitle').textContent = 'New Provider';
    document.getElementById('provId').value = '';
    document.getElementById('provName').value = '';
    document.getElementById('provBranch').value = '';
    document.getElementById('provEmail').value = '';
    document.getElementById('provPhone').value = '';
    document.getElementById('provBio').value = '';
    document.getElementById('provTimezone').value = 'UTC';
    document.getElementById('provActive').value = '1';
    document.getElementById('provDeleteBtn').style.display = 'none';
  } else {
    document.getElementById('provModalTitle').textContent = 'Edit Provider';
    document.getElementById('provDeleteBtn').style.display = '';
    try {
      const r = await fetch(BK + '/admin/providers/' + id, {credentials:'same-origin'});
      const d = await r.json();
      if (!d.ok) return;
      const p = d.provider;
      document.getElementById('provId').value = p.id;
      document.getElementById('provName').value = p.name;
      document.getElementById('provBranch').value = p.branch_name || '';
      document.getElementById('provEmail').value = p.email || '';
      document.getElementById('provPhone').value = p.phone || '';
      document.getElementById('provBio').value = p.bio || '';
      document.getElementById('provTimezone').value = p.timezone || 'UTC';
      document.getElementById('provActive').value = p.is_active;

      // Check services
      const svcSet = new Set((p.services||[]).map(s => Number(s.service_id)));
      checks.querySelectorAll('.svc-check').forEach(el => {
        if (svcSet.has(parseInt(el.dataset.sid))) {
          el.classList.add('selected');
          el.querySelector('input').checked = true;
        }
      });

      buildHoursGrid(p.hours || []);
    } catch(e) {}
  }
  openModal('provModal');
}

function buildHoursGrid(existingHours) {
  const grid = document.getElementById('hoursGrid');
  const hoursMap = {};
  existingHours.forEach(h => { hoursMap[h.day_of_week] = h; });

  grid.innerHTML = DAYS.map((day, i) => {
    const h = hoursMap[i];
    const active = h ? h.is_active : (i >= 1 && i <= 5); // default Mon-Fri
    const start  = h ? h.start_time.slice(0,5) : '09:00';
    const end    = h ? h.end_time.slice(0,5)   : '17:00';
    return `
      <div class="hours-row" id="hrow${i}">
        <span class="day-label">${day}</span>
        <input type="time" id="hstart${i}" value="${start}" ${!active ? 'disabled' : ''}/>
        <input type="time" id="hend${i}"   value="${end}"   ${!active ? 'disabled' : ''}/>
        <button type="button" class="toggle-btn ${active ? 'on' : 'off'}" id="htog${i}" onclick="toggleDay(${i})"></button>
      </div>`;
  }).join('');
}

function toggleDay(i) {
  const btn = document.getElementById('htog' + i);
  const on = btn.classList.toggle('on');
  btn.classList.toggle('off');
  document.getElementById('hstart' + i).disabled = !on;
  document.getElementById('hend' + i).disabled = !on;
}

async function saveProvider() {
  const id     = document.getElementById('provId').value;
  const name   = document.getElementById('provName').value.trim();
  const branch = document.getElementById('provBranch').value.trim();
  const email  = document.getElementById('provEmail').value.trim();
  const phone  = document.getElementById('provPhone').value.trim();
  const bio    = document.getElementById('provBio').value;
  const tz     = document.getElementById('provTimezone').value;
  const active = parseInt(document.getElementById('provActive').value);
  const svcIds = Array.from(document.querySelectorAll('#provSvcChecks input:checked'))
    .map(el => parseInt(el.value, 10))
    .filter(Number.isFinite);

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

  // Build hours array
  const hours = DAYS.map((_, i) => ({
    day_of_week: i,
    start_time: document.getElementById('hstart' + i).value + ':00',
    end_time:   document.getElementById('hend' + i).value   + ':00',
    is_active:  document.getElementById('htog' + i).classList.contains('on') ? 1 : 0,
  }));

  const body = {name, branch_name:branch, email, phone, bio, timezone:tz, is_active:active, service_ids:svcIds};

  try {
    const r = await csrfFetch(BK + '/admin/providers' + (id ? '/' + id : ''), {
      method: id ? 'PUT' : 'POST', body:JSON.stringify(body)
    });
    const d = await r.json();
    if (!d.ok) { toast(d.error || 'Error', 'err'); return; }

    const provId = id || d.id;

    // Save hours
    await csrfFetch(BK + '/admin/providers/' + provId + '/hours', {
      method:'POST', body:JSON.stringify({hours})
    });

    toast(id ? 'Provider updated' : 'Provider created');
    closeModal('provModal');
    loadProviders();
  } catch(e) { toast('Error', 'err'); }
}

async function deleteProvider() {
  const id = document.getElementById('provId').value;
  if (!id || !confirm('Delete this provider?')) return;
  try {
    const r = await csrfFetch(BK + '/admin/providers/' + id, {method:'DELETE'});
    const d = await r.json();
    if (d.ok) { toast('Provider deleted'); closeModal('provModal'); loadProviders(); }
    else toast(d.error || 'Error', 'err');
  } catch(e) { toast('Error', 'err'); }
}

// Hours-only modal (from card button)
async function openHoursModal(provId, provName) {
  // Just open provider modal in edit mode which includes hours
  openProvModal(provId);
}

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

loadProviders();
</script>
</body>
</html>
