<h1>System</h1>

<% if (forbidden) { %>
  <div class="alert alert-danger">Your role does not have permission to manage system-wide controls.</div>
<% } else { %>
<% if (error) { %><div class="alert alert-danger"><%= error %></div><% } %>

<div class="card">
  <h2 style="font-size:15px;margin-top:0">Maintenance Windows</h2>
  <p style="color:var(--muted);font-size:12px">Active windows block <strong>every</strong> tenant request (except admin-console management) with a 503. Requires a fresh re-auth to schedule or cancel.</p>
  <table>
    <thead><tr><th>Starts</th><th>Ends</th><th>Message</th><th>Status</th><th></th></tr></thead>
    <tbody>
      <% for (const w of windows) { %>
      <% const now = new Date(), starts = new Date(w.starts_at), ends = new Date(w.ends_at); %>
      <% const state = w.is_canceled ? 'canceled' : (now >= starts && now <= ends ? 'active' : (now < starts ? 'scheduled' : 'past')); %>
      <tr>
        <td><%= starts.toLocaleString() %></td>
        <td><%= ends.toLocaleString() %></td>
        <td><%= w.message %></td>
        <td><span class="badge <%= { active: 'badge-danger', scheduled: 'badge-warn', canceled: 'badge-ok', past: 'badge-ok' }[state] %>"><%= state %></span></td>
        <td><% if (state === 'active' || state === 'scheduled') { %><form method="post" action="/system/maintenance/<%= w.id %>/cancel"><button class="link-btn" type="submit">Cancel</button></form><% } %></td>
      </tr>
      <% } %>
      <% if (!windows.length) { %><tr><td colspan="5" style="color:var(--muted)">No maintenance windows scheduled.</td></tr><% } %>
    </tbody>
  </table>

  <form method="post" action="/system/maintenance" style="max-width:480px;margin-top:16px">
    <div style="display:flex;gap:12px">
      <div style="flex:1"><label>Starts</label><input type="datetime-local" name="startsAt" required></div>
      <div style="flex:1"><label>Ends</label><input type="datetime-local" name="endsAt" required></div>
    </div>
    <label>Message (shown to tenants)</label>
    <input type="text" name="message" required placeholder="We're performing scheduled maintenance...">
    <button class="btn btn-danger" type="submit" style="width:100%;margin-top:16px">Schedule Maintenance Window</button>
  </form>
</div>

<div class="card" style="max-width:520px">
  <h2 style="font-size:15px;margin-top:0">Platform Kill Switches</h2>
  <p style="color:var(--muted);font-size:12px"><code class="mono">ai_assist</code> is wired up as a real, working example — disabling it actually blocks the AI research endpoint platform-wide. Other flag keys are recorded but not yet checked anywhere (documented extension point).</p>
  <table>
    <thead><tr><th>Flag</th><th>Status</th><th>Reason</th><th>Updated</th></tr></thead>
    <tbody>
      <% for (const s of switches) { %>
      <tr>
        <td><code class="mono"><%= s.flag_key %></code></td>
        <td><span class="badge <%= s.is_disabled ? 'badge-danger' : 'badge-ok' %>"><%= s.is_disabled ? 'Disabled' : 'Enabled' %></span></td>
        <td><%= s.reason || '—' %></td>
        <td><%= s.updated_by %>, <%= new Date(s.updated_at).toLocaleDateString() %></td>
      </tr>
      <% } %>
      <% if (!switches.length) { %><tr><td colspan="4" style="color:var(--muted)">No kill switches configured — everything is enabled by default.</td></tr><% } %>
    </tbody>
  </table>

  <form method="post" action="/system/kill-switches" style="display:flex;gap:6px;margin-top:12px;flex-wrap:wrap">
    <input type="text" name="flagKey" placeholder="ai_assist" style="flex:1" required>
    <select name="isDisabled"><option value="true">Disable</option><option value="false">Enable</option></select>
    <input type="text" name="reason" placeholder="Reason" style="flex:1">
    <button class="btn btn-danger" type="submit">Apply</button>
  </form>
</div>

<div class="card" style="max-width:520px">
  <h2 style="font-size:15px;margin-top:0">Default Platform Theme</h2>
  <p style="color:var(--muted);font-size:12px">
    Base template (§28.1) used whenever a firm hasn't made its own choice in Settings, and for every pre-login page
    (sign-in, etc.) that has no firm context to resolve a per-firm theme from yet. A specific firm's own choice, or
    an admin-console lock on that firm (see that firm's detail page), still wins over this default.
  </p>
  <form method="post" action="/system/ui-config/default-theme" style="display:flex;gap:8px;align-items:center">
    <select name="defaultPlatformTheme">
      <option value="phoenix" <%= defaultPlatformTheme === 'phoenix' ? 'selected' : '' %>>Phoenix</option>
      <option value="dason"   <%= defaultPlatformTheme === 'dason'   ? 'selected' : '' %>>Dason</option>
    </select>
    <button class="btn btn-danger" type="submit">Save</button>
  </form>
</div>

<div class="card" style="max-width:520px">
  <h2 style="font-size:15px;margin-top:0">Auth Page Layout</h2>
  <% if (defaultPlatformTheme === 'dason') { %>
    <p style="color:var(--muted);font-size:12px">
      No choice to make here right now — Dason (the current default platform theme) ships one consistent auth
      design (a testimonial-carousel side panel) applied uniformly across sign-in/sign-up/forgot-password/
      reset-password/lock-screen. This control reappears once the default platform theme above is set back to
      Phoenix, which is the only theme that offers a split/card/simple choice.
    </p>
  <% } else { %>
    <p style="color:var(--muted);font-size:12px">
      Platform-wide, applies to sign-in/sign-up/forgot-password/reset-password/lock-screen on the Staff Frontend and
      Client Portal, for any firm actually rendering under Phoenix.
    </p>
    <form method="post" action="/system/ui-config" style="display:flex;gap:8px;align-items:center">
      <select name="authPageLayout">
        <option value="split"  <%= authPageLayout === 'split'  ? 'selected' : '' %>>Split (form + side panel)</option>
        <option value="card"   <%= authPageLayout === 'card'   ? 'selected' : '' %>>Card (centered, boxed)</option>
        <option value="simple" <%= authPageLayout === 'simple' ? 'selected' : '' %>>Simple (centered, no box)</option>
      </select>
      <button class="btn btn-danger" type="submit">Save</button>
    </form>
  <% } %>
</div>

<div class="card">
  <h2 style="font-size:15px;margin-top:0">OAuth App Credentials (Google / Microsoft / Zoom)</h2>
  <p style="color:var(--muted);font-size:12px">
    Platform-wide OAuth app registrations (client ID/secret, one per provider for the whole system) — used for
    calendar sync, meetings, and inbound-email connections across every firm. Moved here from the firm-level
    Settings &gt; Integrations page since a single firm admin should not be able to view, change, or delete
    credentials shared by every other firm. Requires a fresh re-auth to save or delete.
  </p>
  <% if (typeof saved !== 'undefined' && saved) { %>
    <div class="alert alert-ok"><%= saved %> credential(s) saved and applied immediately.</div>
  <% } %>
  <% for (const group of credGroups) { %>
  <div style="margin-bottom:20px">
    <p style="font-weight:600;font-size:13px;margin-bottom:6px"><%= group.label %></p>
    <table>
      <thead><tr><th>Key</th><th>Status</th><th></th></tr></thead>
      <tbody>
        <% for (const key of group.keys) { %>
        <tr>
          <td><code class="mono"><%= key.name %></code></td>
          <td><span class="badge <%= key.set ? 'badge-ok' : 'badge-warn' %>"><%= key.set ? 'Set' : 'Not set' %></span></td>
          <td>
            <% if (key.set) { %>
            <form method="post" action="/system/oauth-credentials/<%= key.name %>/delete" onsubmit="return confirm('Remove <%= key.name %> from the server? This will also disconnect any active calendar sync using this credential.');">
              <button class="link-btn" type="submit">Remove</button>
            </form>
            <% } %>
          </td>
        </tr>
        <% } %>
      </tbody>
    </table>
    <% if (group.capabilityStates && group.capabilityStates.length) { %>
    <div style="display:flex;gap:16px;flex-wrap:wrap;margin-top:8px">
      <% for (const cap of group.capabilityStates) { %>
      <form method="post" action="/system/oauth-credentials/providers/<%= group.provider %>/capabilities/<%= cap.capability %>" style="display:flex;gap:6px;align-items:center">
        <input type="hidden" name="enabled" value="<%= cap.enabled ? 'false' : 'true' %>">
        <button class="link-btn" type="submit" style="font-size:12px"><%= cap.capability %>: <%= cap.enabled ? 'enabled (click to disable)' : 'disabled (click to enable)' %></button>
      </form>
      <% } %>
    </div>
    <% } %>
  </div>
  <% } %>

  <form method="post" action="/system/oauth-credentials" style="margin-top:8px">
    <label>Paste <code class="mono">KEY=value</code> lines (encrypted before storage, applied immediately):</label>
    <textarea name="envBlock" rows="6" class="mono" style="width:100%" placeholder="GOOGLE_OAUTH_CLIENT_ID=&#10;GOOGLE_OAUTH_CLIENT_SECRET=&#10;GOOGLE_OAUTH_REDIRECT_URI="></textarea>
    <button class="btn btn-danger" type="submit" style="margin-top:8px">Save &amp; Apply</button>
  </form>
</div>

<div class="card" style="max-width:520px">
  <h2 style="font-size:15px;margin-top:0">Restart Backend Server</h2>
  <p style="color:var(--muted);font-size:12px">
    Restarts the shared tenant-api process that every firm's app runs on — every firm loses their connection for a
    few seconds. Moved here from the firm-level Settings page since a single firm admin should not be able to
    restart infrastructure shared by every other firm. Requires a fresh re-auth.
  </p>
  <form method="post" action="/system/restart" onsubmit="return confirm('Restart the shared backend server now? Every firm will briefly lose connection.');">
    <button class="btn btn-danger" type="submit">Restart Server</button>
  </form>
</div>

<% if (typeof restarted !== 'undefined' && restarted) { %>
  <div class="alert alert-success" style="max-width:520px">Restart triggered — the server should be back within a few seconds.</div>
<% } %>

<% } %>
