<?php
// Include the database connection file
require_once 'includes/dbconn.php';

/**
 * Creates a PBKDF2 password hash
 * 
 * @param string $password The password to hash
 * @param string $salt Optional salt (will be generated if not provided)
 * @param int $iterations Number of iterations (default: 10000)
 * @param int $keyLength Length of the derived key (default: 32)
 * @return array Array containing the hash and salt
 */
function hash_pbkdf2_password($password, $salt = null, $iterations = 10000, $keyLength = 32) {
    // Generate a random salt if not provided
    if ($salt === null) {
        $salt = bin2hex(random_bytes(16)); // 32 character hex string
    }
    
    // Create the hash using PBKDF2 with SHA256
    $hash = hash_pbkdf2(
        "sha256",
        $password,
        $salt,
        $iterations,
        $keyLength * 2, // *2 because hash_pbkdf2 returns hex
        true // Set to true to get raw binary data
    );
    
    // Convert binary hash to hex for storage
    $hashHex = bin2hex($hash);
    
    return [
        'hash' => $hashHex,
        'salt' => $salt,
        'iterations' => $iterations,
        'keyLength' => $keyLength
    ];
}

/**
 * Add a new user to the database
 */
function add_user_to_database($username, $password) {
    global $pdo; // Using the PDO connection from dbconn.php
    
    try {
        // Hash the password
        $hashData = hash_pbkdf2_password($password);
        
        // Prepare SQL statement with correct table name
        $stmt = $pdo->prepare("INSERT INTO admin_users (username, pass_hash, salt, iterations, key_length, created_at) 
                              VALUES (:username, :pass_hash, :salt, :iterations, :key_length, NOW())");
        
        // Bind parameters and execute
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':pass_hash', $hashData['hash']);
        $stmt->bindParam(':salt', $hashData['salt']);
        $stmt->bindParam(':iterations', $hashData['iterations'], PDO::PARAM_INT);
        $stmt->bindParam(':key_length', $hashData['keyLength'], PDO::PARAM_INT);
        $stmt->execute();
        
        return true;
    } catch (PDOException $e) {
        // Silently log error without displaying it
        error_log("Database error: " . $e->getMessage());
        return false;
    }
}

// Set username and password
$username = 'admin2';
$password = 'pass2';

// Add user to database
if (add_user_to_database($username, $password)) {
    echo "Admin user successfully added!";
} else {
    echo "Error adding admin user.";
}
?>