<?php
session_start();
require_once "../config/db.php";

// Hanya superadmin yg boleh menambah user
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'superadmin') {
    header("Location: ../pages/users.php?error=unauthorized");
    exit;
}

$nama     = trim($_POST['nama'] ?? '');
$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');
$role     = trim($_POST['role'] ?? '');

if ($nama === '' || $username === '' || $password === '' || $role === '') {
    header("Location: ../pages/users.php?error=empty");
    exit;
}

// Hash password
$hashed = password_hash($password, PASSWORD_BCRYPT);

// Insert user
$stmt = $pdo->prepare("INSERT INTO users (nama, username, password, role, created_at)
                       VALUES (:nama, :username, :password, :role, NOW())");
$stmt->execute([
    ':nama'     => $nama,
    ':username' => $username,
    ':password' => $hashed,
    ':role'     => $role
]);

header("Location: ../pages/users.php?success=1");
exit;
