<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
$u = require_superadmin();
$pdo = get_db();

$id = (int)($_GET['id'] ?? ($_POST['id'] ?? 0));
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$account) { die('Account not found.'); }

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check();
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = ($_POST['role'] ?? 'admin') === 'superadmin' ? 'superadmin' : 'admin';
    $newPassword = $_POST['password'] ?? '';

    // prevent demoting yourself out of superadmin (would lock you out)
    if ((int)$account['id'] === (int)$u['id'] && $role !== 'superadmin') {
        $error = 'You cannot remove your own Super Admin role.';
    } elseif (strlen($name) < 2) {
        $error = 'Please provide a valid name.';
    } elseif ($newPassword !== '' && strlen($newPassword) < 8) {
        $error = 'New password must be at least 8 characters (or leave blank to keep the current password).';
    } else {
        if ($newPassword !== '') {
            $stmt = $pdo->prepare('UPDATE users SET name=?, email=?, role=?, password_hash=? WHERE id=?');
            $stmt->execute([$name, $email, $role, password_hash($newPassword, PASSWORD_DEFAULT), $id]);
        } else {
            $stmt = $pdo->prepare('UPDATE users SET name=?, email=?, role=? WHERE id=?');
            $stmt->execute([$name, $email, $role, $id]);
        }
        header('Location: users.php?msg=' . urlencode('Account updated for ' . $account['username']));
        exit;
    }
}

$csrf = csrf_token();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Account — Delmas Careers Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link href="assets/admin.css" rel="stylesheet">
</head>
<body>
<?php include __DIR__ . '/includes/topbar.php'; ?>
<div class="admin-wrap" style="max-width:500px">
  <a href="users.php" class="small">&larr; Back to accounts</a>
  <h5 class="mt-2 mb-3">Edit Account — <?= h($account['username']) ?></h5>
  <?php if ($error): ?><div class="alert alert-danger py-2"><?= h($error) ?></div><?php endif; ?>
  <div class="card-plain p-3">
    <form method="post">
      <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
      <input type="hidden" name="id" value="<?= (int)$account['id'] ?>">
      <div class="mb-2"><label class="form-label small">Username</label>
        <input class="form-control form-control-sm" value="<?= h($account['username']) ?>" disabled>
        <div class="form-text">Username cannot be changed.</div>
      </div>
      <div class="mb-2"><label class="form-label small">Full Name</label>
        <input class="form-control form-control-sm" name="name" required value="<?= h($account['name']) ?>"></div>
      <div class="mb-2"><label class="form-label small">Email</label>
        <input class="form-control form-control-sm" type="email" name="email" value="<?= h($account['email']) ?>"></div>
      <div class="mb-2"><label class="form-label small">Role</label>
        <select class="form-select form-select-sm" name="role">
          <option value="admin" <?= $account['role']==='admin'?'selected':'' ?>>Admin (can post &amp; manage jobs)</option>
          <option value="superadmin" <?= $account['role']==='superadmin'?'selected':'' ?>>Super Admin (can also manage accounts)</option>
        </select>
      </div>
      <div class="mb-2"><label class="form-label small">Reset Password <span class="text-muted">(optional)</span></label>
        <input class="form-control form-control-sm" type="password" name="password" minlength="8" placeholder="Leave blank to keep current password"></div>
      <button class="btn btn-gold btn-sm w-100 mt-2" type="submit">Save Changes</button>
    </form>
  </div>
</div>
</body>
</html>
