<?php
require_once __DIR__ . "/auth.php";
require_role(['super','admin']);
require_once __DIR__ . "/../includes/db.php";

$message = "";

/* Helpers */
function rand_password($len = 10): string {
  $len = max(6, min(32, (int)$len));
  $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#$%&*!?';
  $out = '';
  for ($i=0;$i<$len;$i++) $out .= $chars[random_int(0, strlen($chars)-1)];
  return $out;
}

/* CREATE */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create'])) {
  $username = trim($_POST['username'] ?? '');
  $display  = trim($_POST['display_name'] ?? '');
  $role     = in_array($_POST['role'] ?? 'staff', ['super','admin','staff'], true) ? $_POST['role'] : 'staff';
  $status   = in_array($_POST['status'] ?? 'active', ['active','disabled'], true) ? $_POST['status'] : 'active';
  $pw_plain = trim($_POST['password'] ?? '');

  if ($username === '' || $pw_plain === '') {
    $message = "<div class='alert alert-danger'>Username and password are required.</div>";
  } else {
    $hash = password_hash($pw_plain, PASSWORD_DEFAULT);
    $st = $conn->prepare("INSERT INTO admins (username, display_name, password, role, status) VALUES (?,?,?,?,?)");
    $st->bind_param("sssss", $username, $display, $hash, $role, $status);

    if ($st->execute()) {
      $message = "<div class='alert alert-success'>Account created. <strong>Temp Password:</strong> " . htmlspecialchars($pw_plain) . "</div>";
    } else {
      $message = "<div class='alert alert-danger'>" . htmlspecialchars($conn->error) . "</div>";
    }
    $st->close();
  }
}

/* UPDATE */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
  $id       = (int)($_POST['id'] ?? 0);
  $username = trim($_POST['username'] ?? '');
  $display  = trim($_POST['display_name'] ?? '');
  $role     = in_array($_POST['role'] ?? 'staff', ['super','admin','staff'], true) ? $_POST['role'] : 'staff';
  $status   = in_array($_POST['status'] ?? 'active', ['active','disabled'], true) ? $_POST['status'] : 'active';

  if ($id <= 0 || $username === '') {
    $message = "<div class='alert alert-danger'>Invalid form.</div>";
  } else {
    if ($id === (int)($_SESSION['admin_id'] ?? 0) && $status === 'disabled') {
      $message = "<div class='alert alert-warning'>You cannot disable your own account.</div>";
    } else {
      $st = $conn->prepare("UPDATE admins SET username=?, display_name=?, role=?, status=? WHERE id=?");
      $st->bind_param("ssssi", $username, $display, $role, $status, $id);

      if ($st->execute()) {
        $message = "<div class='alert alert-info'>Account updated.</div>";
      } else {
        $message = "<div class='alert alert-danger'>" . htmlspecialchars($conn->error) . "</div>";
      }
      $st->close();
    }
  }
}

/* RESET PASSWORD */
if (isset($_GET['reset'])) {
  $id = (int)($_GET['reset'] ?? 0);
  if ($id > 0) {
    $new  = rand_password(10);
    $hash = password_hash($new, PASSWORD_DEFAULT);

    $st = $conn->prepare("UPDATE admins SET password=?, updated_at=NOW() WHERE id=?");
    $st->bind_param("si", $hash, $id);

    if ($st->execute()) {
      $message = "<div class='alert alert-warning'>Password reset. <strong>New Password:</strong> " . htmlspecialchars($new) . "</div>";
    } else {
      $message = "<div class='alert alert-danger'>" . htmlspecialchars($conn->error) . "</div>";
    }
    $st->close();
  }
}

/* CHANGE PASSWORD */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
  $id           = (int)($_POST['id'] ?? 0);
  $new_password = trim($_POST['new_password'] ?? '');

  if ($id <= 0 || $new_password === '') {
    $message = "<div class='alert alert-danger'>New password is required.</div>";
  } elseif (strlen($new_password) < 6) {
    $message = "<div class='alert alert-danger'>Password must be at least 6 characters.</div>";
  } else {
    $hash = password_hash($new_password, PASSWORD_DEFAULT);
    $st = $conn->prepare("UPDATE admins SET password=?, updated_at=NOW() WHERE id=?");
    $st->bind_param("si", $hash, $id);

    if ($st->execute()) {
      $message = "<div class='alert alert-success'>Password changed successfully.</div>";
    } else {
      $message = "<div class='alert alert-danger'>" . htmlspecialchars($conn->error) . "</div>";
    }
    $st->close();
  }
}

/* TOGGLE STATUS */
if (isset($_GET['toggle'])) {
  $id = (int)($_GET['toggle'] ?? 0);
  if ($id === (int)($_SESSION['admin_id'] ?? 0)) {
    $message = "<div class='alert alert-warning'>You cannot toggle your own status.</div>";
  } elseif ($id > 0) {
    $conn->query("UPDATE admins SET status = IF(status='active','disabled','active') WHERE id=" . $id);
    $message = "<div class='alert alert-info'>Status toggled.</div>";
  }
}

/* DELETE */
if (isset($_GET['delete'])) {
  $id = (int)($_GET['delete'] ?? 0);
  if ($id === (int)($_SESSION['admin_id'] ?? 0)) {
    $message = "<div class='alert alert-warning'>You cannot delete your own account.</div>";
  } elseif ($id > 0) {
    $conn->query("DELETE FROM admins WHERE id=" . $id);
    $message = "<div class='alert alert-danger'>Account deleted.</div>";
  }
}

/* LIST */
$list = $conn->query("SELECT id, username, display_name, role, status, last_login, created_at FROM admins ORDER BY id DESC");
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Staff Management • Eden Campus</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">

  <style>
    :root{ --blue:#0b2c61; --red:#e42424; }

    body{
      background:#f5f7fb;
    }

    .card-neo{
      border:0;
      border-radius:16px;
      box-shadow:0 14px 36px rgba(15,23,42,.12);
    }

    .hdr{
      background:linear-gradient(135deg,#0b2c61,#071f49);
      color:#fff;
      border-radius:18px;
      padding:18px 22px;
      box-shadow:0 12px 26px rgba(11,44,97,.14);
    }

    .hdr-full{
      display:block;
      width:100%;
      min-height:84px;
    }

    .page-head{
      display:block;
      width:100%;
      margin-top:22px;
      margin-bottom:18px;
    }

    .btn-theme{
      background:var(--red);
      border-color:var(--red);
      color:#fff;
    }

    .btn-theme:hover{
      background:#c71f1f;
      border-color:#c71f1f;
      color:#fff;
    }

    .table td,
    .table th{
      vertical-align:middle;
      white-space:nowrap;
    }

    .role-col{ width:110px; }
    .status-col{ width:110px; }
    .lastlogin-col{ width:150px; }
    .created-col{ width:150px; }
    .actions-col{ width:420px; }

    .actions-cell{
      text-align:right;
      white-space:nowrap;
    }

    .actions-wrap{
      display:inline-flex;
      align-items:center;
      justify-content:flex-end;
      gap:6px;
      flex-wrap:nowrap;
    }

    .actions-wrap .btn,
    .actions-wrap .you-badge{
      white-space:nowrap;
    }

    .modal-content{
      border:0;
      border-radius:16px;
      box-shadow:0 14px 36px rgba(15,23,42,.18);
    }

    .modal-header,
    .modal-footer{
      border-color:#eef2f7;
    }
  </style>
</head>
<body class="py-4">
<?php
$__topbar_candidates = [
  __DIR__ . '/includes/topbar.php',
  __DIR__ . '/../admin/includes/topbar.php',
  __DIR__ . '/../includes/topbar.php',
];
$__topbar_loaded = false;
foreach ($__topbar_candidates as $__p) {
  if (is_file($__p)) {
    require_once $__p;
    $__topbar_loaded = true;
    break;
  }
}
if (!$__topbar_loaded) {
  echo "<!-- topbar.php not found -->";
}
?>

<div class="container-fluid px-3 px-lg-4" style="max-width:1280px">

  <div class="page-head">
    <div class="hdr hdr-full">
      <div class="fw-bold">Staff & Admin Management</div>
      <div class="small text-white-50">Create staff accounts for the staff portal, or super admins for full access.</div>
    </div>
  </div>

  <?= $message ?>

  <div class="card card-neo mb-3">
    <div class="card-header">Create New Account</div>
    <div class="card-body">
      <form method="post" class="row g-3">
        <div class="col-md-3">
          <label class="form-label">Username</label>
          <input name="username" class="form-control" required>
        </div>

        <div class="col-md-3">
          <label class="form-label">Display Name</label>
          <input name="display_name" class="form-control">
        </div>

        <div class="col-md-3">
          <label class="form-label">Password</label>
          <div class="input-group">
            <input name="password" id="pw" type="text" class="form-control" required>
            <button type="button" class="btn btn-outline-secondary" onclick="genPw()">Generate</button>
          </div>
          <div class="form-text">Share this once with the new user.</div>
        </div>

        <div class="col-md-2">
          <label class="form-label">Role</label>
          <select name="role" class="form-select">
            <option value="staff">Staff</option>
            <option value="admin">Admin</option>
            <option value="super">Super Admin</option>
          </select>
        </div>

        <div class="col-md-1">
          <label class="form-label">Status</label>
          <select name="status" class="form-select">
            <option value="active">Active</option>
            <option value="disabled">Disabled</option>
          </select>
        </div>

        <div class="col-12">
          <button class="btn btn-theme" name="create">Create</button>
        </div>
      </form>
    </div>
  </div>

  <div class="card card-neo">
    <div class="card-header">Accounts</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-hover m-0">
          <thead class="table-light">
            <tr>
              <th>ID</th>
              <th>Username</th>
              <th>Name</th>
              <th class="role-col">Role</th>
              <th class="status-col">Status</th>
              <th class="lastlogin-col">Last Login</th>
              <th class="created-col">Created</th>
              <th class="text-end actions-col">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($list && $list->num_rows): ?>
              <?php while($a = $list->fetch_assoc()): ?>
                <tr>
                  <td><?= (int)$a['id'] ?></td>
                  <td>
                    <form method="post" class="m-0">
                      <input type="hidden" name="id" value="<?= (int)$a['id'] ?>">
                      <input class="form-control form-control-sm" name="username" value="<?= htmlspecialchars($a['username']) ?>">
                  </td>
                  <td>
                      <input class="form-control form-control-sm" name="display_name" value="<?= htmlspecialchars($a['display_name'] ?: '') ?>">
                  </td>
                  <td class="role-col">
                      <select name="role" class="form-select form-select-sm">
                        <option value="staff" <?= $a['role']==='staff'?'selected':'' ?>>Staff</option>
                        <option value="admin" <?= $a['role']==='admin'?'selected':'' ?>>Admin</option>
                        <option value="super" <?= $a['role']==='super'?'selected':'' ?>>Super</option>
                      </select>
                  </td>
                  <td class="status-col">
                      <select name="status" class="form-select form-select-sm">
                        <option value="active" <?= $a['status']==='active'?'selected':'' ?>>Active</option>
                        <option value="disabled" <?= $a['status']==='disabled'?'selected':'' ?>>Disabled</option>
                      </select>
                  </td>
                  <td class="lastlogin-col">
                    <small><?= htmlspecialchars($a['last_login'] ?: '-') ?></small>
                  </td>
                  <td class="created-col">
                    <small><?= htmlspecialchars($a['created_at']) ?></small>
                  </td>
                  <td class="actions-cell">
                    <div class="actions-wrap">
                      <button class="btn btn-sm btn-outline-primary" name="update">Save</button>
                    </form>

                    <a href="users.php?reset=<?= (int)$a['id'] ?>"
                       class="btn btn-sm btn-outline-warning"
                       onclick="return confirm('Reset password for this user?')">
                      Reset PW
                    </a>

                    <button type="button"
                            class="btn btn-sm btn-outline-dark"
                            data-bs-toggle="modal"
                            data-bs-target="#changePwModal<?= (int)$a['id'] ?>">
                      Change PW
                    </button>

                    <a href="users.php?toggle=<?= (int)$a['id'] ?>" class="btn btn-sm btn-outline-secondary">
                      Toggle
                    </a>

                    <?php if ((int)$a['id'] !== (int)($_SESSION['admin_id'] ?? 0)): ?>
                      <a href="users.php?delete=<?= (int)$a['id'] ?>"
                         class="btn btn-sm btn-outline-danger"
                         onclick="return confirm('Delete this account?')">
                        Delete
                      </a>
                    <?php else: ?>
                      <span class="text-muted small you-badge">You</span>
                    <?php endif; ?>
                    </div>

                    <div class="modal fade" id="changePwModal<?= (int)$a['id'] ?>" tabindex="-1" aria-hidden="true">
                      <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                          <form method="post">
                            <div class="modal-header">
                              <h5 class="modal-title">Change Password</h5>
                              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>

                            <div class="modal-body text-start">
                              <input type="hidden" name="id" value="<?= (int)$a['id'] ?>">

                              <div class="mb-3">
                                <label class="form-label">Username</label>
                                <input type="text" class="form-control" value="<?= htmlspecialchars($a['username']) ?>" disabled>
                              </div>

                              <div class="mb-3">
                                <label class="form-label">New Password</label>
                                <input type="text" name="new_password" class="form-control" required>
                                <div class="form-text">Enter a new password for this user.</div>
                              </div>
                            </div>

                            <div class="modal-footer">
                              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                              <button type="submit" name="change_password" class="btn btn-primary">Update Password</button>
                            </div>
                          </form>
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
              <?php endwhile; ?>
            <?php else: ?>
              <tr>
                <td colspan="8" class="text-center p-4">No accounts yet.</td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

</div>

<script>
function genPw(){
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#$%&*!?';
  let out = '';
  for (let i=0;i<10;i++) out += chars[Math.floor(Math.random()*chars.length)];
  document.getElementById('pw').value = out;
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>