<?php
// admin/create_admin.php
// Only superadmin can create / manage admin users
if (session_status() === PHP_SESSION_NONE) session_start();

include __DIR__ . '/config/journal_config.php';
include __DIR__ . '/config/auth.php';

require_role('superadmin');   // 🔒 superadmin only

$success = $error = '';

// ── Fetch journals for dropdown ────────────────────────────────
$journals = $pdo->query("SELECT id, name FROM journals ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// ── Fetch all admin users ──────────────────────────────────────
function fetchUsers($pdo): array {
    return $pdo->query("
        SELECT au.id, au.email, au.first_name, au.last_name,
               au.role, au.is_active, au.last_login_at,
               j.name AS journal_name
        FROM   admin_users au
        LEFT   JOIN journals j ON j.id = au.journal_id
        ORDER  BY au.id DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
}

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

    /* ---- Create ---- */
    if ($action === 'create') {
        $first      = trim($_POST['first_name']  ?? '');
        $last       = trim($_POST['last_name']   ?? '');
        $email      = trim($_POST['email']       ?? '');
        $role       = $_POST['role']             ?? 'author';
        $journal_id = ($_POST['journal_id'] !== '') ? (int)$_POST['journal_id'] : null;
        $password   = $_POST['password']         ?? '';
        $confirm    = $_POST['confirm_password'] ?? '';
        $is_active  = isset($_POST['is_active']) ? 1 : 0;

        // Validate
        if (empty($first) || empty($last) || empty($email) || empty($password)) {
            $error = 'All required fields must be filled.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email address.';
        } elseif (strlen($password) < 8 || !preg_match('/[A-Z]/', $password) || !preg_match('/[0-9]/', $password)) {
            $error = 'Password must be 8+ chars with one uppercase and one number.';
        } elseif ($password !== $confirm) {
            $error = 'Passwords do not match.';
        } elseif (!array_key_exists($role, ROLE_HIERARCHY)) {
            $error = 'Invalid role selected.';
        } else {
            // Check duplicate email
            $chk = $pdo->prepare("SELECT id FROM admin_users WHERE email = ? LIMIT 1");
            $chk->execute([$email]);
            if ($chk->fetch()) {
                $error = "An account with email <strong>$email</strong> already exists.";
            } else {
                $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
                $pdo->prepare("
                    INSERT INTO admin_users
                      (email, password_hash, first_name, last_name, role, journal_id, is_active)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ")->execute([$email, $hash, $first, $last, $role, $journal_id, $is_active]);
                $success = "User <strong>{$first} {$last}</strong> created successfully.";
            }
        }
    }

    /* ---- Toggle active ---- */
    elseif ($action === 'toggle_active') {
        $uid = (int)($_POST['user_id'] ?? 0);
        if ($uid && $uid !== (int)$_SESSION['admin_user_id']) {
            $pdo->prepare("UPDATE admin_users SET is_active = NOT is_active WHERE id = ?")
                ->execute([$uid]);
            $success = 'User status updated.';
        }
    }

    /* ---- Delete ---- */
    elseif ($action === 'delete') {
        $uid = (int)($_POST['user_id'] ?? 0);
        if ($uid && $uid !== (int)$_SESSION['admin_user_id']) {
            $pdo->prepare("DELETE FROM admin_users WHERE id = ?")->execute([$uid]);
            $success = 'User deleted.';
        } else {
            $error = 'You cannot delete your own account.';
        }
    }
}

$users = fetchUsers($pdo);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Manage Admin Users — RSIS</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root { --brand: #1a3c5e; --brand-dark: #122d47; }
    body  { font-family: 'Inter', sans-serif; background: #f0f2f5; }
    .page-header {
      background: var(--brand); color: #fff;
      padding: 18px 28px; border-radius: 12px;
      margin-bottom: 24px;
    }
    .page-header h5 { margin: 0; font-weight: 700; }
    .page-header p  { margin: 4px 0 0; font-size: .83rem; opacity: .75; }
    .card { border: none; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,.07); }
    .card-header {
      background: #fff; border-bottom: 1px solid #e5e7eb;
      border-radius: 12px 12px 0 0 !important;
      padding: 16px 20px; font-weight: 600; font-size: .95rem;
    }
    .form-label  { font-size: .875rem; font-weight: 500; color: #374151; }
    .form-control, .form-select {
      font-size: .88rem; border-radius: 8px; border-color: #d1d5db;
    }
    .form-control:focus, .form-select:focus {
      border-color: var(--brand);
      box-shadow: 0 0 0 3px rgba(26,60,94,.12);
    }
    .btn-brand {
      background: var(--brand); border: none;
      border-radius: 8px; font-weight: 600; font-size: .88rem;
    }
    .btn-brand:hover { background: var(--brand-dark); }
    .badge-role {
      font-size: .72rem; font-weight: 600;
      padding: 4px 10px; border-radius: 20px;
    }
    .table th { font-size: .78rem; text-transform: uppercase;
                letter-spacing: .5px; color: #6b7280; border-top: none; }
    .table td { font-size: .875rem; vertical-align: middle; }
    .pw-wrap { position: relative; }
    .pw-toggle {
      position: absolute; right: 10px; top: 50%;
      transform: translateY(-50%);
      background: none; border: none; color: #9ca3af;
      cursor: pointer; padding: 0;
    }
    .strength-bar { height: 4px; border-radius: 4px; transition: all .3s; }
  </style>
</head>
<body>
<div class="container-xl py-4">

  <!-- Header -->
  <div class="page-header d-flex justify-content-between align-items-center">
    <div>
      <h5>👤 Manage Admin Users</h5>
      <p>Create and manage staff, editors, and reviewers</p>
    </div>
    <a href="admin.php?section=submissions" class="btn btn-outline-light btn-sm">← Dashboard</a>
  </div>

  <!-- Alerts -->
  <?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show py-2 px-3 mb-3">
      <?= $success ?> <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>
  <?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show py-2 px-3 mb-3">
      <?= $error ?> <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <div class="row g-4">

    <!-- ── Create form ── -->
    <div class="col-lg-4">
      <div class="card">
        <div class="card-header">➕ Create New User</div>
        <div class="card-body p-4">
          <form method="POST" novalidate id="createForm">
            <input type="hidden" name="action" value="create">

            <div class="row g-2 mb-3">
              <div class="col">
                <label class="form-label">First name *</label>
                <input type="text" name="first_name" class="form-control"
                       value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>" required>
              </div>
              <div class="col">
                <label class="form-label">Last name *</label>
                <input type="text" name="last_name" class="form-control"
                       value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>" required>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Email *</label>
              <input type="email" name="email" class="form-control"
                     value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
            </div>

            <div class="mb-3">
              <label class="form-label">Role *</label>
              <select name="role" class="form-select" id="roleSelect" onchange="toggleJournal(this.value)">
                <?php foreach (ROLE_HIERARCHY as $r => $_): ?>
                  <option value="<?= $r ?>" <?= (($_POST['role'] ?? 'author') === $r) ? 'selected' : '' ?>>
                    <?= ucfirst($r) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="mb-3" id="journalWrap">
              <label class="form-label">Journal</label>
              <select name="journal_id" class="form-select">
                <option value="">— All journals (superadmin) —</option>
                <?php foreach ($journals as $j): ?>
                  <option value="<?= $j['id'] ?>"
                    <?= (isset($_POST['journal_id']) && (int)$_POST['journal_id'] === (int)$j['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($j['name']) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="mb-3">
              <label class="form-label">Password *</label>
              <div class="pw-wrap">
                <input type="password" name="password" id="newPw" class="form-control pe-5"
                       placeholder="Min 8 chars" required oninput="checkStr(this.value)">
                <button type="button" class="pw-toggle" onclick="togglePw('newPw')">
                  <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM8 11a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/></svg>
                </button>
              </div>
              <div class="mt-1">
                <div class="strength-bar bg-light"><div id="strBar" class="strength-bar" style="width:0%;background:#ef4444"></div></div>
                <small id="strText" style="font-size:.73rem"></small>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Confirm password *</label>
              <div class="pw-wrap">
                <input type="password" name="confirm_password" id="confPw" class="form-control pe-5" required>
                <button type="button" class="pw-toggle" onclick="togglePw('confPw')">
                  <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM8 11a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/></svg>
                </button>
              </div>
            </div>

            <div class="mb-4">
              <div class="form-check">
                <input type="checkbox" name="is_active" id="isActive" class="form-check-input"
                       value="1" checked>
                <label for="isActive" class="form-check-label form-label mb-0">Active immediately</label>
              </div>
            </div>

            <button type="submit" class="btn btn-brand btn-primary w-100">Create User</button>
          </form>
        </div>
      </div>
    </div>

    <!-- ── Users table ── -->
    <div class="col-lg-8">
      <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span>📋 All Admin Users (<?= count($users) ?>)</span>
          <input type="search" id="tableSearch" class="form-control form-control-sm w-auto"
                 placeholder="Search…" style="max-width:180px" oninput="filterTable(this.value)">
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover mb-0" id="usersTable">
              <thead class="table-light">
                <tr>
                  <th class="ps-3">Name / Email</th>
                  <th>Role</th>
                  <th>Journal</th>
                  <th>Status</th>
                  <th>Last login</th>
                  <th class="pe-3">Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($users)): ?>
                  <tr><td colspan="6" class="text-center text-muted py-4">No users found.</td></tr>
                <?php endif; ?>
                <?php foreach ($users as $u):
                  $isSelf = (int)$u['id'] === (int)$_SESSION['admin_user_id'];
                  $roleColors = [
                    'superadmin' => 'bg-dark text-white',
                    'admin'      => 'bg-primary text-white',
                    'editor'     => 'bg-info text-dark',
                    'reviewer'   => 'bg-warning text-dark',
                    'author'     => 'bg-secondary text-white',
                  ];
                  $roleClass = $roleColors[$u['role']] ?? 'bg-secondary text-white';
                ?>
                <tr>
                  <td class="ps-3">
                    <div class="fw-500"><?= htmlspecialchars($u['first_name'] . ' ' . $u['last_name']) ?>
                      <?php if ($isSelf): ?><small class="text-muted">(you)</small><?php endif; ?>
                    </div>
                    <small class="text-muted"><?= htmlspecialchars($u['email']) ?></small>
                  </td>
                  <td><span class="badge badge-role <?= $roleClass ?>"><?= ucfirst($u['role']) ?></span></td>
                  <td><small><?= $u['journal_name'] ? htmlspecialchars($u['journal_name']) : '<em class="text-muted">All</em>' ?></small></td>
                  <td>
                    <?php if ($u['is_active']): ?>
                      <span class="badge bg-success-subtle text-success">Active</span>
                    <?php else: ?>
                      <span class="badge bg-danger-subtle text-danger">Inactive</span>
                    <?php endif; ?>
                  </td>
                  <td><small class="text-muted"><?= $u['last_login_at'] ? date('d M y, H:i', strtotime($u['last_login_at'])) : 'Never' ?></small></td>
                  <td class="pe-3">
                    <?php if (!$isSelf): ?>
                      <!-- Toggle active -->
                      <form method="POST" class="d-inline">
                        <input type="hidden" name="action" value="toggle_active">
                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                        <button class="btn btn-sm <?= $u['is_active'] ? 'btn-outline-warning' : 'btn-outline-success' ?> py-0 px-2"
                                title="<?= $u['is_active'] ? 'Deactivate' : 'Activate' ?>">
                          <?= $u['is_active'] ? '⏸' : '▶' ?>
                        </button>
                      </form>
                      <!-- Delete -->
                      <form method="POST" class="d-inline"
                            onsubmit="return confirm('Delete <?= htmlspecialchars($u['first_name']) ?>? This cannot be undone.')">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger py-0 px-2" title="Delete">🗑</button>
                      </form>
                    <?php else: ?>
                      <small class="text-muted">—</small>
                    <?php endif; ?>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function togglePw(id) {
  const el = document.getElementById(id);
  el.type = el.type === 'password' ? 'text' : 'password';
}

function checkStr(pw) {
  let s = 0;
  if (pw.length >= 8)            s++;
  if (/[A-Z]/.test(pw))         s++;
  if (/[0-9]/.test(pw))         s++;
  if (/[^A-Za-z0-9]/.test(pw)) s++;
  const lvl = [
    {w:'0%',c:'#ef4444',t:''},
    {w:'25%',c:'#ef4444',t:'Weak'},
    {w:'50%',c:'#f97316',t:'Fair'},
    {w:'75%',c:'#eab308',t:'Good'},
    {w:'100%',c:'#22c55e',t:'Strong'},
  ];
  document.getElementById('strBar').style.cssText = `width:${lvl[s].w};background:${lvl[s].c}`;
  const t = document.getElementById('strText');
  t.textContent = lvl[s].t;
  t.style.color = lvl[s].c;
}

function toggleJournal(role) {
  document.getElementById('journalWrap').style.display =
    role === 'superadmin' ? 'none' : '';
}
toggleJournal(document.getElementById('roleSelect').value);

function filterTable(q) {
  q = q.toLowerCase();
  document.querySelectorAll('#usersTable tbody tr').forEach(row => {
    row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
}
</script>
</body>
</html>