<?php
// public/admin.php — Studio Admin Panel
require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/layout.php';

$user  = requireAuth();
$isAdmin = ($user['role'] ?? '') === 'admin';
$tab   = $_GET['tab'] ?? 'studio';

// ── Handle POST ────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';

    if ($action === 'save_ai_settings') {
        $provider = in_array($_POST['ai_provider'] ?? '', ['deepseek','anthropic']) ? $_POST['ai_provider'] : 'deepseek';
        $aiData   = ['ai_provider' => $provider];
        // Only overwrite keys if something new was typed (not placeholder bullets)
        $dsKey = trim($_POST['deepseek_api_key'] ?? '');
        if ($dsKey !== '' && strpos($dsKey, '••••') === false) $aiData['deepseek_api_key'] = $dsKey;
        $antKey = trim($_POST['anthropic_api_key'] ?? '');
        if ($antKey !== '' && strpos($antKey, '••••') === false) {
            // Store in studio_settings for per-user override; also try updating config-level constant
            $aiData['anthropic_api_key'] = $antKey;
        }
        saveStudioSettings($user['id'], $aiData);
        flash('success', 'AI settings saved.');
        redirect(APP_URL . '/admin.php?tab=ai');
    }

    if ($action === 'save_studio') {
        saveStudioSettings($user['id'], [
            'studio_name'  => trim($_POST['studio_name']  ?? ''),
            'owner_name'   => trim($_POST['owner_name']   ?? ''),
            'address'      => trim($_POST['address']      ?? ''),
            'tax_id'       => trim($_POST['tax_id']       ?? ''),
            'phone'        => trim($_POST['phone']        ?? ''),
            'email'        => trim($_POST['email']        ?? ''),
            'website'      => trim($_POST['website']      ?? ''),
            'logo_url'     => trim($_POST['logo_url']     ?? ''),
            'accent_color' => trim($_POST['accent_color'] ?? '#5b5ef4'),
        ]);
        flash('success', 'Studio branding saved.');
        redirect(APP_URL . '/admin.php?tab=studio');
    }

    if ($action === 'save_invoice_settings') {
        saveStudioSettings($user['id'], [
            'invoice_prefix'      => trim($_POST['invoice_prefix']      ?? 'INV'),
            'invoice_next_number' => max(1, (int)($_POST['invoice_next_number'] ?? 1)),
            'default_currency'    => in_array($_POST['default_currency'] ?? '', ['USD','EUR','GBP'])
                                      ? $_POST['default_currency'] : 'USD',
            'payment_due_days'    => max(0, (int)($_POST['payment_due_days'] ?? 30)),
            'invoice_footer'      => trim($_POST['invoice_footer'] ?? 'Thank you for your business!'),
        ]);
        flash('success', 'Invoice settings saved.');
        redirect(APP_URL . '/admin.php?tab=invoice');
    }

    if ($action === 'save_bank') {
        saveStudioSettings($user['id'], [
            'bank_details' => trim($_POST['bank_details'] ?? ''),
        ]);
        flash('success', 'Bank details saved.');
        redirect(APP_URL . '/admin.php?tab=bank');
    }

    if ($action === 'save_smtp') {
        $smtpData = [
            'smtp_host'       => trim($_POST['smtp_host']       ?? ''),
            'smtp_port'       => max(1, (int)($_POST['smtp_port'] ?? 587)),
            'smtp_user'       => trim($_POST['smtp_user']       ?? ''),
            'smtp_from_name'  => trim($_POST['smtp_from_name']  ?? ''),
            'smtp_encryption' => in_array($_POST['smtp_encryption'] ?? '', ['tls','ssl','none'])
                                  ? $_POST['smtp_encryption'] : 'tls',
        ];
        // Only overwrite password if user typed something new (not the placeholder bullets)
        $newPass = $_POST['smtp_pass'] ?? '';
        if ($newPass !== '' && $newPass !== '••••••••') {
            $smtpData['smtp_pass'] = trim($newPass);
        }
        saveStudioSettings($user['id'], $smtpData);
        flash('success', 'SMTP settings saved.');
        redirect(APP_URL . '/admin.php?tab=email');
    }

    if ($action === 'update_user_role' && $isAdmin) {
        $uid  = (int)($_POST['uid'] ?? 0);
        $role = in_array($_POST['role'] ?? '', ['admin','designer']) ? $_POST['role'] : 'designer';
        if ($uid && $uid !== $user['id']) {
            update('users', ['role' => $role], 'id = ?', [$uid]);
            flash('success', 'Role updated.');
        }
        redirect(APP_URL . '/admin.php?tab=users');
    }

    if ($action === 'delete_user' && $isAdmin) {
        $uid = (int)($_POST['uid'] ?? 0);
        if ($uid && $uid !== $user['id']) {
            query("DELETE FROM users WHERE id = ?", [$uid]);
            flash('success', 'User deleted.');
        }
        redirect(APP_URL . '/admin.php?tab=users');
    }
}

// ── Load settings ──────────────────────────────────────────────────────────────
$s = getStudioSettings($user['id']);

renderHead('Studio Admin');
renderNav($user);
renderFlash();
?>

<?php renderPageHeader('Studio Admin', 'Branding, invoicing & system settings'); ?>

<!-- Tabs -->
<div class="tabs" style="margin-bottom:24px;">
  <?php
  $tabs = ['studio' => 'Branding', 'invoice' => 'Invoice', 'bank' => 'Bank Details', 'email' => 'Email / SMTP', 'ai' => '🤖 AI Settings'];
  if ($isAdmin) $tabs['users'] = 'Users';
  foreach ($tabs as $key => $label):
  ?>
  <a href="admin.php?tab=<?= $key ?>" class="tab <?= $tab === $key ? 'active' : '' ?>"><?= $label ?></a>
  <?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     TAB: STUDIO BRANDING
═══════════════════════════════════════════════════════════════════════ -->
<?php if ($tab === 'studio'): ?>
<div class="card" style="max-width:660px;">
  <h2 class="card-title">Studio Branding</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">This information appears on every invoice PDF.</p>

  <?php
  $logoPreviewUrl = $s['logo_url'] ?: 'https://rakibhasaan.com/wp-content/uploads/2024/09/Rakib-hasan-logo-e1726952149161.webp';
  ?>

  <!-- Logo preview -->
  <div style="display:flex;align-items:center;gap:20px;padding:16px;background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius-lg);margin-bottom:24px;">
    <img id="logo-preview"
         src="<?= e($logoPreviewUrl) ?>"
         style="height:48px;max-width:160px;object-fit:contain;"
         onerror="this.style.display='none'">
    <div>
      <div style="font-size:12px;font-weight:600;color:var(--text);margin-bottom:3px;">Logo Preview</div>
      <div style="font-size:11px;color:var(--text2);">Paste a logo URL below — PNG, JPG, or WebP recommended.</div>
    </div>
  </div>

  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_studio">

    <div class="form-group">
      <label>Logo URL</label>
      <input type="url" name="logo_url" id="logo-url-input"
             value="<?= e($s['logo_url']) ?>"
             placeholder="https://yoursite.com/logo.png"
             oninput="document.getElementById('logo-preview').src=this.value||'about:blank'">
      <small style="color:var(--text2);font-size:11px;margin-top:4px;display:block">
        Tip: use a transparent PNG or WebP for best results. Recommended height: 60–80px.
      </small>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Studio / Company Name</label>
        <input type="text" name="studio_name" value="<?= e($s['studio_name']) ?>" placeholder="e.g. Three R Enterprise">
      </div>
      <div class="form-group">
        <label>Owner / Your Name</label>
        <input type="text" name="owner_name" value="<?= e($s['owner_name'] ?: $user['name']) ?>" placeholder="<?= e($user['name']) ?>">
      </div>
    </div>

    <div class="form-group">
      <label>Business Address</label>
      <textarea name="address" rows="3" placeholder="Street&#10;City, State ZIP&#10;Country"><?= e($s['address']) ?></textarea>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Tax ID / VAT Number</label>
        <input type="text" name="tax_id" value="<?= e($s['tax_id']) ?>" placeholder="e.g. 340458298650">
      </div>
      <div class="form-group">
        <label>Phone</label>
        <input type="text" name="phone" value="<?= e($s['phone']) ?>" placeholder="+1 555 000 0000">
      </div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Email</label>
        <input type="email" name="email" value="<?= e($s['email'] ?: $user['email']) ?>" placeholder="support@yourstudio.com">
      </div>
      <div class="form-group">
        <label>Website</label>
        <input type="url" name="website" value="<?= e($s['website']) ?>" placeholder="https://yourstudio.com">
      </div>
    </div>

    <div class="form-group">
      <label>Invoice Accent Color <small style="font-size:11px;font-weight:400;color:var(--text2)">(used in PDF header, table headers, totals)</small></label>
      <div style="display:flex;align-items:center;gap:12px;">
        <input type="color" name="accent_color" value="<?= e($s['accent_color'] ?: '#5b5ef4') ?>"
               style="width:48px;height:38px;border:1px solid var(--border);border-radius:8px;background:var(--bg3);cursor:pointer;padding:3px;">
        <input type="text" id="accent-hex"
               value="<?= e($s['accent_color'] ?: '#5b5ef4') ?>"
               style="width:110px"
               oninput="document.querySelector('[name=accent_color]').value=this.value">
        <div style="display:flex;gap:6px;flex-wrap:wrap;">
          <?php foreach (['#5b5ef4','#0ea5e9','#10b981','#f59e0b','#ef4444','#8b5cf6','#1a1a2e','#374151'] as $c): ?>
          <div onclick="document.querySelector('[name=accent_color]').value='<?= $c ?>';document.getElementById('accent-hex').value='<?= $c ?>';"
               style="width:24px;height:24px;background:<?= $c ?>;border-radius:50%;cursor:pointer;border:2px solid transparent;transition:.15s"
               onmouseover="this.style.borderColor='var(--text2)'" onmouseout="this.style.borderColor='transparent'"></div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>

    <button class="btn btn-primary" type="submit">Save Branding</button>
  </form>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     TAB: INVOICE SETTINGS
═══════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'invoice'): ?>
<div class="card" style="max-width:560px;">
  <h2 class="card-title">Invoice Settings</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">Numbering, currency defaults, and invoice footer.</p>

  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_invoice_settings">

    <div class="form-group">
      <label>Invoice Number Preview</label>
      <div style="font-size:20px;font-weight:700;color:var(--accent2);padding:10px 14px;background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius);display:inline-block;" id="inv-preview">
        <?= e(nextInvoiceNumber($user['id'])) ?>
      </div>
      <small style="color:var(--text2);font-size:11px;margin-top:6px;display:block">This is the number that will be assigned to your next invoice.</small>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Prefix</label>
        <input type="text" name="invoice_prefix" id="prefix-input"
               value="<?= e($s['invoice_prefix']) ?>" placeholder="INV" maxlength="10"
               oninput="updatePreview()">
        <small style="color:var(--text2);font-size:11px">e.g. INV, 3RE, STUDIO</small>
      </div>
      <div class="form-group">
        <label>Next Number</label>
        <input type="number" name="invoice_next_number" id="num-input"
               value="<?= e($s['invoice_next_number']) ?>" min="1" oninput="updatePreview()">
        <small style="color:var(--text2);font-size:11px">Auto-increments after each invoice</small>
      </div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>Default Currency</label>
        <select name="default_currency">
          <?php foreach (['USD' => '$ USD — US Dollar', 'EUR' => '€ EUR — Euro', 'GBP' => '£ GBP — British Pound'] as $code => $label): ?>
          <option value="<?= $code ?>" <?= ($s['default_currency'] ?? 'USD') === $code ? 'selected' : '' ?>><?= $label ?></option>
          <?php endforeach; ?>
        </select>
        <small style="color:var(--text2);font-size:11px">Can be overridden per-client and per-invoice</small>
      </div>
      <div class="form-group">
        <label>Payment Due (days)</label>
        <input type="number" name="payment_due_days" value="<?= e($s['payment_due_days'] ?? 30) ?>" min="0" max="365">
        <small style="color:var(--text2);font-size:11px">Days after issue date (e.g. 30)</small>
      </div>
    </div>

    <div class="form-group">
      <label>Invoice Footer Text</label>
      <input type="text" name="invoice_footer"
             value="<?= e($s['invoice_footer'] ?: 'Thank you for your business!') ?>"
             placeholder="Thank you for your business!">
      <small style="color:var(--text2);font-size:11px">Appears at the bottom of every invoice PDF</small>
    </div>

    <button class="btn btn-primary" type="submit">Save Invoice Settings</button>
  </form>
</div>

<script>
function updatePreview() {
  var prefix = document.getElementById('prefix-input').value || 'INV';
  var num    = parseInt(document.getElementById('num-input').value) || 1;
  var padded = String(num).padStart(4, '0');
  document.getElementById('inv-preview').textContent = prefix + '-' + padded;
}
</script>

<!-- ═══════════════════════════════════════════════════════════════════════
     TAB: BANK DETAILS
═══════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'bank'): ?>
<div class="card" style="max-width:640px;">
  <h2 class="card-title">Bank / Payment Details</h2>
  <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">
    This text appears in the <strong>Payment Details</strong> section of every invoice PDF, exactly as you write it. One item per line.
  </p>

  <!-- Preview panel -->
  <div style="background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius-lg);padding:16px 18px;margin-bottom:24px;border-left:3px solid var(--accent);">
    <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--accent2);margin-bottom:10px;">PDF Preview</div>
    <?php
    $bankLines = array_filter(array_map('trim', explode("\n", $s['bank_details'] ?? '')));
    if ($bankLines):
      foreach ($bankLines as $line): ?>
      <div style="font-size:12px;color:var(--text2);margin-bottom:3px;"><?= e($line) ?></div>
    <?php endforeach;
    else: ?>
      <div style="font-size:12px;color:var(--text2);font-style:italic;">No bank details saved yet.</div>
    <?php endif; ?>
  </div>

  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
    <input type="hidden" name="action" value="save_bank">
    <div class="form-group">
      <label>Bank Details (one item per line)</label>
      <textarea name="bank_details" rows="14" placeholder="Send money to — Bangladesh&#10;Receiving option — Bank Deposit&#10;Bank Name — Dutch-Bangla Bank&#10;Account Number — 1251510372678&#10;SWIFT Code — DBBLBDDH&#10;Routing Number — 090100378&#10;&#10;Recipient Address:&#10;Rakibul Islam&#10;Bogra, Bogra Zila 5800&#10;Phone: +8801722536564"><?= e($s['bank_details'] ?? '') ?></textarea>
    </div>
    <button class="btn btn-primary" type="submit">Save Bank Details</button>
  </form>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     TAB: EMAIL / SMTP
═══════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'email'): ?>
<div style="max-width:640px;display:flex;flex-direction:column;gap:24px;">

  <div class="card">
    <h2 class="card-title">Email / SMTP Settings</h2>
    <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">
      Configure SMTP to send invoices directly from Debrieft.
      If left blank, PHP's built-in <code>mail()</code> is used (may not work on all hosts).
    </p>

    <form method="POST">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <input type="hidden" name="action" value="save_smtp">

      <div class="form-group">
        <label>From Name <small style="font-weight:400;color:var(--text2);">(shown in client's inbox)</small></label>
        <input type="text" name="smtp_from_name" value="<?= e($s['smtp_from_name'] ?: ($s['studio_name'] ?: $user['name'])) ?>" placeholder="<?= e($user['name']) ?>">
      </div>

      <div class="form-row">
        <div class="form-group">
          <label>SMTP Host</label>
          <input type="text" name="smtp_host" value="<?= e($s['smtp_host']) ?>" placeholder="smtp.gmail.com">
        </div>
        <div class="form-group">
          <label>SMTP Port</label>
          <input type="number" name="smtp_port" value="<?= e($s['smtp_port'] ?? 587) ?>" placeholder="587">
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
          <label>SMTP Username</label>
          <input type="email" name="smtp_user" value="<?= e($s['smtp_user']) ?>" placeholder="you@gmail.com" autocomplete="off">
        </div>
        <div class="form-group">
          <label>SMTP Password / App Password</label>
          <input type="password" name="smtp_pass" value="<?= $s['smtp_pass'] ? '••••••••' : '' ?>" placeholder="••••••••" autocomplete="new-password">
          <small style="color:var(--text2);font-size:11px">Leave unchanged to keep current password</small>
        </div>
      </div>

      <div class="form-group">
        <label>Encryption</label>
        <select name="smtp_encryption">
          <option value="tls"  <?= ($s['smtp_encryption'] ?? 'tls') === 'tls'  ? 'selected' : '' ?>>TLS / STARTTLS (port 587) — recommended</option>
          <option value="ssl"  <?= ($s['smtp_encryption'] ?? '')     === 'ssl'  ? 'selected' : '' ?>>SSL (port 465)</option>
          <option value="none" <?= ($s['smtp_encryption'] ?? '')     === 'none' ? 'selected' : '' ?>>None (not recommended)</option>
        </select>
      </div>

      <button class="btn btn-primary" type="submit">Save SMTP Settings</button>
    </form>
  </div>

  <div class="card">
    <h2 class="card-title" style="font-size:14px;">Common SMTP Providers</h2>
    <?php
    $providers = [
      'Gmail'     => ['smtp.gmail.com', 587, 'TLS', 'Use an App Password (not your Google password). Enable 2FA first.'],
      'Outlook'   => ['smtp.office365.com', 587, 'TLS', 'Use your Microsoft 365 email and password.'],
      'Brevo'     => ['smtp-relay.brevo.com', 587, 'TLS', 'Free up to 300 emails/day. Generate an SMTP key in your account.'],
      'Mailgun'   => ['smtp.mailgun.org', 587, 'TLS', 'Reliable transactional email. Good for client-facing invoices.'],
    ];
    foreach ($providers as $name => [$host, $port, $enc, $note]): ?>
    <div style="display:flex;gap:14px;padding:10px 0;border-bottom:1px solid var(--border);align-items:flex-start;">
      <div style="font-weight:600;font-size:13px;min-width:80px;color:var(--accent2)"><?= $name ?></div>
      <div>
        <code style="font-size:11px;color:var(--text2)"><?= $host ?></code>
        <span style="font-size:11px;color:var(--text2);margin-left:8px">Port <?= $port ?> · <?= $enc ?></span>
        <div style="font-size:11px;color:var(--text2);margin-top:2px"><?= $note ?></div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     TAB: USERS (admin only)
═══════════════════════════════════════════════════════════════════════ -->
<?php elseif ($tab === 'ai'): ?>
<div style="max-width:640px;display:flex;flex-direction:column;gap:24px;">

  <div class="card">
    <h2 class="card-title">🤖 AI Provider Settings</h2>
    <p style="font-size:13px;color:var(--text2);margin-bottom:24px;">
      Choose which AI powers brief &amp; spec generation.
      <strong>DeepSeek is free</strong> — sign up at
      <a href="https://platform.deepseek.com" target="_blank" style="color:var(--accent2)">platform.deepseek.com</a>
      and get 500M free tokens on registration.
    </p>

    <form method="POST">
      <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
      <input type="hidden" name="action" value="save_ai_settings">

      <div class="form-group">
        <label>AI Provider</label>
        <div style="display:flex;flex-direction:column;gap:10px;margin-top:4px;">
          <?php
          $curProvider = $s['ai_provider'] ?? 'deepseek';
          $providers = [
            'deepseek'  => ['🟢 DeepSeek (Recommended — Free tier available)', 'deepseek-chat model · OpenAI-compatible · Excellent quality · Much cheaper than Anthropic'],
            'anthropic' => ['🔵 Anthropic Claude', 'Claude Sonnet · Highest quality · Requires paid API key'],
          ];
          foreach ($providers as $val => [$label, $desc]):
          ?>
          <label style="display:flex;gap:12px;align-items:flex-start;padding:14px 16px;border:2px solid <?= $curProvider === $val ? 'var(--accent)' : 'var(--border)' ?>;border-radius:var(--radius-lg);cursor:pointer;transition:.15s;"
                 onclick="document.querySelectorAll('.provider-opt').forEach(el=>el.style.borderColor='var(--border)');this.style.borderColor='var(--accent)'">
            <input type="radio" name="ai_provider" value="<?= $val ?>" <?= $curProvider === $val ? 'checked' : '' ?>
                   style="margin-top:3px;accent-color:var(--accent)">
            <div>
              <div style="font-weight:600;font-size:13px;"><?= $label ?></div>
              <div style="font-size:11px;color:var(--text2);margin-top:2px;"><?= $desc ?></div>
            </div>
          </label>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="form-group">
        <label>DeepSeek API Key
          <small style="font-weight:400;color:var(--text2);">
            — Get free at <a href="https://platform.deepseek.com/api_keys" target="_blank" style="color:var(--accent2)">platform.deepseek.com/api_keys</a>
          </small>
        </label>
        <input type="text" name="deepseek_api_key"
               value="<?= $s['deepseek_api_key'] ? '••••••••' . substr($s['deepseek_api_key'], -4) : '' ?>"
               placeholder="sk-xxxxxxxxxxxxxxxxxxxxxxxx"
               autocomplete="off">
        <small style="color:var(--text2);font-size:11px;margin-top:4px;display:block">
          Starts with <code>sk-</code>. Leave blank to keep existing key.
        </small>
      </div>

      <div class="form-group">
        <label>Anthropic API Key
          <small style="font-weight:400;color:var(--text2);">
            — Get at <a href="https://console.anthropic.com/settings/keys" target="_blank" style="color:var(--accent2)">console.anthropic.com</a>
          </small>
        </label>
        <input type="text" name="anthropic_api_key"
               value="<?= ($s['anthropic_api_key'] ?? '') ? '••••••••' . substr($s['anthropic_api_key'], -4) : '' ?>"
               placeholder="sk-ant-xxxxxxxxxxxxxxxx"
               autocomplete="off">
        <small style="color:var(--text2);font-size:11px;margin-top:4px;display:block">
          Required if using Anthropic Claude as provider. Leave blank to keep existing key.
        </small>
      </div>

      <button class="btn btn-primary" type="submit">Save AI Settings</button>
    </form>
  </div>

  <!-- How to get DeepSeek key -->
  <div class="card">
    <h2 class="card-title" style="font-size:14px;">How to get a free DeepSeek API key</h2>
    <?php
    $steps = [
      '1' => ['Go to', 'platform.deepseek.com', 'https://platform.deepseek.com', 'and create a free account'],
      '2' => ['Click', 'API Keys', null, 'in the left sidebar'],
      '3' => ['Click', 'Create new API key', null, '— name it "Debrieft"'],
      '4' => ['Copy the key', '(starts with sk-)', null, 'and paste it above'],
      '5' => ['You get', '500M free tokens', null, 'on signup — enough for thousands of briefs'],
    ];
    foreach ($steps as $num => [$a, $b, $link, $c]): ?>
    <div style="display:flex;gap:14px;align-items:flex-start;padding:10px 0;border-bottom:1px solid var(--border);">
      <div style="width:24px;height:24px;background:var(--accent);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:#fff;flex-shrink:0;"><?= $num ?></div>
      <div style="font-size:13px;color:var(--text2);line-height:1.5;">
        <?= $a ?> <?= $link ? '<a href="' . $link . '" target="_blank" style="color:var(--accent2)">' . $b . '</a>' : '<strong style="color:var(--text)">' . $b . '</strong>' ?> <?= $c ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<?php elseif ($tab === 'users' && $isAdmin):
  $allUsers = fetchAll("SELECT u.*, (SELECT COUNT(*) FROM projects p WHERE p.user_id = u.id) AS project_count FROM users u ORDER BY u.created_at DESC");
?>
<div class="card">
  <h2 class="card-title">All Users</h2>
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Name</th><th>Email</th><th>Role</th><th>Company</th><th>Projects</th><th>Since</th><th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($allUsers as $u): ?>
        <tr>
          <td>
            <strong><?= e($u['name']) ?></strong>
            <?php if ((int)$u['id'] === (int)$user['id']): ?>
            <span class="badge badge-blue" style="margin-left:6px;font-size:10px">You</span>
            <?php endif; ?>
          </td>
          <td style="color:var(--text2)"><?= e($u['email']) ?></td>
          <td>
            <?php if ((int)$u['id'] !== (int)$user['id']): ?>
            <div style="display:flex;gap:6px;align-items:center">
            <form method="POST">
              <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
              <input type="hidden" name="action" value="update_user_role">
              <input type="hidden" name="uid" value="<?= $u['id'] ?>">
              <select name="role" onchange="this.form.submit()" style="font-size:12px;padding:4px 8px;">
                <option value="designer" <?= $u['role'] === 'designer' ? 'selected' : '' ?>>Designer</option>
                <option value="admin"    <?= $u['role'] === 'admin'    ? 'selected' : '' ?>>Admin</option>
              </select>
            </form>
            </div>
            <?php else: ?>
            <?= statusBadge($u['role']) ?>
            <?php endif; ?>
          </td>
          <td style="color:var(--text2)"><?= e($u['company'] ?? '—') ?></td>
          <td style="color:var(--text2)"><?= $u['project_count'] ?></td>
          <td style="color:var(--text2)"><?= formatDate($u['created_at']) ?></td>
          <td>
            <?php if ((int)$u['id'] !== (int)$user['id']): ?>
            <form method="POST" style="display:inline">
              <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
              <input type="hidden" name="action" value="delete_user">
              <input type="hidden" name="uid" value="<?= $u['id'] ?>">
              <button type="submit" class="btn btn-ghost btn-sm" data-confirm="Delete this user and ALL their data? This cannot be undone.">Delete</button>
            </form>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php elseif ($tab === 'users' && !$isAdmin): ?>
<div class="card"><div class="empty-state"><div class="big-icon">🔒</div><h3>Admin only</h3><p>User management requires admin role.</p></div></div>
<?php endif; ?>

<?php renderFooter(); ?>
