<?php
// /admin/company_settings.php
// Company-level settings + users + SSO, styled like main Towlens admin UI.

session_start();

$config = require __DIR__ . '/../lib/config.php';
require __DIR__ . '/../lib/db.php';
require __DIR__ . '/../lib/helpers.php';
require __DIR__ . '/../lib/sso_settings.php';

// If your require_admin_auth() currently only allows "admin"/"org_admin",
// you can switch this to a generic "require_auth" if you have it.
// For now we keep it to enforce login; role checks are done below.
require_admin_auth($config);

$base   = rtrim($config['base_url'] ?? '', '/');
$isDemo = !empty($config['demo_mode']);

if ($pdo instanceof PDO) {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

$me = $_SESSION['user'] ?? [];
if (!$me) {
    http_response_code(403);
    exit('Not signed in.');
}

$role     = $me['role'] ?? '';
$orgId    = (int)($me['organisation_id'] ?? 0);
$companyId= (int)($me['company_id'] ?? 0);

// Who can manage this page:
// - admin
// - org_admin
// - company_admin   (NEW)
$canManageCompany = in_array($role, ['admin', 'company_admin'], true);

if ($orgId <= 0 || $companyId <= 0 || !$canManageCompany) {
    http_response_code(403);
    exit('You do not have permission to manage settings.');
}

// Full "system" admin for nav etc (no change)
$isSystemAdmin = in_array($role, ['admin', 'company_admin'], true);

/* ---------- Load company ---------- */

$companyStmt = $pdo->prepare("
    SELECT id, organisation_id, name, brand_name, brand_subtitle,
           brand_color, logo_url, support_email, slug, status, created_at
    FROM companies
    WHERE id = ? AND organisation_id = ?
    LIMIT 1
");
$companyStmt->execute([$companyId, $orgId]);
$company = $companyStmt->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    http_response_code(404);
    exit('Company not found.');
}

/* ---------- Ensure / load SSO row ---------- */

ensure_company_sso_table($pdo);

$ssoStmt = $pdo->prepare("
    SELECT *
    FROM company_sso_settings
    WHERE company_id = ? AND organisation_id = ?
    LIMIT 1
");
$ssoStmt->execute([$companyId, $orgId]);
$companySso = $ssoStmt->fetch(PDO::FETCH_ASSOC);

if (!$companySso) {
    $companySso = [
        'id'                      => null,
        'organisation_id'         => $orgId,
        'company_id'              => $companyId,
        'enabled'                 => 0,
        'tenant_id'               => '',
        'allowed_domains'         => '',
        'require_sso'             => 0,
        'allow_password_fallback' => 1,
        'created_at'              => null,
        'updated_at'              => null,
    ];
}

/* ---------- Load users for this company ---------- */

$usersStmt = $pdo->prepare("
    SELECT id, provider, oid, email, display_name, role, is_active,
           last_login_at, created_at
    FROM users
    WHERE organisation_id = ? AND company_id = ?
    ORDER BY email
");
$usersStmt->execute([$orgId, $companyId]);
$users = $usersStmt->fetchAll(PDO::FETCH_ASSOC);

/* ---------- CSRF ---------- */

function company_csrf_token(): string {
    if (empty($_SESSION['csrf_company_settings'])) {
        $_SESSION['csrf_company_settings'] = bin2hex(random_bytes(16));
    }
    return $_SESSION['csrf_company_settings'];
}

function company_csrf_ok(): bool {
    return !empty($_POST['csrf'])
        && hash_equals($_SESSION['csrf_company_settings'] ?? '', $_POST['csrf']);
}

$errors  = [];
$notices = [];

/* ---------- Handle POST ---------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!company_csrf_ok()) {
        $errors[] = 'Your session expired. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';

        try {
            switch ($action) {
                case 'save_company':
                    // Allowed for company_admin and above
                    $brand_name     = trim($_POST['brand_name'] ?? '');
                    $brand_subtitle = trim($_POST['brand_subtitle'] ?? '');
                    $brand_color    = trim($_POST['brand_color'] ?? '');
                    $logo_url       = trim($_POST['logo_url'] ?? '');
                    $support_email  = trim($_POST['support_email'] ?? '');
                    $status         = trim($_POST['status'] ?? $company['status']);

                    $upd = $pdo->prepare("
                        UPDATE companies
                        SET brand_name = ?, brand_subtitle = ?, brand_color = ?,
                            logo_url = ?, support_email = ?, status = ?
                        WHERE id = ? AND organisation_id = ?
                        LIMIT 1
                    ");
                    $upd->execute([
                        $brand_name,
                        $brand_subtitle,
                        $brand_color,
                        $logo_url,
                        $support_email,
                        $status,
                        $companyId,
                        $orgId,
                    ]);

                    $notices[] = 'settings updated.';
                    break;

                case 'save_sso':
                    // Allowed for company_admin and above (still scoped to their company)
                    $enabled                 = !empty($_POST['sso_enabled']) ? 1 : 0;
                    $tenant_id               = trim($_POST['sso_tenant_id'] ?? '');
                    $allowed_domains_raw     = trim($_POST['sso_allowed_domains'] ?? '');
                    $require_sso             = !empty($_POST['sso_require_sso']) ? 1 : 0;
                    $allow_password_fallback = !empty($_POST['sso_allow_pw_fallback']) ? 1 : 0;

                    $allowed_domains = '';
                    if ($allowed_domains_raw !== '') {
                        $parts = array_filter(array_map('trim', preg_split('/[,\s]+/', $allowed_domains_raw)));
                        $allowed_domains = implode(',', $parts);
                    }

                    if ($companySso['id']) {
                        $upd = $pdo->prepare("
                            UPDATE company_sso_settings
                            SET enabled = ?, tenant_id = ?, allowed_domains = ?,
                                require_sso = ?, allow_password_fallback = ?
                            WHERE id = ? AND organisation_id = ? AND company_id = ?
                            LIMIT 1
                        ");
                        $upd->execute([
                            $enabled,
                            $tenant_id,
                            $allowed_domains,
                            $require_sso,
                            $allow_password_fallback,
                            $companySso['id'],
                            $orgId,
                            $companyId,
                        ]);
                    } else {
                        $ins = $pdo->prepare("
                            INSERT INTO company_sso_settings
                                (organisation_id, company_id, enabled, tenant_id,
                                 allowed_domains, require_sso, allow_password_fallback,
                                 created_at, updated_at)
                            VALUES (?,?,?,?,?,?,?,NOW(),NOW())
                        ");
                        $ins->execute([
                            $orgId,
                            $companyId,
                            $enabled,
                            $tenant_id,
                            $allowed_domains,
                            $require_sso,
                            $allow_password_fallback,
                        ]);
                    }

                    $notices[] = 'SSO settings updated for this company.';
                    break;

                case 'add_user':
                    $email    = trim($_POST['new_email'] ?? '');
                    $name     = trim($_POST['new_name'] ?? '');
                    $roleNew  = trim($_POST['new_role'] ?? 'staff');
                    $password = (string)($_POST['new_password'] ?? '');

                    if ($email === '') {
                        $errors[] = 'Email is required for new user.';
                        break;
                    }

                    $chk = $pdo->prepare("
                        SELECT id FROM users
                        WHERE organisation_id = ? AND company_id = ? AND email = ?
                        LIMIT 1
                    ");
                    $chk->execute([$orgId, $companyId, $email]);
                    if ($chk->fetchColumn()) {
                        $errors[] = 'A user with that email already exists in this company.';
                        break;
                    }

                    $provider = $password !== '' ? 'local' : 'entra';
                    $hash     = $password !== '' ? password_hash($password, PASSWORD_DEFAULT) : null;

                    $ins = $pdo->prepare("
                        INSERT INTO users
                            (organisation_id, company_id, provider, oid,
                             email, display_name, role, is_active,
                             created_at, last_login_at, password_hash)
                        VALUES (?,?,?,?,?,?,?,?,NOW(),NULL,?)
                    ");
                    $ins->execute([
                        $orgId,
                        $companyId,
                        $provider,
                        null,
                        $email,
                        ($name !== '' ? $name : $email),
                        ($roleNew !== '' ? $roleNew : 'staff'),
                        1,
                        $hash,
                    ]);

                    $notices[] = 'User added.';
                    break;

                case 'toggle_user_active':
                    $uid = (int)($_POST['user_id'] ?? 0);
                    if ($uid > 0 && $uid !== (int)$me['id']) {
                        $sel = $pdo->prepare("
                            SELECT id, is_active
                            FROM users
                            WHERE id = ? AND organisation_id = ? AND company_id = ?
                            LIMIT 1
                        ");
                        $sel->execute([$uid, $orgId, $companyId]);
                        $u = $sel->fetch(PDO::FETCH_ASSOC);
                        if ($u) {
                            $new = $u['is_active'] ? 0 : 1;
                            $upd = $pdo->prepare("UPDATE users SET is_active = ? WHERE id = ? LIMIT 1");
                            $upd->execute([$new, $uid]);
                            $notices[] = 'User ' . ($new ? 'activated.' : 'deactivated.');
                        }
                    }
                    break;

                case 'delete_user':
                    $uid = (int)($_POST['user_id'] ?? 0);
                    if ($uid > 0 && $uid !== (int)$me['id']) {
                        $del = $pdo->prepare("
                            DELETE FROM users
                            WHERE id = ? AND organisation_id = ? AND company_id = ?
                            LIMIT 1
                        ");
                        $del->execute([$uid, $orgId, $companyId]);
                        $notices[] = 'User removed.';
                    }
                    break;

                case 'update_user_role':
                    $uid     = (int)($_POST['user_id'] ?? 0);
                    $roleNew = trim($_POST['role'] ?? '');
                    if ($uid > 0 && $uid !== (int)$me['id'] && $roleNew !== '') {
                        $upd = $pdo->prepare("
                            UPDATE users
                            SET role = ?
                            WHERE id = ? AND organisation_id = ? AND company_id = ?
                            LIMIT 1
                        ");
                        $upd->execute([$roleNew, $uid, $orgId, $companyId]);
                        $notices[] = 'User role updated.';
                    }
                    break;
            }
        } catch (Throwable $e) {
            $errors[] = 'Save failed: ' . esc($e->getMessage());
        }
    }

    // Reload after changes
    $companyStmt->execute([$companyId, $orgId]);
    $company = $companyStmt->fetch(PDO::FETCH_ASSOC);

    $ssoStmt->execute([$companyId, $orgId]);
    $companySso = $ssoStmt->fetch(PDO::FETCH_ASSOC) ?: $companySso;

    $usersStmt->execute([$orgId, $companyId]);
    $users = $usersStmt->fetchAll(PDO::FETCH_ASSOC);
}

$csrf = company_csrf_token();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Towlens — settings<?= $isDemo ? ' (Demo Mode)' : '' ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
  ::-webkit-scrollbar{width:10px;height:10px}
  ::-webkit-scrollbar-track{background:#f1f4f8;border-left:1px solid var(--line)}
  ::-webkit-scrollbar-thumb{background:linear-gradient(var(--brand),var(--brand-dark));border-radius:5px;border:1px solid rgba(255,255,255,0.4)}
  ::-webkit-scrollbar-thumb:hover{background:linear-gradient(var(--brand-dark),#1e4c83)}
  *{scrollbar-width:thin;scrollbar-color:var(--brand) #f1f4f8}

  :root{
    --bg:#eceff3; --win:#ffffff; --ink:#1f2933; --muted:#5d6b78; --line:#cfd6de;
    --brand:#2f6db2; --brand-dark:#255a95;
    --ok:#3a7d3a; --danger:#b22f2f;
    --radius:4px;
    --shadow:0 1px 0 rgba(0,0,0,.04), 0 2px 4px rgba(0,0,0,.06);
    --hdr-grad: linear-gradient(#f8fafc, #e8edf3);
    --btn-grad: linear-gradient(#f8fafc, #e6ecf2);
    --btn-grad-active: linear-gradient(#e6ecf2, #d9e1e9);
    --tbl-head-grad: linear-gradient(#eef3f8, #e2e9f1);
  }
  *{box-sizing:border-box}
  html,body{height:100%}
  body{
    margin:0;
    font:13px/1.45 Segoe UI,Tahoma,Arial,Helvetica,sans-serif;
    color:var(--ink);
    background:var(--bg);
  }
  .app{min-height:100%;display:flex;flex-direction:column}

  .ribbon{
    background:var(--hdr-grad);
    border-bottom:1px solid var(--line);
    box-shadow:var(--shadow);
  }
  .ribbon-inner{
    max-width:1200px;
    margin:0 auto;
    padding:10px 14px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
  }
  .title{display:flex;align-items:center;gap:10px}
  .title .mark{
    width:28px;height:28px;border-radius:4px;
    background:#2f6db2;
    box-shadow:inset 0 0 0 1px rgba(255,255,255,.4);
  }
  h1{font-size:16px;margin:0}
  .sub{color:var(--muted);font-size:12px}

  .actions{display:flex;gap:8px;align-items:center}
  .btn{
    appearance:none;
    border:1px solid #bfc8d2;
    color:#123;
    background:var(--btn-grad);
    font-weight:600;
    padding:6px 10px;
    border-radius:var(--radius);
    cursor:pointer;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.85),0 1px 0 rgba(255,255,255,.5);
    font-size:12px;
    display:inline-flex;
    align-items:center;
    gap:4px;
  }
  .btn:hover{background:var(--btn-grad-active)}
  .btn.primary{
    border-color:#2a5f9c;
    color:#fff;
    background:linear-gradient(#3b79c1,#2b67ab);
  }
  .btn.primary:hover{
    background:linear-gradient(#366fb2,#255f9f);
  }
  .btn.small{padding:4px 8px;font-size:11px}
  .btn.danger{
    border-color:#dc2626;
    color:#b91c1c;
    background:#fef2f2;
  }

  .toolbar{
    background:#f4f7fa;
    border-bottom:1px solid var(--line);
  }
  .toolbar-inner{
    max-width:1200px;
    margin:0 auto;
    padding:8px 14px;
    display:flex;
    justify-content:space-between;
    align-items:flex-end;
    gap:12px;
    flex-wrap:wrap;
  }
  .toolbar-title{font-size:13px;color:var(--muted)}
  .toolbar-title strong{color:var(--ink)}
  .badge{
    display:inline-block;
    padding:2px 6px;
    font-size:10px;
    border-radius:999px;
    background:#e5e7eb;
    color:#4b5563;
    margin-left:6px;
  }

  .window{
    max-width:1200px;
    margin:16px auto 24px;
    padding:0 14px;
    width:100%;
  }
  .panel{
    background:var(--win);
    border:1px solid var(--line);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    padding:10px 10px 12px;
    margin-top:14px;
  }
  .panel h2{
    font-size:14px;
    margin:0 0 4px;
    font-weight:600;
  }
  .panel p.help{
    margin:0 0 6px;
    font-size:11px;
    color:var(--muted);
  }
  .grid{
    display:grid;
    grid-template-columns:1.2fr 1.2fr;
    gap:14px;
  }
  @media (max-width:880px){
    .grid{grid-template-columns:1fr;}
  }

  label{
    display:block;
    font-size:11px;
    color:var(--muted);
    margin-bottom:2px;
  }
  input[type=text],
  input[type=email],
  input[type=password],
  select{
    width:100%;
    padding:6px 8px;
    border-radius:var(--radius);
    border:1px solid var(--line);
    font-size:12px;
    background:#ffffff;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.85);
    outline:none;
  }
  input[readonly]{
    background:#f3f4f6;
    color:#6b7280;
  }
  input:focus,
  select:focus{
    border-color:#99b4d6;
    box-shadow:0 0 0 1px #e0ecff;
  }
  .row{display:flex;gap:8px;margin-bottom:6px}
  .row > div{flex:1}

  .msgs{margin-top:10px}
  .msgs .err,
  .msgs .note{
    padding:6px 8px;
    border-radius:4px;
    font-size:11px;
    margin-bottom:4px;
  }
  .msgs .err{
    background:#fef2f2;
    border:1px solid #fecaca;
    color:#991b1b;
  }
  .msgs .note{
    background:#ecfdf5;
    border:1px solid #bbf7d0;
    color:#166534;
  }

  .mini{font-size:10px;color:var(--muted)}

  table{
    border-collapse:separate;
    border-spacing:0;
    width:100%;
    background:#fff;
    font-size:11px;
  }
  thead th{
    background:var(--tbl-head-grad);
    border-bottom:1px solid var(--line);
    color:#2a3b4b;
    font-weight:700;
    text-align:left;
    padding:6px 8px;
    position:sticky;
    top:0;
    z-index:1;
  }
  tbody td{
    padding:6px 8px;
    border-bottom:1px solid #e7ecf1;
    vertical-align:middle;
  }
  tbody tr:nth-child(even){background:#fafbfd}
  .pill{
    display:inline-block;
    padding:2px 6px;
    border-radius:999px;
    background:#e5e7eb;
    color:#374151;
    font-size:9px;
  }
  .pill.ok{background:#dcfce7;color:#166534;}
  .pill.off{background:#fee2e2;color:#991b1b;}
  .pill.you{background:#e0f2fe;color:#075985;}
  .col-actions{white-space:nowrap}
  .aslink{
    background:none;
    border:0;
    padding:0;
    margin:0;
    font:inherit;
    color:#2f6db2;
    text-decoration:underline;
    cursor:pointer;
  }
  .aslink:hover{text-decoration:none;}

  footer{
    color:var(--muted);
    font-size:11px;
    text-align:center;
    margin:18px 0 4px;
  }

  html,body,.app,*{
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
    -webkit-touch-callout:none;
  }
  input,textarea,select,button,label{
    -webkit-user-select:auto;
    -moz-user-select:auto;
    -ms-user-select:auto;
    user-select:auto;
  }

  .demo-badge{
    position:fixed;
    right:12px;
    bottom:12px;
    background:#f8e9e9;
    color:#7a2222;
    border:1px solid #e0bcbc;
    border-radius:12px;
    padding:6px 10px;
    font-size:12px;
    box-shadow:var(--shadow);
  }
  </style>
</head>
<body class="<?= $isDemo ? 'demo' : '' ?>">
<div class="app">

  <!-- Ribbon -->
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title">
        <!-- <div class="mark" aria-hidden="true"></div> -->
        <div>
          <h1>Towlens</h1>
          <div class="sub">Vehicle Imaging System — Settings</div>
        </div>
      </div>
      <div class="actions">
        <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/index.php">Dashboard</button>
        <?php if ($isAdmin): ?>
          <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/settings.php">System Settings</button>
        <?php endif; ?>
        <button type="button" class="btn primary" data-nav="<?= esc($base) ?>/admin/logout.php">Logout</button>
      </div>
    </div>
  </div>

  <!-- Toolbar -->
  <div class="toolbar">
    <div class="toolbar-inner">
      <div class="toolbar-title">
        Managing settings for <strong><?= esc($company['name']) ?></strong>
        <span class="badge">Slug: <?= esc($company['slug']) ?></span>
      </div>
      <!-- <div class="mini">
        Accessible to company admin and above. Other settings remain restricted.
      </div> -->
    </div>
  </div>

  <!-- Main window -->
  <div class="window">

    <div class="msgs">
      <?php foreach ($errors as $m): ?>
        <div class="err"><?= esc($m) ?></div>
      <?php endforeach; ?>
      <?php foreach ($notices as $m): ?>
        <div class="note"><?= esc($m) ?></div>
      <?php endforeach; ?>
      <?php if ($isDemo): ?>
        <div class="note">Demo mode: some actions may be simulated.</div>
      <?php endif; ?>
    </div>

    <div class="grid">
      <!-- Company panel -->
      <div class="panel">
        <h2>Brand & Company</h2>
        <p class="help">Control how this company appears. The slug is fixed for routing and cannot be edited.</p>
        <form method="post">
          <input type="hidden" name="csrf" value="<?= esc($csrf) ?>">
          <input type="hidden" name="action" value="save_company">

          <div class="row">
            <div>
              <label>Company name</label>
              <input type="text" value="<?= esc($company['name']) ?>" readonly>
            </div>
            <div>
              <label>Slug</label>
              <input type="text" value="<?= esc($company['slug']) ?>" readonly>
            </div>
          </div>

          <div class="row">
            <div>
              <label>Brand name</label>
              <input type="text" name="brand_name" value="<?= esc($company['brand_name']) ?>">
            </div>
            <div>
              <label>Brand subtitle</label>
              <input type="text" name="brand_subtitle" value="<?= esc($company['brand_subtitle']) ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Brand color (hex) or standard colour label e.g. Blue</label>
              <input type="text" name="brand_color" placeholder="#2f6db2" value="<?= esc($company['brand_color']) ?>">
            </div>
            <div>
              <label>Logo URL</label>
              <input type="text" name="logo_url" value="<?= esc($company['logo_url']) ?>">
            </div>
          </div>

          <div class="row">
            <div>
              <label>Support email</label>
              <input type="email" name="support_email" value="<?= esc($company['support_email']) ?>">
            </div>
            <div>
              <label>Status</label>
              <?php $st = $company['status'] ?? 'active'; ?>
              <select name="status">
                <option value="active"   <?= $st==='active'?'selected':'' ?>>Active</option>
                <option value="inactive" <?= $st==='inactive'?'selected':'' ?>>Inactive</option>
                <option value="archived" <?= $st==='archived'?'selected':'' ?>>Archived</option>
              </select>
            </div>
          </div>

          <div style="margin-top:6px">
            <button type="submit" class="btn primary">Save settings</button>
          </div>
        </form>
      </div>

      <!-- SSO panel -->
      <div class="panel">
        <h2>SSO (Microsoft Entra)</h2>
        <p class="help">
          Map Entra sign-ins into this company.
          Use Tenant ID (tid) and/or allowed domains. Works with the global multi-tenant app.
        </p>
        <form method="post">
          <input type="hidden" name="csrf" value="<?= esc($csrf) ?>">
          <input type="hidden" name="action" value="save_sso">

          <div class="row">
            <div>
              <label>
                <input type="checkbox" name="sso_enabled" value="1"
                  <?= !empty($companySso['enabled']) ? 'checked' : '' ?>>
                Enable SSO for this company
              </label>
            </div>
          </div>

          <div class="row">
            <div>
              <label>Tenant ID (GUID)</label>
              <input type="text" name="sso_tenant_id" placeholder="Optional if using domains"
                     value="<?= esc($companySso['tenant_id'] ?? '') ?>">
              <div class="mini">Matches the <code>tid</code> claim. Leave blank to rely on domains only.</div>
            </div>
          </div>

          <div class="row">
            <div>
              <label>Allowed domains</label>
              <input type="text" name="sso_allowed_domains"
                     placeholder="example.com otherco.com"
                     value="<?= esc($companySso['allowed_domains'] ?? '') ?>">
              <div class="mini">Space or comma separated domains that should land in this company.</div>
            </div>
          </div>

          <div class="row">
            <div>
              <label>
                <input type="checkbox" name="sso_require_sso" value="1"
                  <?= !empty($companySso['require_sso']) ? 'checked' : '' ?>>
                Require SSO for this company
              </label>
              <div class="mini">If enabled, users are expected to sign in via Entra.</div>
            </div>
          </div>

          <div class="row">
            <div>
              <label>
                <input type="checkbox" name="sso_allow_pw_fallback" value="1"
                  <?= !empty($companySso['allow_password_fallback']) ? 'checked' : '' ?>>
                Allow password fallback
              </label>
              <div class="mini">If off and SSO is required, passwords are blocked for this company’s users.</div>
            </div>
          </div>

          <div style="margin-top:6px">
            <button type="submit" class="btn primary">Save SSO settings</button>
          </div>
        </form>
      </div>
    </div>

    <!-- Users panel -->
    <div class="panel">
      <div style="display:flex;justify-content:space-between;align-items:flex-end;gap:8px">
        <div>
          <h2>Users for this company</h2>
          <p class="help">Add or manage users scoped strictly to this company.</p>
        </div>
      </div>

      <!-- Add user -->
      <form method="post" style="margin-top:4px;margin-bottom:8px">
        <input type="hidden" name="csrf" value="<?= esc($csrf) ?>">
        <input type="hidden" name="action" value="add_user">
        <div class="row">
          <div>
            <label>Work email</label>
            <input type="email" name="new_email" placeholder="user@company.com" required>
          </div>
          <div>
            <label>Display name</label>
            <input type="text" name="new_name" placeholder="Optional">
          </div>
          <div>
            <label>Role</label>
            <select name="new_role">
              <option value="staff">Staff</option>
              <option value="company_admin">Company Admin</option>
            </select>
          </div>
          <div>
            <label>Password (optional)</label>
            <input type="password" name="new_password" placeholder="Blank = SSO only">
          </div>
          <div style="align-self:flex-end">
            <button type="submit" class="btn small">Add user</button>
          </div>
        </div>
      </form>

      <!-- Users table -->
      <div style="border:1px solid var(--line);border-radius:var(--radius);overflow:auto">
        <table>
          <thead>
          <tr>
            <th>Email</th>
            <th>Name</th>
            <th>Auth Provider</th>
            <th>Role</th>
            <th>Status</th>
            <th>Last login</th>
            <th class="col-actions">Actions</th>
          </tr>
          </thead>
          <tbody>
          <?php if (!$users): ?>
            <tr>
              <td colspan="7" class="mini" style="text-align:center;padding:10px">
                No users yet for this company.
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($users as $u): ?>
              <tr>
                <td><?= esc($u['email']) ?></td>
                <td><?= esc($u['display_name'] ?: $u['email']) ?></td>
                <td><span class="pill"><?= esc($u['provider'] ?: 'local') ?></span></td>
                <td>
                  <?php if ((int)$u['id'] === (int)$me['id']): ?>
                    <span class="pill you"><?= esc($u['role']) ?> (you)</span>
                  <?php else: ?>
                    <form method="post" style="display:inline">
                      <input type="hidden" name="csrf" value="<?= esc($csrf) ?>">
                      <input type="hidden" name="action" value="update_user_role">
                      <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                      <select name="role" onchange="this.form.submit()" style="font-size:10px;padding:2px 4px;">
                        <?php
                        $roles = ['staff' => 'Staff', 'company_admin' => 'Company admin'];
                        foreach ($roles as $rk => $rv): ?>
                          <option value="<?= esc($rk) ?>" <?= $u['role'] === $rk ? 'selected' : '' ?>>
                            <?= esc($rv) ?>
                          </option>
                        <?php endforeach; ?>
                      </select>
                    </form>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if ($u['is_active']): ?>
                    <span class="pill ok">Active</span>
                  <?php else: ?>
                    <span class="pill off">Inactive</span>
                  <?php endif; ?>
                </td>
                <td class="mini">
                  <?= $u['last_login_at'] ? esc($u['last_login_at']) : '—' ?>
                </td>
                <td class="col-actions">
                  <?php if ((int)$u['id'] !== (int)$me['id']): ?>
                    <form method="post" style="display:inline">
                      <input type="hidden" name="csrf" value="<?= esc($csrf) ?>">
                      <input type="hidden" name="action" value="toggle_user_active">
                      <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                      <button type="submit" class="btn small">
                        <?= $u['is_active'] ? 'Deactivate' : 'Activate' ?>
                      </button>
                    </form>
                    <form method="post" style="display:inline"
                          onsubmit="return confirm('Remove this user? This cannot be undone.');">
                      <input type="hidden" name="csrf" value="<?= esc($csrf) ?>">
                      <input type="hidden" name="action" value="delete_user">
                      <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
                      <button type="submit" class="btn small danger">Delete</button>
                    </form>
                  <?php else: ?>
                    <span class="mini">You</span>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

   <!-- <footer>
      <span>Powered by </span>
      <button type="button" class="aslink" data-open="https://mpmg.co.uk/software">
        Mount Pleasant Motoring Services
      </button>
    </footer>
  </div> -->

  <?php if ($isDemo): ?>
    <div class="demo-badge">DEMO</div>
  <?php endif; ?>
</div>

<script>
document.addEventListener('click', function(e){
  const navBtn = e.target.closest('[data-nav]');
  if (navBtn) {
    window.location.assign(navBtn.getAttribute('data-nav'));
    return;
  }
  const openBtn = e.target.closest('[data-open]');
  if (openBtn) {
    window.open(openBtn.getAttribute('data-open'), '_blank', 'noopener');
    return;
  }
});

// Block right-click to match main UI
window.addEventListener('contextmenu', function(e){
  e.preventDefault();
}, {capture:true});
</script>
</body>
</html>
