<?php
// /admin/users.php
session_start();

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

/**
 * Render a themed error page that matches the Classic Commercial UI
 */
function themed_error(int $statusCode, string $heading, string $message, array $config): void {
  http_response_code($statusCode);
  $base = rtrim($config['base_url'] ?? '', '/');
  ?>
  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Admin Settings — Error</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      /* ===== Custom Scrollbar (matches Classic Commercial Theme) ===== */
      ::-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:#2f7d3d; --danger:#b22f2f; --warn:#b28a2f;
        --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);
        --badge:#eef3f8;
      }
      *{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 */
      .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{display:flex; align-items:center; gap:10px}
      .mark{width:26px; height:26px; border-radius:4px; background:#2f6db2; box-shadow:inset 0 0 0 1px rgba(255,255,255,.5)}
      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)}
      .btn:hover{background:var(--btn-grad-active)}
      .btn.primary{border-color:#2a5f9c; color:#fff; background:linear-gradient(#3b79c1,#2b67ab)}
      .btn.small{padding:4px 8px; font-size:12px}

      /* Container + tabs */
      .container{max-width:1100px; margin:16px auto 24px; padding:0 14px; width:100%}
      .tabs{display:flex; flex-wrap:wrap; gap:8px; margin-bottom:12px}
      .tab{display:inline-block; padding:8px 12px; background:linear-gradient(#f5f7fa,#e9eef4); border:1px solid var(--line); border-radius:4px; cursor:pointer}
      .tab.active{background:#fff; font-weight:700}

      /* Panels + alerts */
      .panel{background:#fff; border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); padding:12px; margin:12px 0}
      .alert{padding:10px; border-radius:4px; margin:10px 0}
      .ok{background:#eaf4ea; border:1px solid #bcd8bc; color:#1e4b1e}
      .err{background:#fae7e7; border:1px solid #e3b1b1; color:#7f2020}

      /* Disable selection & iOS long-press */
      html, body, .app, * { -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; -webkit-touch-callout:none; }
    </style>
  </head>
  <body>
    <div class="app">
      <div class="ribbon">
        <div class="ribbon-inner">
          <div class="title">
            <div class="mark" aria-hidden="true"></div>
            <div>
              <h1>Admin Settings — Error</h1>
              <div class="sub">Something went wrong</div>
            </div>
          </div>
          <div class="actions" style="display:flex; gap:8px">
            <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/settings.php">SSO</button>
            <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/index.php">Dashboard</button>
            <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/companies.php">Companies</button>
            <button type="button" class="btn primary" data-nav="<?= esc($base) ?>/admin/logout.php">Logout</button>
          </div>
        </div>
      </div>

      <div class="container">
        <nav class="tabs">
          <button type="button" class="tab" data-nav="<?= esc($base) ?>/admin/settings.php">SSO</button>
          <button type="button" class="tab active" data-nav="<?= esc($base) ?>/admin/users.php">Users</button>
        </nav>

        <div class="alert err"><strong><?= esc($heading) ?> (<?= (int)$statusCode ?>):</strong> <?= esc($message) ?></div>

        <section class="panel">
          <div style="display:flex; gap:8px; flex-wrap:wrap">
            <button type="button" class="btn" onclick="history.back()">Go back</button>
            <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/index.php">Go to Dashboard</button>
          </div>
        </section>
      </div>
    </div>

    <script>
      // JS nav (no URL preview on hover)
      document.addEventListener('click', (e) => {
        const nav = e.target.closest('[data-nav]');
        if (nav) { window.location.assign(nav.getAttribute('data-nav')); }
      });
      // Block right-click
      window.addEventListener('contextmenu', e => e.preventDefault(), { capture: true });
    </script>
  </body>
  </html>
  <?php
  exit;
}

require_admin_auth($config); // signed-in
if (($_SESSION['user']['role'] ?? '') !== 'admin') {
  themed_error(403, 'Access denied', 'Admins only.', $config);
}

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

function csrf_token(): string {
  if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
  return $_SESSION['csrf'];
}
function csrf_ok(): bool {
  return !empty($_POST['csrf']) && hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf']);
}

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

// Ensure users table exists
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  provider ENUM('local','entra') NOT NULL DEFAULT 'local',
  oid VARCHAR(64) DEFAULT NULL,
  email VARCHAR(190) NOT NULL,
  display_name VARCHAR(190) DEFAULT NULL,
  role ENUM('admin','staff') NOT NULL DEFAULT 'staff',
  is_active TINYINT(1) NOT NULL DEFAULT 1,
  last_login_at DATETIME DEFAULT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_entra_oid (provider, oid),
  UNIQUE KEY uq_email_provider (provider, email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Handle actions (Add / Delete only; editing via popup)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!csrf_ok()) {
    $errors[] = 'Invalid CSRF token. Please reload and try again.';
  } else {
    $section = $_POST['section'] ?? '';

    if ($section === 'user_add') {
      $provider = ($_POST['provider'] ?? 'entra') === 'local' ? 'local' : 'entra';
      $email = strtolower(trim($_POST['email'] ?? ''));
      $name  = trim($_POST['display_name'] ?? '');
      $role  = ($_POST['role'] ?? 'staff') === 'admin' ? 'admin' : 'staff';
      $oid   = trim($_POST['oid'] ?? '');

      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
      } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE provider=? AND (email=? OR (oid IS NOT NULL AND oid=?)) LIMIT 1");
        $stmt->execute([$provider, $email, $oid ?: '']);
        if ($stmt->fetchColumn()) {
          $errors[] = 'User already exists for this provider.';
        } else {
          $ins = $pdo->prepare("INSERT INTO users (provider, oid, email, display_name, role, is_active, last_login_at)
                                VALUES (?,?,?,?,?,1,NULL)");
          $ins->execute([$provider, ($oid ?: null), $email, ($name ?: null), $role]);
          $notices[] = 'User added.';
        }
      }
    }

    if ($section === 'user_delete') {
      $uid = (int)($_POST['id'] ?? 0);
      if ($uid <= 0) {
        $errors[] = 'Invalid user id.';
      } elseif ($uid === (int)($_SESSION['user']['id'] ?? -1)) {
        $errors[] = 'You cannot delete your own account.';
      } else {
        $del = $pdo->prepare("DELETE FROM users WHERE id=?");
        $del->execute([$uid]);
        $notices[] = 'User deleted.';
      }
    }
  }
}

// Load users
$users = $pdo->query("SELECT id, provider, oid, email, display_name, role, is_active, last_login_at, created_at
                      FROM users ORDER BY role DESC, is_active DESC, id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Admin Settings — Users</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
  /* ===== Custom Scrollbar (matches Classic Commercial Theme) ===== */
  ::-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:#2f7d3d; --danger:#b22f2f; --warn:#b28a2f;
    --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);
    --badge:#eef3f8;
  }
  *{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 */
  .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{display:flex; align-items:center; gap:10px}
  .mark{width:26px; height:26px; border-radius:4px; background:#2f6db2; box-shadow:inset 0 0 0 1px rgba(255,255,255,.5)}
  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)}
  .btn:hover{background:var(--btn-grad-active)}
  .btn.primary{border-color:#2a5f9c; color:#fff; background:linear-gradient(#3b79c1,#2b67ab)}
  .btn.danger{border-color:#9c2a2a; color:#fff; background:linear-gradient(#c93b3b,#ab2b2b)}
  .btn.small{padding:4px 8px; font-size:12px}

  /* Container + tabs */
  .container{max-width:1100px; margin:16px auto 24px; padding:0 14px; width:100%}
  .tabs{display:flex; flex-wrap:wrap; gap:8px; margin-bottom:12px}
  .tab{display:inline-block; padding:8px 12px; background:linear-gradient(#f5f7fa,#e9eef4); border:1px solid var(--line); border-radius:4px; cursor:pointer}
  .tab.active{background:#fff; font-weight:700}

  /* Panels + alerts */
  .panel{background:#fff; border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); padding:12px; margin:12px 0}
  .alert{padding:10px; border-radius:4px; margin:10px 0}
  .ok{background:#eaf4ea; border:1px solid #bcd8bc; color:#1e4b1e}
  .err{background:#fae7e7; border:1px solid #e3b1b1; color:#7f2020}

  /* Forms */
  label{display:block; font-weight:600; margin:0 0 6px}
  input, select{padding:8px; border:1px solid #cfd6de; border-radius:4px; min-height:34px}
  input:focus, select:focus{border-color:#99b4d6; outline:none}
  .row{display:flex; gap:12px; flex-wrap:wrap}
  .hint{color:var(--muted); font-size:12px}

  /* Table */
  .table-wrap{overflow:auto; border:1px solid var(--line); border-radius:4px}
  table{border-collapse:separate; border-spacing:0; width:100%; background:#fff}
  thead th{background:linear-gradient(#eef3f8,#e2e9f1); border-bottom:1px solid var(--line); color:#2a3b4b; font-size:12px; text-align:left; padding:8px 10px; position:sticky; top:0; z-index:1}
  tbody td{padding:8px 10px; border-bottom:1px solid #e7ecf1; vertical-align:middle}
  tbody tr:nth-child(even){background:#fafbfd}
  tbody tr:hover{background:#fffde7}
  .badge{display:inline-block; padding:3px 8px; border:1px solid var(--line); background:var(--badge); border-radius:999px; font-size:12px; font-weight:700}
  .badge.role-admin{background:#ffe8d6}
  .badge.provider-local{background:#e6f0ff}
  .badge.provider-entra{background:#eaf7ed}
  .badge.active-yes{background:#dcfce7; border-color:#bbf7d0; color:#166534}
  .badge.active-no{background:#fee2e2; border-color:#fecaca; color:#991b1b}
  .actions{display:flex; gap:6px; flex-wrap:wrap}

  /* Disable selection & iOS long-press */
  html, body, .app, * { -webkit-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; -webkit-touch-callout:none; }
  </style>
</head>
<body>
<div class="app">
  <!-- Ribbon -->
  <div class="ribbon">
    <div class="ribbon-inner">
      <div class="title">
        <div class="mark" aria-hidden="true"></div>
        <div>
          <h1>Admin Settings — Users</h1>
          <div class="sub">Manage access, roles, and status</div>
        </div>
      </div>
      <div class="actions" style="display:flex; gap:8px">
        <!-- JS nav buttons (no URL preview) -->
        <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/settings.php">SSO</button>
        <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/index.php">Dashboard</button>
        <button type="button" class="btn" data-nav="<?= esc($base) ?>/admin/companies.php">Companies</button>
        <button type="button" class="btn primary" data-nav="<?= esc($base) ?>/admin/logout.php">Logout</button>
      </div>
    </div>
  </div>

  <div class="container">
    <!-- Tabs -->
    <nav class="tabs">
      <button type="button" class="tab" data-nav="<?= esc($base) ?>/admin/settings.php">SSO</button>
      <button type="button" class="tab active" data-nav="<?= esc($base) ?>/admin/users.php">Users</button>
    </nav>

    <?php foreach ($notices as $n): ?><div class="alert ok"><?= esc($n) ?></div><?php endforeach; ?>
    <?php foreach ($errors as $e): ?><div class="alert err"><?= esc($e) ?></div><?php endforeach; ?>

    <!-- Add user -->
    <section class="panel">
      <h2 style="margin:0 0 8px">Add user</h2>
      <form method="post">
        <input type="hidden" name="csrf" value="<?= esc(csrf_token()) ?>">
        <input type="hidden" name="section" value="user_add">
        <div class="row">
          <div style="min-width:260px; flex:1">
            <label>Email</label>
            <input name="email" type="email" required placeholder="user@company.com" style="width:100%">
          </div>
          <div style="min-width:220px; flex:1">
            <label>Display name (optional)</label>
            <input name="display_name" placeholder="Jane Doe" style="width:100%">
          </div>
        </div>
        <div class="row" style="margin-top:8px">
          <div>
            <label>Provider</label>
            <select name="provider">
              <option value="entra">Microsoft Entra (SSO)</option>
              <option value="local">Local</option>
            </select>
          </div>
          <div>
            <label>Role</label>
            <select name="role">
              <option value="staff">Staff</option>
              <option value="admin">Admin</option>
            </select>
          </div>
          <div style="min-width:280px">
            <label>OID (optional)</label>
            <input name="oid" placeholder="Azure Object ID">
            <div class="hint">If blank, first SSO match happens by email.</div>
          </div>
        </div>
        <div style="margin-top:10px">
          <button class="btn primary" type="submit">Add user</button>
        </div>
      </form>
    </section>

    <!-- Users table -->
    <section class="panel">
      <h2 style="margin:0 0 8px">Users</h2>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th style="width:70px">ID</th>
              <th style="width:110px">Provider</th>
              <th>Email</th>
              <th style="width:220px">Name</th>
              <th style="width:140px">Role</th>
              <th style="width:120px">Active</th>
              <th style="width:180px">Last login</th>
              <th style="width:210px">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$users): ?>
            <tr><td colspan="8" style="text-align:center; color:var(--muted); padding:18px">No users found.</td></tr>
          <?php else: foreach ($users as $u): ?>
            <tr>
              <td><strong>#<?= (int)$u['id'] ?></strong></td>
              <td>
                <span class="badge provider-<?= esc($u['provider']) ?>"><?= esc(strtoupper($u['provider'])) ?></span>
              </td>
              <td>
                <?= esc($u['email']) ?>
                <div class="hint"><?= esc($u['oid'] ?: '') ?></div>
              </td>
              <td><?= esc($u['display_name'] ?: '—') ?></td>
              <td>
                <?php if ($u['role'] === 'admin'): ?>
                  <span class="badge role-admin">Admin</span>
                <?php else: ?>
                  <span class="badge">Staff</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if ((int)$u['is_active'] === 1): ?>
                  <span class="badge active-yes">Active</span>
                <?php else: ?>
                  <span class="badge active-no">Disabled</span>
                <?php endif; ?>
              </td>
              <td class="hint"><?= esc($u['last_login_at'] ?: '—') ?></td>
              <td class="actions">
                <button type="button"
                        class="btn small"
                        data-user-popup="<?= esc($base) ?>/admin/user_edit.php?id=<?= (int)$u['id'] ?>">
                  Edit
                </button>

                <form method="post" onsubmit="return confirm('Delete this user?');" style="display:inline">
                  <input type="hidden" name="csrf" value="<?= esc(csrf_token()) ?>">
                  <input type="hidden" name="section" value="user_delete">
                  <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                  <button class="btn danger small" type="submit">Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </section>
  </div>
</div>

<script>
  // JS navigation via data-nav (prevents URL preview on hover)
  document.addEventListener('click', (e) => {
    const nav = e.target.closest('[data-nav]');
    if (nav) {
      e.preventDefault();
      window.location.assign(nav.getAttribute('data-nav'));
      return;
    }

    const popupBtn = e.target.closest('[data-user-popup]');
    if (popupBtn) {
      e.preventDefault();
      const url = popupBtn.getAttribute('data-user-popup');
      if (!url) return;
      const w = 720, h = 540;
      const left = window.screenX + Math.max(0, (window.outerWidth - w) / 2);
      const top  = window.screenY + Math.max(0, (window.outerHeight - h) / 2);
      window.open(
        url,
        'TowLensUserEdit',
        'width=' + w + ',height=' + h +
        ',left=' + left + ',top=' + top +
        ',resizable=yes,scrollbars=yes'
      );
    }
  });

  // Block right-click/context menu
  window.addEventListener('contextmenu', e => e.preventDefault(), { capture: true });
</script>
</body>
</html>