<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  header("Location: ../auth/login.php");
  exit;
}

// Fetch all users with site names
$users = $pdo->query("
  SELECT u.*, s.site_name FROM users u
  LEFT JOIN sites s ON u.site_id = s.id
  ORDER BY u.id DESC
")->fetchAll();

// Get site list for dropdowns
$sites = $pdo->query("SELECT id, site_name FROM sites ORDER BY site_name")->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
  <title>Manage Users</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="../assets/css/admin_dashboard.css">
</head>
</head>
<body>

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

<div class="main-content" id="mainContent">
  <div class="container mt-4">
      <h4>👥 Manage Users</h4>
      <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addUserModal">➕ Add User</button>

      <table class="table table-bordered table-hover">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>Username</th>
            <th>Email</th>
            <th>Role</th>
            <th>Site</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($users as $i => $u): ?>
          <tr>
            <td><?= $i + 1 ?></td>
            <td><?= htmlspecialchars($u['username']) ?></td>
            <td><?= htmlspecialchars($u['email']) ?></td>
            <td><?= ucfirst($u['role']) ?></td>
            <td><?= $u['site_name'] ?? 'Unassigned' ?></td>
            <td><?= $u['created_at'] ?></td>
            <td>
              <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#editUser<?= $u['id'] ?>">✏️</button>
              <form method="post" action="users_action.php" class="d-inline" onsubmit="return confirm('Delete this user?');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <button class="btn btn-sm btn-danger">🗑</button>
              </form>
            </td>
          </tr>

          <!-- Edit Modal -->
          <div class="modal fade" id="editUser<?= $u['id'] ?>" tabindex="-1">
            <div class="modal-dialog">
              <form method="post" action="users_action.php" class="modal-content">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <div class="modal-header">
                  <h5 class="modal-title">Edit User</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                  <input name="username" class="form-control mb-2" value="<?= $u['username'] ?>" required>
                  <input name="email" type="email" class="form-control mb-2" value="<?= $u['email'] ?>" required>
                  <select name="role" class="form-select mb-2" required>
                    <option value="officer" <?= $u['role'] === 'officer' ? 'selected' : '' ?>>Officer</option>
                    <option value="admin" <?= $u['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                  </select>
                  <select name="site_id" class="form-select mb-2">
                    <option value="">No site assigned</option>
                    <?php foreach ($sites as $s): ?>
                      <option value="<?= $s['id'] ?>" <?= $u['site_id'] == $s['id'] ? 'selected' : '' ?>><?= $s['site_name'] ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="modal-footer">
                  <button class="btn btn-success">Update</button>
                </div>
              </form>
            </div>
          </div>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- Add User Modal -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
      <div class="modal-dialog">
        <form method="post" action="users_action.php" class="modal-content">
          <input type="hidden" name="action" value="add">
          <div class="modal-header">
            <h5 class="modal-title">Add User</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <input name="username" class="form-control mb-2" placeholder="Username" required>
            <input name="email" type="email" class="form-control mb-2" placeholder="Email" required>
            <input name="password" type="password" class="form-control mb-2" placeholder="Password" required>
            <select name="role" class="form-select mb-2" required>
              <option value="officer">Officer</option>
              <option value="admin">Admin</option>
            </select>
            <select name="site_id" class="form-select mb-2">
              <option value="">No site assigned</option>
              <?php foreach ($sites as $s): ?>
                <option value="<?= $s['id'] ?>"><?= $s['site_name'] ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="modal-footer">
            <button class="btn btn-primary">Add User</button>
          </div>
        </form>
      </div>
    </div>
</div>

<script>
  const ctx = document.getElementById('trendChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: <?= $trendLabels ?>,
      datasets: [{
        label: 'Check-ins',
        data: <?= $trendCounts ?>,
        backgroundColor: '#004080',
        borderRadius: 8
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true,
          ticks: { stepSize: 1 }
        }
      }
    }
  });
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
