<?php
include 'header.php';
require '../config.php';

$error = "";
$success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $role = $_POST['role'] ?? 'staff';

    if (!empty($username) && !empty($email) && !empty($password)) {
        // تحقق من وجود الإيميل مسبقاً
        $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
        $check->execute([$email]);
        if ($check->fetchColumn() > 0) {
            $error = "الإيميل مستخدم مسبقاً.";
        } else {
            // تشفير كلمة السر
            $hashed = password_hash($password, PASSWORD_BCRYPT);

            $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role) VALUES (?,?,?,?)");
            $stmt->execute([$username, $email, $hashed, $role]);

            $success = "تمت إضافة المستخدم بنجاح.";
        }
    } else {
        $error = "الرجاء تعبئة جميع الحقول.";
    }
}
?>

<h3>➕ إضافة مستخدم جديد</h3>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= $error ?></div>
<?php endif; ?>
<?php if ($success): ?>
  <div class="alert alert-success"><?= $success ?></div>
<?php endif; ?>

<form method="POST" class="card p-4 shadow-sm">
  <div class="mb-3">
    <label class="form-label">اسم المستخدم</label>
    <input type="text" name="username" class="form-control" required>
  </div>
  <div class="mb-3">
    <label class="form-label">الإيميل</label>
    <input type="email" name="email" class="form-control" required>
  </div>
  <div class="mb-3">
    <label class="form-label">كلمة المرور</label>
    <input type="password" name="password" class="form-control" required>
  </div>
  <div class="mb-3">
    <label class="form-label">الدور</label>
    <select name="role" class="form-select">
      <option value="admin">مدير</option>
      <option value="staff" selected>موظف</option>
    </select>
  </div>
  <button type="submit" class="btn btn-success">حفظ</button>
  <a href="users.php" class="btn btn-secondary">رجوع</a>
</form>

<?php include 'footer.php'; ?>
