<?php
// ============================================================
// admin.php - Admin Dashboard for Clyde 37-DE RCI-1550 Console
// ============================================================
// Place this file in the same directory as your dashboard HTML
// ============================================================

session_start();

// --- CONFIGURATION ---
$USERS_FILE = __DIR__ . '/users.json';
$SESSION_TIMEOUT = 3600; // 1 hour

// --- HELPER FUNCTIONS ---
function loadUsers() {
    global $USERS_FILE;
    if (!file_exists($USERS_FILE)) {
        // Create default admin user
        $default = [
            'admin' => [
                'password' => password_hash('admin123', PASSWORD_DEFAULT),
                'email' => 'admin@example.com',
                'role' => 'admin',
                'created' => date('Y-m-d H:i:s'),
                'last_login' => null,
                'active' => true
            ]
        ];
        file_put_contents($USERS_FILE, json_encode($default, JSON_PRETTY_PRINT));
        return $default;
    }
    return json_decode(file_get_contents($USERS_FILE), true) ?: [];
}

function saveUsers($users) {
    global $USERS_FILE;
    file_put_contents($USERS_FILE, json_encode($users, JSON_PRETTY_PRINT));
}

function getUser($username) {
    $users = loadUsers();
    return $users[$username] ?? null;
}

function userExists($username) {
    $users = loadUsers();
    return isset($users[$username]);
}

function createUser($username, $password, $email, $role = 'user') {
    $users = loadUsers();
    if (isset($users[$username])) return false;
    $users[$username] = [
        'password' => password_hash($password, PASSWORD_DEFAULT),
        'email' => $email,
        'role' => $role,
        'created' => date('Y-m-d H:i:s'),
        'last_login' => null,
        'active' => true
    ];
    saveUsers($users);
    return true;
}

function deleteUser($username) {
    $users = loadUsers();
    if ($username === 'admin') return false; // Cannot delete admin
    if (!isset($users[$username])) return false;
    unset($users[$username]);
    saveUsers($users);
    return true;
}

function updateUserPassword($username, $newPassword) {
    $users = loadUsers();
    if (!isset($users[$username])) return false;
    $users[$username]['password'] = password_hash($newPassword, PASSWORD_DEFAULT);
    saveUsers($users);
    return true;
}

function toggleUserActive($username) {
    $users = loadUsers();
    if ($username === 'admin') return false;
    if (!isset($users[$username])) return false;
    $users[$username]['active'] = !$users[$username]['active'];
    saveUsers($users);
    return true;
}

function updateUserEmail($username, $email) {
    $users = loadUsers();
    if (!isset($users[$username])) return false;
    $users[$username]['email'] = $email;
    saveUsers($users);
    return true;
}

function updateUserRole($username, $role) {
    $users = loadUsers();
    if ($username === 'admin') return false;
    if (!isset($users[$username])) return false;
    $users[$username]['role'] = $role;
    saveUsers($users);
    return true;
}

function recordLogin($username) {
    $users = loadUsers();
    if (!isset($users[$username])) return;
    $users[$username]['last_login'] = date('Y-m-d H:i:s');
    saveUsers($users);
}

function isLoggedIn() {
    if (!isset($_SESSION['user'])) return false;
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $GLOBALS['SESSION_TIMEOUT'])) {
        session_destroy();
        return false;
    }
    $_SESSION['last_activity'] = time();
    return true;
}

function isAdmin() {
    return isLoggedIn() && ($_SESSION['role'] ?? '') === 'admin';
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: admin.php?action=login');
        exit;
    }
}

function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: admin.php');
        exit;
    }
}

// --- HANDLE ACTIONS ---
$message = '';
$messageType = '';

// Login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'login':
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $user = getUser($username);
            if ($user && password_verify($password, $user['password']) && $user['active']) {
                $_SESSION['user'] = $username;
                $_SESSION['role'] = $user['role'];
                $_SESSION['last_activity'] = time();
                recordLogin($username);
                header('Location: admin.php');
                exit;
            } else {
                $message = 'Invalid credentials or account inactive.';
                $messageType = 'error';
            }
            break;

        case 'logout':
            session_destroy();
            header('Location: admin.php?action=login');
            exit;

        case 'create_user':
            requireAdmin();
            $username = trim($_POST['new_username'] ?? '');
            $password = $_POST['new_password'] ?? '';
            $email = trim($_POST['new_email'] ?? '');
            $role = $_POST['new_role'] ?? 'user';
            
            if (empty($username) || empty($password) || empty($email)) {
                $message = 'All fields are required.';
                $messageType = 'error';
            } elseif (strlen($password) < 6) {
                $message = 'Password must be at least 6 characters.';
                $messageType = 'error';
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = 'Invalid email address.';
                $messageType = 'error';
            } elseif (createUser($username, $password, $email, $role)) {
                $message = "User '$username' created successfully.";
                $messageType = 'success';
            } else {
                $message = "User '$username' already exists.";
                $messageType = 'error';
            }
            break;

        case 'delete_user':
            requireAdmin();
            $username = $_POST['del_username'] ?? '';
            if (deleteUser($username)) {
                $message = "User '$username' deleted.";
                $messageType = 'success';
            } else {
                $message = "Cannot delete user '$username' (admin or not found).";
                $messageType = 'error';
            }
            break;

        case 'toggle_active':
            requireAdmin();
            $username = $_POST['toggle_username'] ?? '';
            if (toggleUserActive($username)) {
                $message = "User '$username' status toggled.";
                $messageType = 'success';
            } else {
                $message = "Cannot toggle admin or user not found.";
                $messageType = 'error';
            }
            break;

        case 'change_password':
            requireLogin();
            $current = $_POST['current_password'] ?? '';
            $new = $_POST['new_password'] ?? '';
            $confirm = $_POST['confirm_password'] ?? '';
            $username = $_SESSION['user'];
            
            $user = getUser($username);
            if (!password_verify($current, $user['password'])) {
                $message = 'Current password is incorrect.';
                $messageType = 'error';
            } elseif (strlen($new) < 6) {
                $message = 'New password must be at least 6 characters.';
                $messageType = 'error';
            } elseif ($new !== $confirm) {
                $message = 'New passwords do not match.';
                $messageType = 'error';
            } else {
                updateUserPassword($username, $new);
                $message = 'Password changed successfully.';
                $messageType = 'success';
            }
            break;

        case 'admin_change_password':
            requireAdmin();
            $username = $_POST['admin_username'] ?? '';
            $new = $_POST['admin_new_password'] ?? '';
            if (updateUserPassword($username, $new)) {
                $message = "Password for '$username' updated.";
                $messageType = 'success';
            } else {
                $message = "User not found.";
                $messageType = 'error';
            }
            break;

        case 'update_email':
            requireAdmin();
            $username = $_POST['email_username'] ?? '';
            $email = trim($_POST['new_email'] ?? '');
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $message = 'Invalid email address.';
                $messageType = 'error';
            } elseif (updateUserEmail($username, $email)) {
                $message = "Email for '$username' updated.";
                $messageType = 'success';
            } else {
                $message = "User not found.";
                $messageType = 'error';
            }
            break;

        case 'update_role':
            requireAdmin();
            $username = $_POST['role_username'] ?? '';
            $role = $_POST['new_role'] ?? 'user';
            if (updateUserRole($username, $role)) {
                $message = "Role for '$username' updated to '$role'.";
                $messageType = 'success';
            } else {
                $message = "Cannot update admin role or user not found.";
                $messageType = 'error';
            }
            break;
    }
}

// --- PAGE LOGIC ---
$currentAction = $_GET['action'] ?? '';
$users = loadUsers();

// Logout redirect
if ($currentAction === 'logout') {
    session_destroy();
    header('Location: admin.php?action=login');
    exit;
}

// Login page
if ($currentAction === 'login' && !isLoggedIn()) {
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login · Clyde 37-DE</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Oswald:wght@400;600;700&family=Inter:wght@400;500;600&display=swap');
        *{box-sizing:border-box;margin:0;padding:0;}
        body{
            background:linear-gradient(180deg,#1a1e22,#0d0f11);
            min-height:100vh;
            display:flex;
            align-items:center;
            justify-content:center;
            font-family:'Inter',sans-serif;
            padding:20px;
        }
        .login-box{
            background:#1c2126;
            border:1px solid #343a40;
            border-radius:12px;
            padding:40px 36px 32px;
            max-width:380px;
            width:100%;
        }
        .login-box h1{
            font-family:'Oswald',sans-serif;
            font-size:26px;
            color:#ece9e2;
            text-transform:uppercase;
            letter-spacing:0.02em;
            margin-bottom:4px;
        }
        .login-box h1 span{color:#ffc52f;}
        .login-box .sub{
            color:#9aa1a8;
            font-size:13px;
            margin-bottom:24px;
        }
        .login-box label{
            display:block;
            font-size:12px;
            color:#9aa1a8;
            margin-bottom:4px;
            font-weight:500;
            letter-spacing:0.03em;
            text-transform:uppercase;
        }
        .login-box input{
            width:100%;
            padding:10px 12px;
            background:#0e1113;
            border:1px solid #343a40;
            border-radius:6px;
            color:#ece9e2;
            font-size:14px;
            margin-bottom:14px;
            transition:border-color .2s;
        }
        .login-box input:focus{
            outline:none;
            border-color:#ffc52f;
        }
        .login-box button{
            width:100%;
            padding:11px 0;
            font-family:'Oswald',sans-serif;
            font-size:16px;
            text-transform:uppercase;
            background:#ffc52f;
            color:#15181b;
            border:none;
            border-radius:6px;
            font-weight:600;
            cursor:pointer;
            transition:filter .15s;
        }
        .login-box button:hover{filter:brightness(1.08);}
        .msg{
            padding:10px 12px;
            border-radius:6px;
            font-size:13px;
            margin-bottom:16px;
        }
        .msg.error{background:rgba(255,82,82,0.12);border:1px solid rgba(255,82,82,0.3);color:#ff5252;}
        .msg.success{background:rgba(82,209,124,0.12);border:1px solid rgba(82,209,124,0.3);color:#52d17c;}
        .login-foot{
            margin-top:16px;
            font-size:12px;
            color:#5c636a;
            text-align:center;
        }
        .login-foot a{color:#9aa1a8;text-decoration:none;}
        .login-foot a:hover{color:#ffc52f;}
    </style>
</head>
<body>
    <div class="login-box">
        <h1>Clyde <span>37-DE</span></h1>
        <div class="sub">Admin Login</div>
        <?php if ($message): ?>
        <div class="msg <?= $messageType ?>"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>
        <form method="POST">
            <input type="hidden" name="action" value="login">
            <label>Username</label>
            <input type="text" name="username" required autofocus>
            <label>Password</label>
            <input type="password" name="password" required>
            <button type="submit">Sign In</button>
        </form>
        <div class="login-foot">
            Default: <b style="color:#9aa1a8;">admin</b> / <b style="color:#9aa1a8;">admin123</b>
        </div>
    </div>
</body>
</html>
    <?php
    exit;
}

// --- REQUIRE LOGIN FOR EVERYTHING ELSE ---
requireLogin();

// --- MAIN ADMIN DASHBOARD ---
$currentUser = $_SESSION['user'];
$isAdmin = isAdmin();
$users = loadUsers();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard · Clyde 37-DE</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Oswald:wght@400;600;700&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
        *{box-sizing:border-box;}
        body{
            margin:0;
            padding:0;
            background:#15181b;
            color:#ece9e2;
            font-family:'Inter',sans-serif;
            min-height:100vh;
        }
        /* HEADER */
        .admin-header{
            background:#1c2126;
            border-bottom:2px solid #ffc52f;
            padding:16px 24px;
            display:flex;
            justify-content:space-between;
            align-items:center;
            flex-wrap:wrap;
            gap:12px;
            position:sticky;
            top:0;
            z-index:100;
        }
        .admin-header .brand{
            font-family:'Oswald',sans-serif;
            font-size:22px;
            text-transform:uppercase;
            letter-spacing:0.02em;
        }
        .admin-header .brand span{color:#ffc52f;}
        .admin-header .brand small{
            font-family:'Inter',sans-serif;
            font-size:12px;
            color:#9aa1a8;
            font-weight:400;
            text-transform:none;
            letter-spacing:0;
            margin-left:10px;
        }
        .admin-header .user-info{
            display:flex;
            align-items:center;
            gap:14px;
            font-size:13px;
        }
        .admin-header .user-info .role-badge{
            font-size:10px;
            text-transform:uppercase;
            letter-spacing:0.06em;
            padding:3px 10px;
            border-radius:12px;
            background:#ffc52f;
            color:#15181b;
            font-weight:600;
        }
        .admin-header .user-info .role-badge.user{background:#343a40;color:#9aa1a8;}
        .admin-header .user-info a{
            color:#9aa1a8;
            text-decoration:none;
            font-size:12px;
            padding:5px 12px;
            border:1px solid #343a40;
            border-radius:4px;
            transition:all .15s;
        }
        .admin-header .user-info a:hover{
            border-color:#ffc52f;
            color:#ece9e2;
        }
        .admin-header .user-info a.danger:hover{border-color:#ff5252;color:#ff5252;}
        /* LAYOUT */
        .admin-wrap{max-width:1200px;margin:0 auto;padding:24px;}
        .page-title{
            font-family:'Oswald',sans-serif;
            font-size:24px;
            text-transform:uppercase;
            letter-spacing:0.02em;
            margin:0 0 4px 0;
        }
        .page-title span{color:#ffc52f;}
        .page-sub{color:#9aa1a8;font-size:13px;margin-bottom:24px;}
        /* CARDS */
        .grid-2{display:grid;grid-template-columns:1fr 1fr;gap:20px;}
        @media(max-width:800px){.grid-2{grid-template-columns:1fr;}}
        .card{
            background:#1c2126;
            border:1px solid #2a3036;
            border-radius:8px;
            padding:20px 22px;
            margin-bottom:20px;
        }
        .card h2{
            font-family:'Oswald',sans-serif;
            font-size:16px;
            text-transform:uppercase;
            letter-spacing:0.03em;
            color:#ffc52f;
            margin:0 0 14px 0;
            display:flex;
            align-items:center;
            gap:8px;
        }
        .card h2 .badge{
            font-family:'Inter',sans-serif;
            font-size:10px;
            background:#343a40;
            color:#9aa1a8;
            padding:2px 8px;
            border-radius:10px;
            font-weight:400;
            text-transform:none;
            letter-spacing:0;
        }
        .card label{
            display:block;
            font-size:12px;
            color:#9aa1a8;
            font-weight:500;
            letter-spacing:0.03em;
            text-transform:uppercase;
            margin-bottom:4px;
        }
        .card input, .card select{
            width:100%;
            padding:8px 11px;
            background:#0e1113;
            border:1px solid #343a40;
            border-radius:4px;
            color:#ece9e2;
            font-size:13px;
            margin-bottom:10px;
            font-family:'Inter',sans-serif;
        }
        .card input:focus, .card select:focus{
            outline:none;
            border-color:#ffc52f;
        }
        .card .row-2{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
        @media(max-width:500px){.card .row-2{grid-template-columns:1fr;}}
        .btn{
            padding:8px 16px;
            border:none;
            border-radius:4px;
            font-weight:600;
            font-size:13px;
            cursor:pointer;
            transition:filter .15s, background .15s;
            font-family:'Inter',sans-serif;
        }
        .btn:hover{filter:brightness(1.1);}
        .btn-primary{background:#ffc52f;color:#15181b;}
        .btn-danger{background:#ff5252;color:#fff;}
        .btn-success{background:#52d17c;color:#15181b;}
        .btn-warning{background:#ff9a1f;color:#15181b;}
        .btn-outline{background:transparent;color:#9aa1a8;border:1px solid #343a40;}
        .btn-outline:hover{background:#343a40;color:#ece9e2;}
        .btn-sm{padding:5px 10px;font-size:11px;}
        .mt-8{margin-top:8px;}
        .mt-12{margin-top:12px;}
        /* TABLE */
        .table-wrap{overflow-x:auto;}
        table{width:100%;border-collapse:collapse;font-size:13px;}
        th{
            text-align:left;
            padding:9px 10px;
            color:#9aa1a8;
            font-weight:500;
            font-size:11px;
            text-transform:uppercase;
            letter-spacing:0.05em;
            border-bottom:1px solid #2a3036;
        }
        td{
            padding:9px 10px;
            border-bottom:1px solid #2a3036;
            color:#ece9e2;
        }
        tr:hover td{background:rgba(255,197,47,0.03);}
        .status-badge{
            display:inline-block;
            padding:2px 10px;
            border-radius:10px;
            font-size:10px;
            text-transform:uppercase;
            font-weight:600;
            letter-spacing:0.04em;
        }
        .status-badge.active{background:rgba(82,209,124,0.15);color:#52d17c;border:1px solid rgba(82,209,124,0.3);}
        .status-badge.inactive{background:rgba(255,82,82,0.12);color:#ff5252;border:1px solid rgba(255,82,82,0.3);}
        .role-tag{
            display:inline-block;
            padding:1px 8px;
            border-radius:3px;
            font-size:10px;
            text-transform:uppercase;
            font-weight:600;
            background:#343a40;
            color:#9aa1a8;
        }
        .role-tag.admin{background:#ffc52f;color:#15181b;}
        .action-group{display:flex;gap:5px;flex-wrap:wrap;}
        .msg{
            padding:10px 14px;
            border-radius:6px;
            font-size:13px;
            margin-bottom:16px;
        }
        .msg.error{background:rgba(255,82,82,0.1);border:1px solid rgba(255,82,82,0.2);color:#ff5252;}
        .msg.success{background:rgba(82,209,124,0.1);border:1px solid rgba(82,209,124,0.2);color:#52d17c;}
        .msg.info{background:rgba(255,197,47,0.08);border:1px solid rgba(255,197,47,0.15);color:#ffc52f;}
        .inline-form{display:inline;}
        .mt-20{margin-top:20px;}
        .text-muted{color:#5c636a;font-size:12px;}
        .divider{border-top:1px solid #2a3036;margin:16px 0;}
        .dashboard-stats{
            display:grid;
            grid-template-columns:repeat(auto-fit,minmax(140px,1fr));
            gap:14px;
            margin-bottom:20px;
        }
        .stat-card{
            background:#0e1113;
            border:1px solid #2a3036;
            border-radius:6px;
            padding:14px 16px;
        }
        .stat-card .num{
            font-family:'Oswald',sans-serif;
            font-size:28px;
            color:#ffc52f;
        }
        .stat-card .label{font-size:11px;color:#5c636a;text-transform:uppercase;letter-spacing:0.04em;}

        .back-link{
            display:inline-block;
            color:#9aa1a8;
            text-decoration:none;
            font-size:13px;
            padding:5px 0;
        }
        .back-link:hover{color:#ffc52f;}
    </style>
</head>
<body>

<!-- HEADER -->
<header class="admin-header">
    <div class="brand">
        Clyde <span>37-DE</span>
        <small>Admin</small>
    </div>
    <div class="user-info">
        <span><?= htmlspecialchars($currentUser) ?></span>
        <span class="role-badge <?= $isAdmin ? '' : 'user' ?>"><?= $isAdmin ? 'Admin' : 'User' ?></span>
        <a href="admin.php?action=change_pass">Change Password</a>
        <a href="admin.php?action=logout" class="danger">Sign Out</a>
    </div>
</header>

<div class="admin-wrap">

    <!-- DASHBOARD STATS -->
    <?php if ($isAdmin): ?>
    <div class="dashboard-stats">
        <div class="stat-card"><div class="num"><?= count($users) ?></div><div class="label">Total Users</div></div>
        <div class="stat-card"><div class="num"><?= count(array_filter($users, fn($u) => $u['active'])) ?></div><div class="label">Active</div></div>
        <div class="stat-card"><div class="num"><?= count(array_filter($users, fn($u) => ($u['role'] ?? '') === 'admin')) ?></div><div class="label">Admins</div></div>
        <div class="stat-card"><div class="num"><?= count(array_filter($users, fn($u) => ($u['role'] ?? '') === 'user')) ?></div><div class="label">Users</div></div>
    </div>
    <?php endif; ?>

    <!-- MESSAGES -->
    <?php if ($message): ?>
    <div class="msg <?= $messageType ?>"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <!-- PAGE TITLE -->
    <div class="page-title">Admin <span>Dashboard</span></div>
    <div class="page-sub">Manage users and system settings for the Clyde 37-DE RCI-1550 console.</div>

    <!-- ============================================================ -->
    <!-- USER MANAGEMENT (ADMIN ONLY) -->
    <!-- ============================================================ -->
    <?php if ($isAdmin): ?>

    <!-- CREATE USER -->
    <div class="card">
        <h2>➕ Create New User</h2>
        <form method="POST">
            <input type="hidden" name="action" value="create_user">
            <div class="row-2">
                <div>
                    <label>Username</label>
                    <input type="text" name="new_username" required placeholder="e.g. johndoe">
                </div>
                <div>
                    <label>Email</label>
                    <input type="email" name="new_email" required placeholder="user@example.com">
                </div>
            </div>
            <div class="row-2">
                <div>
                    <label>Password (min 6 chars)</label>
                    <input type="password" name="new_password" required minlength="6">
                </div>
                <div>
                    <label>Role</label>
                    <select name="new_role">
                        <option value="user">User</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Create User</button>
        </form>
    </div>

    <!-- USER TABLE -->
    <div class="card">
        <h2>👥 Manage Users <span class="badge"><?= count($users) ?></span></h2>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Last Login</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $username => $data): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($username) ?></strong></td>
                        <td><?= htmlspecialchars($data['email'] ?? '—') ?></td>
                        <td><span class="role-tag <?= ($data['role'] ?? 'user') === 'admin' ? 'admin' : '' ?>"><?= htmlspecialchars($data['role'] ?? 'user') ?></span></td>
                        <td>
                            <span class="status-badge <?= $data['active'] ? 'active' : 'inactive' ?>">
                                <?= $data['active'] ? 'Active' : 'Inactive' ?>
                            </span>
                        </td>
                        <td style="font-size:12px;color:#9aa1a8;"><?= htmlspecialchars($data['created'] ?? '—') ?></td>
                        <td style="font-size:12px;color:#9aa1a8;"><?= htmlspecialchars($data['last_login'] ?? 'Never') ?></td>
                        <td>
                            <div class="action-group">
                                <?php if ($username !== 'admin'): ?>
                                <!-- Toggle Active -->
                                <form method="POST" class="inline-form">
                                    <input type="hidden" name="action" value="toggle_active">
                                    <input type="hidden" name="toggle_username" value="<?= htmlspecialchars($username) ?>">
                                    <button type="submit" class="btn btn-sm <?= $data['active'] ? 'btn-warning' : 'btn-success' ?>">
                                        <?= $data['active'] ? 'Deactivate' : 'Activate' ?>
                                    </button>
                                </form>
                                <!-- Delete -->
                                <form method="POST" class="inline-form" onsubmit="return confirm('Delete user \'<?= htmlspecialchars($username) ?>\'? This cannot be undone.')">
                                    <input type="hidden" name="action" value="delete_user">
                                    <input type="hidden" name="del_username" value="<?= htmlspecialchars($username) ?>">
                                    <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                                </form>
                                <!-- Change Password (admin) -->
                                <button class="btn btn-sm btn-outline" onclick="document.getElementById('adminPassForm_<?= $username ?>').style.display=document.getElementById('adminPassForm_<?= $username ?>').style.display==='block'?'none':'block'">Set Password</button>
                                <button class="btn btn-sm btn-outline" onclick="document.getElementById('adminEmailForm_<?= $username ?>').style.display=document.getElementById('adminEmailForm_<?= $username ?>').style.display==='block'?'none':'block'">Set Email</button>
                                <button class="btn btn-sm btn-outline" onclick="document.getElementById('adminRoleForm_<?= $username ?>').style.display=document.getElementById('adminRoleForm_<?= $username ?>').style.display==='block'?'none':'block'">Set Role</button>
                                <?php else: ?>
                                <span class="text-muted">Protected</span>
                                <?php endif; ?>
                            </div>
                            <!-- Inline forms for admin actions -->
                            <?php if ($username !== 'admin'): ?>
                            <div id="adminPassForm_<?= $username ?>" style="display:none;margin-top:6px;">
                                <form method="POST" class="inline-form">
                                    <input type="hidden" name="action" value="admin_change_password">
                                    <input type="hidden" name="admin_username" value="<?= htmlspecialchars($username) ?>">
                                    <input type="password" name="admin_new_password" placeholder="New password" required minlength="6" style="padding:4px 8px;font-size:12px;width:120px;background:#0e1113;border:1px solid #343a40;color:#ece9e2;border-radius:3px;">
                                    <button type="submit" class="btn btn-sm btn-primary">Update</button>
                                </form>
                            </div>
                            <div id="adminEmailForm_<?= $username ?>" style="display:none;margin-top:6px;">
                                <form method="POST" class="inline-form">
                                    <input type="hidden" name="action" value="update_email">
                                    <input type="hidden" name="email_username" value="<?= htmlspecialchars($username) ?>">
                                    <input type="email" name="new_email" placeholder="New email" required style="padding:4px 8px;font-size:12px;width:140px;background:#0e1113;border:1px solid #343a40;color:#ece9e2;border-radius:3px;">
                                    <button type="submit" class="btn btn-sm btn-primary">Update</button>
                                </form>
                            </div>
                            <div id="adminRoleForm_<?= $username ?>" style="display:none;margin-top:6px;">
                                <form method="POST" class="inline-form">
                                    <input type="hidden" name="action" value="update_role">
                                    <input type="hidden" name="role_username" value="<?= htmlspecialchars($username) ?>">
                                    <select name="new_role" style="padding:4px 8px;font-size:12px;background:#0e1113;border:1px solid #343a40;color:#ece9e2;border-radius:3px;">
                                        <option value="user" <?= ($data['role']??'user')==='user'?'selected':'' ?>>User</option>
                                        <option value="admin" <?= ($data['role']??'')==='admin'?'selected':'' ?>>Admin</option>
                                    </select>
                                    <button type="submit" class="btn btn-sm btn-primary">Update</button>
                                </form>
                            </div>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="text-muted mt-12">* Users with role 'Admin' have full system access.</div>
    </div>

    <?php endif; ?>

    <!-- ============================================================ -->
    <!-- CHANGE PASSWORD (ALL USERS) -->
    <!-- ============================================================ -->
    <?php if ($_GET['action'] === 'change_pass' || !$isAdmin): ?>
    <div class="card">
        <h2>🔑 Change Your Password</h2>
        <form method="POST">
            <input type="hidden" name="action" value="change_password">
            <div>
                <label>Current Password</label>
                <input type="password" name="current_password" required style="max-width:300px;">
            </div>
            <div class="row-2" style="max-width:600px;">
                <div>
                    <label>New Password (min 6 chars)</label>
                    <input type="password" name="new_password" required minlength="6">
                </div>
                <div>
                    <label>Confirm New Password</label>
                    <input type="password" name="confirm_password" required minlength="6">
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Change Password</button>
        </form>
    </div>
    <?php endif; ?>

    <!-- ============================================================ -->
    <!-- USER-SPECIFIC SETTINGS (non-admin) -->
    <!-- ============================================================ -->
    <?php if (!$isAdmin): ?>
    <div class="card">
        <h2>ℹ️ My Account</h2>
        <p style="color:#9aa1a8;font-size:13px;">
            Username: <strong style="color:#ece9e2;"><?= htmlspecialchars($currentUser) ?></strong><br>
            Role: <strong style="color:#ece9e2;"><?= htmlspecialchars($_SESSION['role'] ?? 'user') ?></strong><br>
            <span class="text-muted">Contact your administrator to change your email or role.</span>
        </p>
    </div>
    <?php endif; ?>

    <!-- ============================================================ -->
    <!-- BACK TO DASHBOARD -->
    <!-- ============================================================ -->
    <div class="mt-20">
        <a href="admin.php" class="back-link">← Back to Dashboard</a>
        <span style="margin-left:20px;color:#5c636a;font-size:12px;">
            <a href="Clyde_37DE_RCI1550_Dashboard.html" style="color:#9aa1a8;text-decoration:none;">Return to Crane Console →</a>
        </span>
    </div>

    <div style="text-align:center;color:#5c636a;font-size:11px;margin-top:30px;padding-top:16px;border-top:1px solid #2a3036;">
        Clyde 37-DE Admin Dashboard &bull; RCI-1550 Console
    </div>
</div>

</body>
</html>