<?php
require_once __DIR__ . '/../../core/bootstrap.php';

$deviceNumber = filterRequest("deviceNumber");
$name = filterRequest("name");
$password = filterRequest("password");
$role = filterRequest("role") ?? 'admin';

if (empty($name) || empty($password)) {
    jsonError("Name and password are required.");
    exit;
}

try {
    $con = Database::get('main');
    
    // Hash the password for security
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $sql = "INSERT INTO `adminUser`(`id`, `device_number`, `name`, `password`, `role`) VALUES (
      UUID(),
      :deviceNumber,
      :name,
      :password,
      :role
    )";

    $stmt = $con->prepare($sql);
    $stmt->execute([
        ':deviceNumber' => $deviceNumber,
        ':name' => $name,
        ':password' => $hashedPassword,
        ':role' => $role
    ]);

    if ($stmt->rowCount() > 0) {
      jsonSuccess("Admin user data saved successfully");
    } else {
      jsonError("Failed to save admin user data");
    }
} catch (Exception $e) {
    error_log("[Admin Add Error] " . $e->getMessage());
    jsonError("Database error: " . $e->getMessage());
}
?>

