<?php
include 'config/koneksi.php';

function validateFullname($name) {
    return preg_match("/^[a-zA-Z\s'-]+$/", $name);
}

function validateUsername($username) {
    return preg_match('/^[a-zA-Z0-9]+$/', $username);
}

function validatePassword($password) {
    if (strlen($password) < 6) {
        return false;
    }
    if (!preg_match('/[A-Za-z]/', $password) || !preg_match('/\d/', $password)) {
        return false;
    }
    return true;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = trim($_POST['ID']);
    $username = trim($_POST['username']);
    $password = trim($_POST['pasword']);
    $role_id = $_POST['role'];
    $nama_lengkap = trim($_POST['nama']);

    // Validasi ID
    if (!ctype_digit($user_id)) {
        die("ID harus berupa angka.");
    }

    // Validasi username alphanumeric
    if (!validateUsername($username)) {
        die("Username hanya boleh huruf dan angka.");
    }

    // Validasi nama lengkap seperti register
    if (!validateFullname($nama_lengkap)) {
        die("Nama hanya boleh huruf");
    }

    // Validasi password
    if (!validatePassword($password)) {
        die("Password harus minimal 6 karakter dan mengandung huruf dan angka.");
    }

    // Jangan lupa untuk meng-hash password sebelum simpan
    $hashed_password = md5($password); // disarankan pakai password_hash()

    mysqli_select_db($conn, "users");
    
    $sql = "INSERT INTO users (ID, username, pasword, role, nama) VALUES(?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("issis", $user_id, $username, $hashed_password, $role_id, $nama_lengkap);

    if ($stmt->execute()) {
        header("Location: mainAdmin.php");
        exit();
    } else {
        echo "Gagal tambah: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();

} else {
    header("Location: Admin.php");
    exit();
}
?>
