<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Admin Dashboard - Sentiment Scraper</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <div class="dashboard-container">
    <div class="header">
      <div>
        <h1>Admin Dashboard</h1>
        <p style="margin:0">Welcome back, <strong><%= username %></strong></p>
      </div>
      <div>
        <a href="/logout" class="btn btn-outline" style="width:auto">Logout</a>
      </div>
    </div>

    <div class="grid">
      <!-- User List -->
      <div class="card" style="grid-column: span 2;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <h2 style="margin:0">Registered Users</h2>
          <button onclick="document.getElementById('createUserModal').style.display='flex'" class="btn" style="width:auto">+ Create User</button>
        </div>
        <div style="overflow-x: auto;">
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Role</th>
                <th>Created At</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <% users.forEach(user => { %>
                <tr>
                  <td><%= user.id %></td>
                  <td><%= user.username %></td>
                  <td><span class="badge <%= user.role === 'admin' ? 'badge-admin' : 'badge-user' %>"><%= user.role.toUpperCase() %></span></td>
                  <td><%= new Date(user.created_at).toLocaleString() %></td>
                  <td>
                    <button data-id="<%= user.id %>" data-username="<%= user.username %>" onclick="openResetModal(this.dataset.id, this.dataset.username)" class="btn btn-outline" style="padding: 6px 12px; width:auto; font-size:12px;">Reset Password</button>
                  </td>
                </tr>
              <% }) %>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Create User Modal (Simple implementation via fixed div) -->
  <div id="createUserModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:100; align-items:center; justify-content:center;">
    <div class="auth-card" style="margin: auto; margin-top: 10vh;">
      <h2>Create New User</h2>
      <div id="createAlert" class="alert" style="display:none;"></div>
      <form id="createForm" onsubmit="createUser(event)">
        <div class="form-group">
          <label>Username</label>
          <input type="text" id="c_username" required>
        </div>
        <div class="form-group">
          <label>Password</label>
          <input type="password" id="c_password" required>
        </div>
        <div class="form-group">
          <label>Role</label>
          <select id="c_role">
            <option value="user">User</option>
            <option value="admin">Admin</option>
          </select>
        </div>
        <div class="flex mt-4">
          <button type="button" class="btn btn-outline" onclick="document.getElementById('createUserModal').style.display='none'">Cancel</button>
          <button type="submit" class="btn">Create</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Reset Password Modal -->
  <div id="resetModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); z-index:100; align-items:center; justify-content:center;">
    <div class="auth-card" style="margin: auto; margin-top: 10vh;">
      <h2>Reset Password for <span id="r_username_display"></span></h2>
      <div id="resetAlert" class="alert" style="display:none;"></div>
      <form id="resetForm" onsubmit="resetPassword(event)">
        <input type="hidden" id="r_user_id">
        <div class="form-group">
          <label>New Password</label>
          <input type="password" id="r_password" required>
        </div>
        <div class="flex mt-4">
          <button type="button" class="btn btn-outline" onclick="document.getElementById('resetModal').style.display='none'">Cancel</button>
          <button type="submit" class="btn btn-danger">Reset Password</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    function openResetModal(id, username) {
      document.getElementById('r_user_id').value = id;
      document.getElementById('r_username_display').innerText = username;
      document.getElementById('resetAlert').style.display = 'none';
      document.getElementById('resetModal').style.display = 'flex';
    }

    async function createUser(e) {
      e.preventDefault();
      const username = document.getElementById('c_username').value;
      const password = document.getElementById('c_password').value;
      const role = document.getElementById('c_role').value;
      
      try {
        const res = await fetch('/admin/create-user', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username, password, role })
        });
        const data = await res.json();
        if (res.ok) {
          window.location.reload();
        } else {
          const alert = document.getElementById('createAlert');
          alert.innerText = data.error;
          alert.className = 'alert alert-error';
          alert.style.display = 'block';
        }
      } catch (err) {
        console.error(err);
      }
    }

    async function resetPassword(e) {
      e.preventDefault();
      const user_id = document.getElementById('r_user_id').value;
      const new_password = document.getElementById('r_password').value;
      
      try {
        const res = await fetch('/admin/reset-password', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ user_id, new_password })
        });
        const data = await res.json();
        const alert = document.getElementById('resetAlert');
        if (res.ok) {
          alert.innerText = 'Password reset successful!';
          alert.className = 'alert alert-success';
          alert.style.display = 'block';
          setTimeout(() => document.getElementById('resetModal').style.display = 'none', 1500);
        } else {
          alert.innerText = data.error;
          alert.className = 'alert alert-error';
          alert.style.display = 'block';
        }
      } catch (err) {
        console.error(err);
      }
    }
  </script>
</body>
</html>
