<?php
if (session_status() === PHP_SESSION_NONE) session_start();
include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

// ── Role update POST ──────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_role'])) {
    $uid     = (int)$_POST['user_id'];
    $newRole = $_POST['new_role'] ?? '';
    $valid   = ['author','reviewer','editor','both','other'];
    if ($uid && in_array($newRole, $valid)) {
        $pdo->prepare("UPDATE users SET role=?, updated_at=NOW() WHERE user_id=?")
            ->execute([$newRole, $uid]);
    }
    header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query(array_diff_key($_GET, ['msg'=>''])) . "&msg=updated");
    exit;
}

// ── Toggle active status ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_active'])) {
    $uid = (int)$_POST['user_id'];
    if ($uid) {
        $pdo->prepare("UPDATE users SET is_active = 1 - is_active, updated_at=NOW() WHERE user_id=?")
            ->execute([$uid]);
    }
    header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query(array_diff_key($_GET, ['msg'=>''])) . "&msg=toggled");
    exit;
}

// ── Filters ───────────────────────────────────────────────────
$role    = $_GET['role']   ?? '';
$status  = $_GET['status'] ?? '';
$search  = trim($_GET['q'] ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$per     = 20;
$offset  = ($page - 1) * $per;

$where = ['1=1']; $params = [];

if ($role && in_array($role, ['author','reviewer','editor','both','other'])) {
    $where[] = 'u.role = ?'; $params[] = $role;
}
if ($status === 'active')   { $where[] = 'u.is_active = 1'; }
if ($status === 'inactive') { $where[] = 'u.is_active = 0'; }
if ($status === 'unverified'){ $where[] = 'u.is_email_verified = 0'; }

if ($search) {
    $where[] = "(u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.researcher_id LIKE ?)";
    for($i=0;$i<4;$i++) $params[] = "%$search%";
}

$w = implode(' AND ', $where);

// Count
$cnt = $pdo->prepare("SELECT COUNT(*) FROM users u WHERE $w");
$cnt->execute($params);
$total = (int)$cnt->fetchColumn();
$pages = max(1, (int)ceil($total / $per));

// Fetch
$stmt = $pdo->prepare("
    SELECT u.user_id, u.email, u.first_name, u.middle_name, u.last_name,
           u.title, u.phone_number, u.institutional_email,
           u.profile_photo_url, u.is_active, u.role, u.researcher_id,
           u.is_email_verified, u.created_at, u.updated_at,
           a.name AS affil_name
    FROM users u
    LEFT JOIN affiliations a ON a.affiliation_id = u.affiliation_id
    WHERE $w
    ORDER BY u.created_at DESC
    LIMIT $per OFFSET $offset
");
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Stats
$stats = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(role='author')   AS authors,
        SUM(role='reviewer') AS reviewers,
        SUM(role='editor')   AS editors,
        SUM(role='both')     AS both_roles,
        SUM(is_active=0)     AS inactive,
        SUM(is_email_verified=0) AS unverified
    FROM users
")->fetch(PDO::FETCH_ASSOC);

function buildQ(array $ov=[]): string {
    $q = array_merge($_GET, $ov); unset($q['msg']);
    return http_build_query(array_filter($q, fn($v)=>$v!==''));
}
function p($v){ return htmlspecialchars($v??''); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Users — Admin</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=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
:root{--brand:#1d4ed8;--page-bg:#f4f7fc;--card-bg:#fff;--border:#e2e8f0;--text:#1e293b;--muted:#64748b;--radius:10px;}
body{font-family:'Plus Jakarta Sans',sans-serif;background:var(--page-bg);color:var(--text);}
.stat-card{background:var(--card-bg);border-radius:var(--radius);padding:18px 22px;border:1.5px solid var(--border);display:flex;align-items:center;gap:14px;transition:box-shadow .2s;cursor:pointer;}
.stat-card:hover{box-shadow:0 4px 18px rgba(0,0,0,.07);border-color:#93c5fd;}
.stat-card.active-filter{border-color:#1d4ed8;background:#eff6ff;}
.stat-icon{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:1.1rem;flex-shrink:0;}
.stat-val{font-size:1.5rem;font-weight:800;line-height:1;}
.stat-lbl{font-size:.75rem;color:var(--muted);font-weight:500;margin-top:2px;}
.table-card{background:var(--card-bg);border-radius:var(--radius);border:1.5px solid var(--border);overflow:hidden;}
.th{font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);background:#f8fafc;border-bottom:1.5px solid var(--border);padding:10px 12px;white-space:nowrap;}
.td{font-size:.82rem;padding:11px 12px;vertical-align:middle;border-bottom:1px solid #f1f5f9;}
tbody tr:hover{background:#f8fbff;}
tbody tr:last-child td{border-bottom:none;}
.av{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,#1d4ed8,#60a5fa);display:inline-flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:700;color:#fff;flex-shrink:0;}
.av-img{width:34px;height:34px;border-radius:10px;object-fit:cover;flex-shrink:0;}
/* Role badges */
.rb{display:inline-flex;align-items:center;gap:4px;font-size:.67rem;font-weight:700;padding:3px 8px;border-radius:20px;}
.rb-author{background:#f1f5f9;color:#475569;}
.rb-reviewer{background:#eff6ff;color:#1d4ed8;}
.rb-editor{background:#fef3c7;color:#d97706;}
.rb-both{background:#f0fdf4;color:#15803d;}
.rb-other{background:#f5f3ff;color:#6d28d9;}
/* Status */
.sb-active{background:#dcfce7;color:#15803d;font-size:.67rem;font-weight:700;padding:2px 8px;border-radius:20px;}
.sb-inactive{background:#fee2e2;color:#dc2626;font-size:.67rem;font-weight:700;padding:2px 8px;border-radius:20px;}
.sb-unverified{background:#fef3c7;color:#d97706;font-size:.67rem;font-weight:700;padding:2px 8px;border-radius:20px;}
/* Researcher ID */
.rid{font-family:monospace;font-size:.72rem;font-weight:800;color:#1e40af;background:#eff6ff;border:1px solid #bfdbfe;border-radius:4px;padding:2px 6px;}
/* Filter tabs */
.ftab{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:8px;font-size:.8rem;font-weight:600;text-decoration:none;color:var(--muted);border:1.5px solid transparent;transition:all .15s;}
.ftab:hover{background:#f1f5f9;color:var(--text);text-decoration:none;}
.ftab.active{background:#eff6ff;color:#1d4ed8;border-color:#bfdbfe;}
.btn-xs{padding:4px 9px;font-size:.72rem;font-weight:600;border-radius:6px;}
.page-link{font-size:.8rem;color:var(--brand);border-color:var(--border);}
.page-item.active .page-link{background:var(--brand);border-color:var(--brand);}
.toast-container{position:fixed;top:16px;right:16px;z-index:9999;}
/* Dropdown role change */
.role-dd select{font-size:.75rem;padding:3px 6px;border:1px solid var(--border);border-radius:6px;background:#fff;}
</style>
</head>
<body>
<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="rsis-page">
<div class="p-4">

  <!-- Toast -->
  <?php if (isset($_GET['msg'])): ?>
  <div class="toast-container">
    <div class="toast show align-items-center border-0 bg-success text-white" role="alert">
      <div class="d-flex">
        <div class="toast-body fw-600">
          <?= $_GET['msg']==='updated' ? '✓ Role updated!' : '✓ Status toggled!' ?>
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Header -->
  <div class="d-flex align-items-center justify-content-between mb-4">
    <div>
      <h4 class="mb-0 fw-800 d-flex align-items-center gap-2">
        <i class="fas fa-users text-primary"></i> User Management
      </h4>
      <p class="text-muted mb-0" style="font-size:.83rem">
        All registered users — authors, reviewers, editors
      </p>
    </div>
  </div>

  <!-- Stats -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-2">
      <a href="?<?= buildQ(['role'=>'','page'=>1]) ?>" style="text-decoration:none">
      <div class="stat-card <?= $role===''?'active-filter':'' ?>">
        <div class="stat-icon" style="background:#eff6ff;color:#1d4ed8"><i class="fas fa-users"></i></div>
        <div><div class="stat-val"><?= (int)$stats['total'] ?></div><div class="stat-lbl">Total</div></div>
      </div></a>
    </div>
    <div class="col-6 col-md-2">
      <a href="?<?= buildQ(['role'=>'author','page'=>1]) ?>" style="text-decoration:none">
      <div class="stat-card <?= $role==='author'?'active-filter':'' ?>">
        <div class="stat-icon" style="background:#f1f5f9;color:#475569"><i class="fas fa-pen-nib"></i></div>
        <div><div class="stat-val" style="color:#475569"><?= (int)$stats['authors'] ?></div><div class="stat-lbl">Authors</div></div>
      </div></a>
    </div>
    <div class="col-6 col-md-2">
      <a href="?<?= buildQ(['role'=>'reviewer','page'=>1]) ?>" style="text-decoration:none">
      <div class="stat-card <?= $role==='reviewer'?'active-filter':'' ?>">
        <div class="stat-icon" style="background:#eff6ff;color:#1d4ed8"><i class="fas fa-search"></i></div>
        <div><div class="stat-val" style="color:#1d4ed8"><?= (int)$stats['reviewers'] ?></div><div class="stat-lbl">Reviewers</div></div>
      </div></a>
    </div>
    <div class="col-6 col-md-2">
      <a href="?<?= buildQ(['role'=>'editor','page'=>1]) ?>" style="text-decoration:none">
      <div class="stat-card <?= $role==='editor'?'active-filter':'' ?>">
        <div class="stat-icon" style="background:#fef3c7;color:#d97706"><i class="fas fa-edit"></i></div>
        <div><div class="stat-val" style="color:#d97706"><?= (int)$stats['editors'] ?></div><div class="stat-lbl">Editors</div></div>
      </div></a>
    </div>
    <div class="col-6 col-md-2">
      <a href="?<?= buildQ(['role'=>'both','page'=>1]) ?>" style="text-decoration:none">
      <div class="stat-card <?= $role==='both'?'active-filter':'' ?>">
        <div class="stat-icon" style="background:#f0fdf4;color:#15803d"><i class="fas fa-user-tag"></i></div>
        <div><div class="stat-val" style="color:#15803d"><?= (int)$stats['both_roles'] ?></div><div class="stat-lbl">Both</div></div>
      </div></a>
    </div>
    <div class="col-6 col-md-2">
      <a href="?<?= buildQ(['status'=>'inactive','page'=>1]) ?>" style="text-decoration:none">
      <div class="stat-card <?= $status==='inactive'?'active-filter':'' ?>">
        <div class="stat-icon" style="background:#fee2e2;color:#dc2626"><i class="fas fa-user-slash"></i></div>
        <div><div class="stat-val" style="color:#dc2626"><?= (int)$stats['inactive'] ?></div><div class="stat-lbl">Inactive</div></div>
      </div></a>
    </div>
  </div>

  <!-- Table card -->
  <div class="table-card">

    <!-- Toolbar -->
    <div class="p-3 border-bottom" style="background:#fafbff">
      <div class="d-flex flex-wrap gap-2 align-items-center">

        <!-- Role filter tabs -->
        <div class="d-flex gap-1 flex-wrap">
          <?php
          $roles = [
            ['' , 'All', ''],
            ['author',   'Authors',   'rb-author'],
            ['reviewer', 'Reviewers', 'rb-reviewer'],
            ['editor',   'Editors',   'rb-editor'],
            ['both',     'Both',      'rb-both'],
            ['other',    'Other',     'rb-other'],
          ];
          foreach($roles as [$rv,$rl,$rc]):
          ?>
          <a href="?<?= buildQ(['role'=>$rv,'page'=>1]) ?>"
             class="ftab <?= $role===$rv?'active':'' ?>">
            <?= $rl ?>
          </a>
          <?php endforeach; ?>
        </div>

        <!-- Status filter -->
        <div class="d-flex gap-1 ms-2">
          <a href="?<?= buildQ(['status'=>'','page'=>1]) ?>"
             class="ftab <?= $status===''?'active':'' ?>">All Status</a>
          <a href="?<?= buildQ(['status'=>'active','page'=>1]) ?>"
             class="ftab <?= $status==='active'?'active':'' ?>">Active</a>
          <a href="?<?= buildQ(['status'=>'inactive','page'=>1]) ?>"
             class="ftab <?= $status==='inactive'?'active':'' ?>">Inactive</a>
          <a href="?<?= buildQ(['status'=>'unverified','page'=>1]) ?>"
             class="ftab <?= $status==='unverified'?'active':'' ?>">
            Unverified <span style="background:#fef3c7;color:#92400e;font-size:.65rem;padding:1px 5px;border-radius:10px;margin-left:2px"><?= (int)$stats['unverified'] ?></span>
          </a>
        </div>

        <!-- Search -->
        <form method="GET" class="d-flex gap-2 ms-auto">
          <input type="hidden" name="role"   value="<?= p($role) ?>">
          <input type="hidden" name="status" value="<?= p($status) ?>">
          <input type="search" name="q" class="form-control form-control-sm"
                 style="min-width:220px;font-size:.82rem"
                 placeholder="Name, email, researcher ID…"
                 value="<?= p($search) ?>">
          <button type="submit" class="btn btn-primary btn-sm">
            <i class="fas fa-search"></i>
          </button>
          <?php if($search||$role||$status): ?>
          <a href="users.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-times"></i></a>
          <?php endif; ?>
        </form>

        <span class="text-muted ms-1" style="font-size:.8rem;white-space:nowrap">
          <?= $total ?> user<?= $total!==1?'s':'' ?>
        </span>
      </div>
    </div>

    <!-- Table -->
    <div class="table-responsive">
      <table class="table mb-0" style="border-collapse:separate;border-spacing:0">
        <thead>
          <tr>
            <th class="th">#</th>
            <th class="th">User</th>
            <th class="th">Email</th>
            <th class="th">Role</th>
            <th class="th">Researcher ID</th>
            <th class="th">Affiliation</th>
            <th class="th">Status</th>
            <th class="th">Joined</th>
            <th class="th">Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php if(empty($users)): ?>
        <tr>
          <td colspan="9" class="text-center text-muted py-5">
            <i class="fas fa-users fa-2x mb-2 d-block opacity-25"></i>
            No users found<?= ($search||$role||$status)?' matching filters':'' ?>.
          </td>
        </tr>
        <?php endif; ?>
        <?php foreach($users as $i=>$u):
          $name = trim(($u['title']??'').' '.($u['first_name']??'').' '.($u['last_name']??''));
          $init = strtoupper(substr($u['first_name']??'U',0,1).substr($u['last_name']??'',0,1));
          $roleMap = [
            'author'   => ['rb-author',   'Author'],
            'reviewer' => ['rb-reviewer', 'Reviewer'],
            'editor'   => ['rb-editor',   'Editor'],
            'both'     => ['rb-both',     'Author + Reviewer'],
            'other'    => ['rb-other',    'Other'],
          ];
          [$roleClass, $roleLabel] = $roleMap[$u['role']??'author'] ?? ['rb-other','Unknown'];
        ?>
        <tr>
          <td class="td text-muted" style="font-size:.75rem"><?= $offset+$i+1 ?></td>

          <!-- User -->
          <td class="td" style="min-width:160px">
            <div class="d-flex align-items-center gap-2">
              <?php if(!empty($u['profile_photo_url'])): ?>
              <img src="/<?= p($u['profile_photo_url']) ?>" class="av-img" alt="">
              <?php else: ?>
              <div class="av"><?= p($init) ?></div>
              <?php endif; ?>
              <div>
                <div style="font-size:.83rem;font-weight:600;color:var(--text)"><?= p($name) ?: '—' ?></div>
                <?php if($u['institutional_email']): ?>
                <div style="font-size:.7rem;color:var(--muted)"><?= p($u['institutional_email']) ?></div>
                <?php endif; ?>
              </div>
            </div>
          </td>

          <!-- Email -->
          <td class="td">
            <a href="mailto:<?= p($u['email']) ?>" style="font-size:.78rem;color:#1d4ed8">
              <?= p($u['email']) ?>
            </a>
          </td>

          <!-- Role -->
          <td class="td">
            <span class="rb <?= $roleClass ?>"><?= $roleLabel ?></span>
          </td>

          <!-- Researcher ID -->
          <td class="td">
            <?php if($u['researcher_id']): ?>
            <span class="rid"><?= p($u['researcher_id']) ?></span>
            <?php else: ?>
            <span class="text-muted" style="font-size:.72rem">—</span>
            <?php endif; ?>
          </td>

          <!-- Affiliation -->
          <td class="td" style="max-width:160px">
            <span style="font-size:.78rem;color:var(--text)" class="text-truncate d-block"
                  title="<?= p($u['affil_name']??'') ?>">
              <?= p($u['affil_name'] ?: '—') ?>
            </span>
          </td>

          <!-- Status -->
          <td class="td">
            <?php if(!$u['is_email_verified']): ?>
            <span class="sb-unverified">⚠ Unverified</span>
            <?php elseif($u['is_active']): ?>
            <span class="sb-active">● Active</span>
            <?php else: ?>
            <span class="sb-inactive">● Inactive</span>
            <?php endif; ?>
          </td>

          <!-- Joined -->
          <td class="td" style="white-space:nowrap;font-size:.75rem;color:var(--muted)">
            <?= date('d M Y', strtotime($u['created_at'])) ?>
          </td>

          <!-- Actions -->
          <td class="td">
            <div class="d-flex gap-1 flex-nowrap align-items-center">

              <!-- View details -->
              <button class="btn btn-xs btn-outline-primary"
                      onclick="openModal(<?= htmlspecialchars(json_encode($u), ENT_QUOTES) ?>)"
                      title="View details">
                <i class="fas fa-eye"></i>
              </button>

              <!-- Change role inline -->
              <form method="POST" class="d-inline role-dd">
                <input type="hidden" name="user_id" value="<?= $u['user_id'] ?>">
                <select name="new_role" onchange="this.form.submit()" title="Change role">
                  <?php foreach(['author','reviewer','editor','both','other'] as $r): ?>
                  <option value="<?= $r ?>" <?= ($u['role']??'')===$r?'selected':'' ?>><?= ucfirst($r) ?></option>
                  <?php endforeach; ?>
                </select>
                <button type="submit" name="update_role" style="display:none"></button>
              </form>

              <!-- Toggle active -->
              <form method="POST" class="d-inline">
                <input type="hidden" name="user_id" value="<?= $u['user_id'] ?>">
                <button type="submit" name="toggle_active"
                        class="btn btn-xs <?= $u['is_active']?'btn-outline-warning':'btn-outline-success' ?>"
                        title="<?= $u['is_active']?'Deactivate':'Activate' ?>"
                        onclick="return confirm('<?= $u['is_active']?'Deactivate':'Activate' ?> this user?')">
                  <i class="fas fa-<?= $u['is_active']?'ban':'check' ?>"></i>
                </button>
              </form>

            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Pagination -->
    <?php if($pages > 1): ?>
    <div class="d-flex justify-content-between align-items-center px-4 py-3 border-top">
      <small class="text-muted">Showing <?= $offset+1 ?>–<?= min($offset+$per,$total) ?> of <?= $total ?></small>
      <nav>
        <ul class="pagination pagination-sm mb-0 gap-1">
          <?php for($pg=1;$pg<=$pages;$pg++): ?>
            <?php if($pg===1||$pg===$pages||abs($pg-$page)<=2): ?>
            <li class="page-item <?= $pg===$page?'active':'' ?>">
              <a class="page-link rounded" href="?<?= buildQ(['page'=>$pg]) ?>"><?= $pg ?></a>
            </li>
            <?php elseif(abs($pg-$page)===3): ?>
            <li class="page-item disabled"><span class="page-link">…</span></li>
            <?php endif; ?>
          <?php endfor; ?>
        </ul>
      </nav>
    </div>
    <?php endif; ?>

  </div><!-- /table-card -->

</div>
</div>

<!-- DETAIL MODAL -->
<div class="modal fade" id="userModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content border-0 shadow">
      <div class="modal-header border-0 pb-0" id="modalHdr" style="background:#1d4ed8;border-radius:10px 10px 0 0">
        <div>
          <h5 class="modal-title fw-700 text-white mb-0" id="modalName">User Detail</h5>
          <small class="text-white opacity-75" id="modalEmail"></small>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4" id="modalBody"></div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.querySelectorAll('.toast').forEach(t=>{ setTimeout(()=>bootstrap.Toast.getOrCreateInstance(t).hide(),4000); });

function esc(s){const d=document.createElement('div');d.textContent=String(s??'');return d.innerHTML;}
function row(lbl,val,raw=false){
  const v=raw?(val||'<em class="text-muted">—</em>'):esc(val||'—');
  return `<div class="d-flex gap-3 mb-2 pb-2 border-bottom">
    <div style="min-width:160px;font-size:.78rem;font-weight:700;color:#64748b;flex-shrink:0">${lbl}</div>
    <div style="font-size:.83rem;color:#1e293b">${v}</div>
  </div>`;
}

function openModal(u){
  document.getElementById('modalName').textContent = [(u.title||''),u.first_name,u.last_name].filter(Boolean).join(' ');
  document.getElementById('modalEmail').textContent = u.email;

  const roleColors = {author:'#475569',reviewer:'#1d4ed8',editor:'#d97706',both:'#15803d',other:'#6d28d9'};
  const roleColor = roleColors[u.role] || '#475569';

  const statusHtml = !u.is_email_verified
    ? '<span style="background:#fef3c7;color:#d97706;padding:2px 8px;border-radius:20px;font-size:.72rem;font-weight:700">⚠ Unverified</span>'
    : u.is_active == 1
      ? '<span style="background:#dcfce7;color:#15803d;padding:2px 8px;border-radius:20px;font-size:.72rem;font-weight:700">● Active</span>'
      : '<span style="background:#fee2e2;color:#dc2626;padding:2px 8px;border-radius:20px;font-size:.72rem;font-weight:700">● Inactive</span>';

  const roleHtml = `<span style="background:#eff6ff;color:${esc(roleColor)};padding:2px 10px;border-radius:20px;font-size:.72rem;font-weight:700">${esc(u.role)}</span>`;

  const ridHtml = u.researcher_id
    ? `<span style="font-family:monospace;font-size:.8rem;font-weight:800;color:#1e40af;background:#eff6ff;border:1px solid #bfdbfe;border-radius:4px;padding:2px 8px">${esc(u.researcher_id)}</span>`
    : '<em class="text-muted">Not assigned</em>';

  document.getElementById('modalBody').innerHTML = `
    <div class="row g-4">
      <div class="col-md-6">
        <h6 class="fw-700 text-primary mb-3"><i class="fas fa-user me-2"></i>Personal Info</h6>
        ${row('Full Name', [u.title,u.first_name,u.middle_name,u.last_name].filter(Boolean).join(' '))}
        ${row('Email', `<a href="mailto:${esc(u.email)}">${esc(u.email)}</a>`, true)}
        ${row('Institutional Email', u.institutional_email || '—')}
        ${row('Phone', [(u.phone_country_code||''),(u.phone_number||'')].filter(Boolean).join(' ') || '—')}
        ${row('Affiliation', u.affil_name || '—')}
      </div>
      <div class="col-md-6">
        <h6 class="fw-700 text-primary mb-3"><i class="fas fa-id-badge me-2"></i>Account Info</h6>
        ${row('User ID', '#' + u.user_id)}
        ${row('Role', roleHtml, true)}
        ${row('Researcher ID', ridHtml, true)}
        ${row('Status', statusHtml, true)}
        ${row('Email Verified', u.is_email_verified == 1 ? '✅ Yes' : '❌ No')}
        ${row('Joined', new Date(u.created_at).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'}))}
        ${row('Last Updated', new Date(u.updated_at).toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'}))}
      </div>
    </div>

    <!-- Role change form -->
    <div class="mt-3 p-3" style="background:#f8fafc;border-radius:8px;border:1px solid #e2e8f0">
      <div class="fw-700 mb-2" style="font-size:.85rem">Change Role</div>
      <form method="POST" class="d-flex gap-2 align-items-center flex-wrap">
        <input type="hidden" name="user_id" value="${u.user_id}">
        <select name="new_role" class="form-select form-select-sm" style="width:auto">
          <option value="author"   ${u.role==='author'  ?'selected':''}>Author</option>
          <option value="reviewer" ${u.role==='reviewer'?'selected':''}>Reviewer</option>
          <option value="editor"   ${u.role==='editor'  ?'selected':''}>Editor</option>
          <option value="both"     ${u.role==='both'    ?'selected':''}>Both (Author + Reviewer)</option>
          <option value="other"    ${u.role==='other'   ?'selected':''}>Other</option>
        </select>
        <button type="submit" name="update_role" class="btn btn-primary btn-sm">
          <i class="fas fa-save me-1"></i> Update Role
        </button>
      </form>
    </div>`;

  new bootstrap.Modal(document.getElementById('userModal')).show();
}
</script>
</body>
</html>