<?php
require '../db.php';
require '../auth.php';
require_login();
require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $nama_lengkap = trim($_POST['nama_lengkap'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? '';
    
    // Validate required fields
    if (empty($username) || empty($nama_lengkap) || empty($password) || empty($role)) {
        header('Location: users.php?error=Semua field wajib harus diisi');
        exit;
    }
    
    // Validate role
    if (!in_array($role, ['admin', 'petugas'])) {
        header('Location: users.php?error=Role tidak valid');
        exit;
    }
    
    // Validate password length
    if (strlen($password) < 6) {
        header('Location: users.php?error=Password minimal 6 karakter');
        exit;
    }
    
    try {
        // Check if username already exists
        $check = $db->prepare('SELECT id FROM users WHERE username = ?');
        $check->execute([$username]);
        if ($check->fetch()) {
            header('Location: users.php?error=Username sudah digunakan');
            exit;
        }
        
        // Create user
        $stmt = $db->prepare('INSERT INTO users (username, nama_lengkap, password_hash, role) VALUES (?, ?, ?, ?)');
        $result = $stmt->execute([$username, $nama_lengkap, password_hash($password, PASSWORD_DEFAULT), $role]);
        
        if ($result) {
            header('Location: users.php?success=created');
        } else {
            header('Location: users.php?error=Gagal membuat akun');
        }
    } catch (PDOException $e) {
        header('Location: users.php?error=Error: ' . $e->getMessage());
    }
} else {
    header('Location: users.php');
}
exit;
?>
