<?php
// admin/company_user_wizard.php
// Classic-style wizard to create a new company + first user for TowLens

session_start();

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

require_admin_auth($config); // Require signed-in admin/staff

// PDO error mode (dev-friendly)
if ($pdo instanceof PDO) {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

$base = rtrim($config['base_url'] ?? '', '/');

// Current user / tenancy (if needed later)
$me        = $_SESSION['user'] ?? [];
$orgId     = isset($me['organisation_id']) ? (int)$me['organisation_id'] : 0;
$role      = $me['role'] ?? '';
$isAdmin   = ($role === 'admin');
$isOrgAdmin= ($role === 'org_admin') || !empty($me['is_org_admin']);

if ($orgId <= 0 && !$isAdmin && !$isOrgAdmin) {
    // If your model requires org scope, you can enforce / tweak this.
    // For now, allow global admins; otherwise require org.
    // Adjust this if you want to allow cross-org creation.
    // http_response_code(403);
    // exit('Forbidden: no organisation scope.');
}

/** CSRF helpers **/
function wizard_csrf_token(): string {
    if (empty($_SESSION['wizard_csrf'])) {
        $_SESSION['wizard_csrf'] = bin2hex(random_bytes(16));
    }
    return $_SESSION['wizard_csrf'];
}
function wizard_csrf_ok(): bool {
    return !empty($_POST['csrf'])
        && !empty($_SESSION['wizard_csrf'])
        && hash_equals($_SESSION['wizard_csrf'], $_POST['csrf']);
}

/** Slug + uniqueness helpers **/
function make_slug(string $name): string {
    $s = strtolower(trim($name));
    $s = preg_replace('/[^a-z0-9]+/i', '-', $s);
    $s = trim($s, '-');
    return $s ?: 'client';
}
function unique_company_slug(PDO $pdo, string $slug): string {
    $base = $slug;
    $i = 1;
    while (true) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM companies WHERE slug = ?");
        $stmt->execute([$slug]);
        if ((int)$stmt->fetchColumn() === 0) {
            return $slug;
        }
        $slug = $base . '-' . (++$i);
    }
}

/** Load organisations for dropdown **/
$orgs = [];
try {
    $stmt = $pdo->query("SELECT id, name FROM organisations ORDER BY name");
    $orgs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // If no org table yet, leave empty – you can adapt.
}

/** Wizard state **/
$errors  = [];
$notices = [];
$step    = isset($_POST['step']) ? (int)$_POST['step'] : 1;

$company = $_SESSION['wizard_company'] ?? [
    'organisation_id' => $orgId ?: '',
    'name'            => '',
    'brand_name'      => '',
    'brand_subtitle'  => '',
    'brand_color'     => '',
    'logo_url'        => '',
    'support_email'   => '',
    'slug'            => '',
];

$user = $_SESSION['wizard_user'] ?? [
    'provider'     => 'entra', // default to SSO
    'oid'          => '',
    'email'        => '',
    'display_name' => '',
    'role'         => 'admin',
    'is_active'    => 1,
    'password'     => '',
];

/** Handle POST **/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!wizard_csrf_ok()) {
        $errors[] = 'Your session expired. Please reload the wizard.';
        $step = 1;
    } else {
        if ($step === 1) {
            // Collect + validate company
            $company['organisation_id'] = (int)($_POST['organisation_id'] ?? 0);
            $company['name']            = trim($_POST['name'] ?? '');
            $company['brand_name']      = trim($_POST['brand_name'] ?? '');
            $company['brand_subtitle']  = trim($_POST['brand_subtitle'] ?? '');
            $company['brand_color']     = trim($_POST['brand_color'] ?? '');
            $company['logo_url']        = trim($_POST['logo_url'] ?? '');
            $company['support_email']   = trim($_POST['support_email'] ?? '');
            $company['slug']            = trim($_POST['slug'] ?? '');

            if ($company['organisation_id'] <= 0) {
                $errors[] = 'Please select an organisation.';
            }
            if ($company['name'] === '') {
                $errors[] = 'Please enter a company name.';
            }

            if ($company['brand_name'] === '' && $company['name'] !== '') {
                $company['brand_name'] = $company['name'];
            }
            if ($company['slug'] === '' && $company['name'] !== '') {
                $company['slug'] = make_slug($company['name']);
            }

            if ($company['support_email'] !== '' &&
                !filter_var($company['support_email'], FILTER_VALIDATE_EMAIL)) {
                $errors[] = 'Support email is not a valid email address.';
            }

            if (!$errors) {
                $_SESSION['wizard_company'] = $company;
                $step = 2;
            } else {
                $step = 1;
            }
        } elseif ($step === 2) {
            // Collect + validate user, then create both records
            $user['provider']     = $_POST['provider'] ?? 'entra';
            $user['oid']          = trim($_POST['oid'] ?? '');
            $user['email']        = trim($_POST['email'] ?? '');
            $user['display_name'] = trim($_POST['display_name'] ?? '');
            $user['role']         = $_POST['role'] ?? 'admin';
            $user['is_active']    = isset($_POST['is_active']) ? 1 : 0;
            $user['password']     = $_POST['password'] ?? '';

            if ($user['email'] === '' || !filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
                $errors[] = 'Please enter a valid email address for the user.';
            }
            if ($user['display_name'] === '') {
                $errors[] = 'Please enter a display name for the user.';
            }
            if (!in_array($user['role'], ['admin', 'org_admin', 'company_admin', 'staff'], true)) {
                $errors[] = 'Invalid role selected.';
            }
            if ($user['provider'] === 'entra') {
                if ($user['oid'] === '') {
                    $errors[] = 'For Entra accounts, the user\'s OID is required.';
                }
            } else {
                if ($user['password'] === '') {
                    $errors[] = 'For local accounts, an initial password is required.';
                }
            }

            if (empty($_SESSION['wizard_company'])) {
                $errors[] = 'Company details missing. Please start again.';
            } else {
                $company = $_SESSION['wizard_company'];
            }

            if (!$errors) {
                try {
                    $pdo->beginTransaction();

                    // Ensure slug uniqueness
                    $slugBase = $company['slug'] ?: make_slug($company['name']);
                    $slug     = unique_company_slug($pdo, make_slug($slugBase));

                    // Insert company
                    $stmt = $pdo->prepare("
                        INSERT INTO companies
                          (organisation_id, name, brand_name, brand_subtitle, brand_color,
                           logo_url, support_email, slug, status, created_at)
                        VALUES
                          (:org_id, :name, :brand_name, :brand_subtitle, :brand_color,
                           :logo_url, :support_email, :slug, 'active', NOW())
                    ");
                    $stmt->execute([
                        ':org_id'        => $company['organisation_id'],
                        ':name'          => $company['name'],
                        ':brand_name'    => $company['brand_name'],
                        ':brand_subtitle'=> $company['brand_subtitle'],
                        ':brand_color'   => $company['brand_color'] ?: null,
                        ':logo_url'      => $company['logo_url'] ?: null,
                        ':support_email' => $company['support_email'] ?: null,
                        ':slug'          => $slug,
                    ]);
                    $companyId = (int)$pdo->lastInsertId();

                    // Insert user
                    $passwordHash = null;
                    if ($user['provider'] === 'local') {
                        $passwordHash = password_hash($user['password'], PASSWORD_DEFAULT);
                    }

                    $stmt = $pdo->prepare("
                        INSERT INTO users
                          (organisation_id, company_id, provider, oid, email,
                           display_name, role, is_active, created_at, password_hash)
                        VALUES
                          (:org_id, :company_id, :provider, :oid, :email,
                           :display_name, :role, :is_active, NOW(), :password_hash)
                    ");
                    $stmt->execute([
                        ':org_id'       => $company['organisation_id'],
                        ':company_id'   => $companyId,
                        ':provider'     => $user['provider'],
                        ':oid'          => $user['provider'] === 'entra' ? $user['oid'] : null,
                        ':email'        => $user['email'],
                        ':display_name' => $user['display_name'],
                        ':role'         => $user['role'],
                        ':is_active'    => $user['is_active'] ? 1 : 0,
                        ':password_hash'=> $passwordHash,
                    ]);

                    $pdo->commit();

                    // Clear wizard state
                    unset($_SESSION['wizard_company'], $_SESSION['wizard_user'], $_SESSION['wizard_csrf']);

                    $notices[] = "Company '{$company['name']}' and user '{$user['email']}' have been created.";
                    $step = 3;
                } catch (Throwable $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    $errors[] = 'Error creating company/user: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
                    $step = 2;
                }
            } else {
                $_SESSION['wizard_user'] = $user;
                $step = 2;
            }
        }
    }
}

$csrf = wizard_csrf_token();

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TowLens Admin – New Company &amp; User Wizard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>
  /* ===== Custom Scrollbar (Classic) ===== */
  ::-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; }

  /* ===== Classic Commercial Theme ===== */
  :root{
    --bg:#eceff3; --win:#ffffff; --ink:#1f2933; --muted:#5d6b78; --line:#cfd6de;
    --brand:#2f6db2; --brand-dark:#255a95; --ok:#2f7d3d; --warn:#b28a2f; --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); --tab-grad:linear-gradient(#f5f7fa,#e9eef4);
    --btn-grad:linear-gradient(#f8fafc,#e6ecf2); --btn-grad-active:linear-gradient(#e6ecf2,#d9e1e9);
    --chip:#f1f3f6;
  }
  *{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);
    -webkit-user-select:none;
    -ms-user-select:none;
    user-select:none;
  }
  .app{min-height:100%;display:flex;flex-direction:column}

  /* Ribbon */
  .ribbon{
    background:var(--hdr-grad);
    border-bottom:1px solid var(--line);
    box-shadow:var(--shadow);
  }
  .ribbon-inner{
    max-width:1100px;
    margin:0 auto;
    padding:10px 14px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
  }
  .title-wrap{display:flex;align-items:center;gap:10px;}
  .wiz-icon{
    width:30px;height:30px;border-radius:4px;
    background:linear-gradient(#305c9c,#1f3564);
    box-shadow:inset 0 0 0 1px rgba(255,255,255,.4),0 2px 4px rgba(0,0,0,.18);
    position:relative;
  }
  /* 90s-style Wizard: tiny pixel-ish hat + wand */
  .wiz-icon:before{
    content:"";
    position:absolute;
    left:7px;bottom:4px;
    border-left:8px solid transparent;
    border-right:8px solid transparent;
    border-bottom:14px solid #2f6db2;
  }
  .wiz-icon:after{
    content:"✦";
    position:absolute;
    right:5px;top:5px;
    font-size:9px;
    color:#ffe37a;
    text-shadow:0 0 2px #fff;
  }
  .wiz-wand{
    position:absolute;
    width:2px;height:12px;
    background:#f9fafb;
    right:9px;bottom:7px;
    transform:rotate(-25deg);
    box-shadow:0 0 2px rgba(0,0,0,.4);
  }
  h1{
    font-size:16px;
    margin:0;
  }
  .sub{
    font-size:12px;
    color:var(--muted);
  }

  .btn{
    appearance:none;
    border:1px solid #bfc8d2;
    background:var(--btn-grad);
    color:#123;
    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);
    position:relative;
    transition:background .15s ease, transform .05s ease;
    font-size:12px;
  }
  .btn:hover{background:var(--btn-grad-active);}
  .btn:active{transform:translateY(1px);}
  .btn.primary{
    border-color:#2a5f9c;
    color:#fff;
    background:linear-gradient(#3b79c1,#2b67ab);
  }
  .btn.secondary{
    background:var(--btn-grad);
    color:#223;
  }
  .btn.small{padding:4px 8px;font-size:11px;}

  .window{
    max-width:1100px;
    margin:16px auto 24px;
    padding:0 14px;
    width:100%;
  }

  .strip{
    background:#f6f8fb;
    border:1px solid var(--line);
    border-radius:var(--radius);
    padding:8px 10px;
    box-shadow:var(--shadow);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:10px;
  }
  .meta{font-size:12px;color:var(--muted);}
  a.back-link{
    font-size:12px;
    color:#2f6db2;
    text-decoration:none;
  }
  a.back-link:hover{text-decoration:underline;}

  /* Wizard steps */
  .wizard-steps{
    display:flex;
    gap:6px;
    margin:8px 0 10px;
    font-size:11px;
  }
  .wizard-step{
    padding:4px 9px;
    border-radius:999px;
    background:var(--chip);
    border:1px solid var(--line);
    color:var(--muted);
  }
  .wizard-step.active{
    background:#ffffff;
    border-color:#2f6db2;
    color:#1f2933;
    font-weight:700;
  }
  .wizard-step.done{
    background:#e8f8ec;
    border-color:#2f7d3d;
    color:#14532d;
    font-weight:600;
  }

  .card{
    background:#ffffff;
    border-radius:var(--radius);
    border:1px solid var(--line);
    box-shadow:var(--shadow);
    padding:12px 12px 10px;
  }

  .field-row{
    display:flex;
    gap:10px;
    margin-bottom:8px;
    flex-wrap:wrap;
  }
  .field{
    flex:1;
    min-width:220px;
  }
  .field label{
    display:block;
    font-size:10px;
    text-transform:uppercase;
    letter-spacing:.09em;
    color:var(--muted);
    margin-bottom:2px;
  }
  .field input,
  .field select{
    width:100%;
    padding:6px 7px;
    border-radius:3px;
    border:1px solid #cfd6de;
    font-size:12px;
    outline:none;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.9);
    background:#f9fafb;
  }
  .field input:focus,
  .field select:focus{
    border-color:#99b4d6;
    background:#ffffff;
  }
  .help-text{
    font-size:10px;
    color:#9ca3af;
    margin-top:1px;
  }

  .alerts{margin:4px 0 8px;}
  .alert{
    padding:7px 9px;
    border-radius:3px;
    margin-bottom:4px;
    font-size:11px;
  }
  .alert.error{
    background:#fae7e7;
    border:1px solid #e3b1b1;
    color:#7f2020;
  }
  .alert.ok{
    background:#eaf2fd;
    border:1px solid #b9d0f5;
    color:#163a6c;
  }

  .actions{
    margin-top:10px;
    display:flex;
    justify-content:flex-end;
    gap:6px;
  }

  .summary{
    font-size:12px;
    color:var(--ink);
    margin:6px 0 4px;
  }
  .summary span{
    font-size:10px;
    color:var(--muted);
    text-transform:uppercase;
    letter-spacing:.08em;
    display:block;
    margin-bottom:2px;
  }
  </style>
</head>
<body>

<div class="app">

  <!-- Ribbon -->
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title-wrap">
        <div class="wiz-icon">
          <div class="wiz-wand"></div>
        </div>
        <div>
          <h1>New Company &amp; User Wizard</h1>
          <div class="sub">TowLens admin wizard for onboarding fresh clients.</div>
        </div>
      </div>
      <div>
        <button type="button"
                class="btn small"
                data-nav="companies">
          ⬅ Back to Companies      </button>
      </div>
    </div>
  </div>

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

    <!-- Small strip -->
    <div class="strip">
      <div class="meta">
        Use this wizard to:
        <strong>1)</strong> create a company,
        <strong>2)</strong> add its first admin user.
      </div>
      <div class="meta">
        🧙‍♂️ Wizard tip: nothing is saved until you finish step 2.
      </div>
    </div>

    <!-- Steps indicator -->
    <div class="wizard-steps">
      <div class="wizard-step <?php echo ($step === 1 ? 'active' : ($step > 1 ? 'done' : '')); ?>">
        1. Company details
      </div>
      <div class="wizard-step <?php echo ($step === 2 ? 'active' : ($step > 2 ? 'done' : '')); ?>">
        2. First user
      </div>
      <div class="wizard-step <?php echo ($step === 3 ? 'active' : ($step > 3 ? 'done' : '')); ?>">
        3. Complete
      </div>
    </div>

    <!-- Alerts -->
    <div class="alerts">
      <?php foreach ($errors as $e): ?>
        <div class="alert error"><?php echo htmlspecialchars($e, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endforeach; ?>
      <?php foreach ($notices as $n): ?>
        <div class="alert ok"><?php echo htmlspecialchars($n, ENT_QUOTES, 'UTF-8'); ?></div>
      <?php endforeach; ?>
    </div>

    <?php if ($step === 1): ?>
      <!-- STEP 1: COMPANY -->
      <form method="post" class="card">
        <input type="hidden" name="csrf" value="<?php echo esc($csrf); ?>">
        <input type="hidden" name="step" value="1">

        <div class="field-row">
          <div class="field">
            <label>Organisation</label>
            <select name="organisation_id" required>
              <option value="">Select organisation…</option>
              <?php foreach ($orgs as $org): ?>
                <option value="<?php echo (int)$org['id']; ?>"
                  <?php if ((int)$company['organisation_id'] === (int)$org['id']) echo 'selected'; ?>>
                  <?php echo esc($org['name']); ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="help-text">Which parent organisation this company belongs to.</div>
          </div>
          <div class="field">
            <label>Company name</label>
            <input type="text" name="name"
                   value="<?php echo esc($company['name']); ?>" required>
            <div class="help-text">Client display name, e.g. "Mount Pleasant Motoring Services".</div>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <label>Brand name</label>
            <input type="text" name="brand_name"
                   value="<?php echo esc($company['brand_name']); ?>">
            <div class="help-text">Shown in UI/emails (defaults to company name).</div>
          </div>
          <div class="field">
            <label>Brand subtitle</label>
            <input type="text" name="brand_subtitle"
                   value="<?php echo esc($company['brand_subtitle']); ?>">
            <div class="help-text">Optional tagline, e.g. "Vehicle Images".</div>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <label>Brand color (hex)</label>
            <input type="text" name="brand_color" placeholder="#2f6db2"
                   value="<?php echo esc($company['brand_color']); ?>">
            <div class="help-text">Used for theming; leave blank to use default.</div>
          </div>
          <div class="field">
            <label>Logo URL</label>
            <input type="text" name="logo_url"
                   value="<?php echo esc($company['logo_url']); ?>">
            <div class="help-text">Public logo for this client (optional).</div>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <label>Support email</label>
            <input type="email" name="support_email"
                   value="<?php echo esc($company['support_email']); ?>">
            <div class="help-text">For TowLens notifications / contact (optional).</div>
          </div>
          <div class="field">
            <label>Slug</label>
            <input type="text" name="slug"
                   value="<?php echo esc($company['slug']); ?>">
            <div class="help-text">Short ID, auto-uniqued (e.g. "client").</div>
          </div>
        </div>

        <div class="actions">
          <button type="submit" class="btn primary">
            Next &nbsp;▶
          </button>
        </div>
      </form>

    <?php elseif ($step === 2): ?>
      <!-- STEP 2: USER -->
      <form method="post" class="card">
        <input type="hidden" name="csrf" value="<?php echo esc($csrf); ?>">
        <input type="hidden" name="step" value="2">

        <div class="field-row">
          <div class="field">
            <label>Auth provider</label>
            <select name="provider" id="provider-select">
              <option value="entra" <?php if ($user['provider'] === 'entra') echo 'selected'; ?>>Entra (SSO)</option>
              <option value="local" <?php if ($user['provider'] === 'local') echo 'selected'; ?>>Local account</option>
            </select>
            <div class="help-text">Match how this user will sign in.</div>
          </div>
          <div class="field" id="oid-field">
            <label>OID (for Entra)</label>
            <input type="text" name="oid"
                   value="<?php echo esc($user['oid']); ?>">
            <div class="help-text">Required for Entra users; ignored for local.</div>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <label>User email</label>
            <input type="email" name="email" required
                   value="<?php echo esc($user['email']); ?>">
            <div class="help-text">Login ID &amp; notification address.</div>
          </div>
          <div class="field">
            <label>Display name</label>
            <input type="text" name="display_name" required
                   value="<?php echo esc($user['display_name']); ?>">
            <div class="help-text">Shown inside TowLens.</div>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <label>Role</label>
            <select name="role">
              <option value="admin" <?php if ($user['role']==='admin') echo 'selected'; ?>>Admin</option>
              <option value="org_admin" <?php if ($user['role']==='org_admin') echo 'selected'; ?>>Org Admin</option>
              <option value="company_admin" <?php if ($user['role']==='company_admin') echo 'selected'; ?>>Company Admin</option>
              <option value="staff" <?php if ($user['role']==='staff') echo 'selected'; ?>>Staff</option>
            </select>
            <div class="help-text">First user is usually Admin or Company Admin.</div>
          </div>
          <div class="field" style="display:flex;align-items:flex-end">
            <label>&nbsp;</label>
            <label style="font-size:11px;color:var(--ink);display:flex;align-items:center;gap:5px;">
              <input type="checkbox" name="is_active" value="1"
                <?php if (!isset($user['is_active']) || $user['is_active']) echo 'checked'; ?>>
              Active account
            </label>
          </div>
        </div>

        <div class="field-row" id="password-row">
          <div class="field">
            <label>Initial password (local only)</label>
            <input type="password" name="password" autocomplete="new-password">
            <div class="help-text">Required if provider is "Local".</div>
          </div>
        </div>

        <div class="actions">
          <button type="button" class="btn secondary" onclick="history.back();">
            ◀ Back
          </button>
          <button type="submit" class="btn primary">
            Finish – Create company &amp; user
          </button>
        </div>
      </form>

      <script>
      (function(){
        function toggleProviderFields(){
          var provider = document.getElementById('provider-select').value;
          var oidField = document.getElementById('oid-field');
          var pwRow    = document.getElementById('password-row');

          if (provider === 'entra') {
            oidField.style.opacity = '1';
            oidField.style.pointerEvents = 'auto';
            pwRow.style.display = 'none';
          } else {
            oidField.style.opacity = '.4';
            oidField.style.pointerEvents = 'none';
            pwRow.style.display = 'flex';
          }
        }
        document.getElementById('provider-select').addEventListener('change', toggleProviderFields);
        toggleProviderFields();
      })();
      </script>

    <?php else: ?>
      <!-- STEP 3: DONE -->
      <div class="card">
        <div class="summary">
          <span>Wizard complete</span>
          Your new TowLens client has been created with its first user.
        </div>
        <div class="actions" style="justify-content:flex-start;margin-top:10px;">
          <a class="btn primary" href="<?php echo esc($base); ?>/admin/company_user_wizard.php">
            + Add another company
          </a>
          <a class="btn secondary" href="<?php echo esc($base); ?>/admin/companies.php">
            &larr; Back to Companies
          </a>
        </div>
      </div>
    <?php endif; ?>

  </div>
</div>

<script>
  // Disable right-click and image drag
  window.addEventListener('contextmenu', e => e.preventDefault(), {passive:false});
  document.addEventListener('dragstart', e => {
    if (e.target && e.target.tagName === 'IMG') e.preventDefault();
  });

  // Data-nav buttons: navigate without showing URL on hover
  document.addEventListener('click', function (e) {
    const btn = e.target.closest('[data-nav]');
    if (!btn) return;
    const target = btn.getAttribute('data-nav');
    if (!target) return;
    e.preventDefault();
    window.location.href = target;
  }, { passive: false });
</script>

<script>
  // Match classic behaviour: disable right-click & text selection (already CSS for select)
  window.addEventListener('contextmenu', function(e){ e.preventDefault(); }, {passive:false});
  document.addEventListener('dragstart', function(e){
    if (e.target && e.target.tagName === 'IMG') e.preventDefault();
  });
</script>

</body>
</html>