<?php
// Koneksi ke database
$conn = new mysqli("localhost", "root", "", "ptpn_produksi");

// Cek koneksi
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Ambil data dari form
$name       = $_POST['name'];
$username   = $_POST['username'];
$password   = password_hash($_POST['password'], PASSWORD_DEFAULT);
$jabatan    = $_POST['jabatan'];
$role       = $_POST['role'];
$status     = $_POST['status'];
$created_at = date('Y-m-d H:i:s'); // Timestamp otomatis

// Cek apakah username sudah ada
$cek = $conn->query("SELECT * FROM users WHERE username = '$username'");
if ($cek->num_rows > 0) {
    header("Location: data_user.php?error=username");
    exit();
}

// Simpan ke database
$sql = "INSERT INTO users (name, username, password, jabatan, role, status, created_at)
        VALUES ('$name', '$username', '$password', '$jabatan', '$role', '$status', '$created_at')";

if ($conn->query($sql) === TRUE) {
    header("Location: data_user.php?status=sukses");
    exit();
} else {
    echo "Gagal menambahkan data: " . $conn->error;
}

$conn->close();
?>
