<?php
// example-usage.php - Beispiel zur Verwendung von Doctrine

require_once 'bootstrap.php';

use Entity\User;

// Beispiel 1: Neuen User erstellen
function createUser($entityManager, $username, $email, $password)
{
    $user = new User();
    $user->setUsername($username);
    $user->setEmail($email);
    $user->setPassword(password_hash($password, PASSWORD_DEFAULT));

    $entityManager->persist($user);
    $entityManager->flush();

    echo "User created with ID: " . $user->getId() . "\n";
    return $user;
}

// Beispiel 2: User suchen
function findUserById($entityManager, $id)
{
    $user = $entityManager->find(User::class, $id);

    if ($user) {
        echo "Found user: " . $user->getUsername() . " (" . $user->getEmail() . ")\n";
    } else {
        echo "User not found\n";
    }

    return $user;
}

// Beispiel 3: Alle User abrufen
function getAllUsers($entityManager)
{
    $userRepository = $entityManager->getRepository(User::class);
    $users = $userRepository->findAll();

    echo "Found " . count($users) . " users:\n";
    foreach ($users as $user) {
        echo "- " . $user->getUsername() . " (" . $user->getEmail() . ")\n";
    }

    return $users;
}

// Beispiel 4: User nach Email suchen
function findUserByEmail($entityManager, $email)
{
    $userRepository = $entityManager->getRepository(User::class);
    $user = $userRepository->findOneBy(['email' => $email]);

    if ($user) {
        echo "Found user by email: " . $user->getUsername() . "\n";
    } else {
        echo "No user found with email: $email\n";
    }

    return $user;
}

// Beispiel 5: User aktualisieren
function updateUser($entityManager, $id, $newEmail)
{
    $user = $entityManager->find(User::class, $id);

    if ($user) {
        $user->setEmail($newEmail);
        $entityManager->flush();
        echo "User updated\n";
    } else {
        echo "User not found\n";
    }
}

// Beispiel 6: User löschen
function deleteUser($entityManager, $id)
{
    $user = $entityManager->find(User::class, $id);

    if ($user) {
        $entityManager->remove($user);
        $entityManager->flush();
        echo "User deleted\n";
    } else {
        echo "User not found\n";
    }
}

// Verwendungsbeispiel (auskommentiert):
// createUser($entityManager, 'johndoe', 'john@example.com', 'secret123');
// findUserById($entityManager, 1);
// getAllUsers($entityManager);
// findUserByEmail($entityManager, 'john@example.com');
// updateUser($entityManager, 1, 'newemail@example.com');
// deleteUser($entityManager, 1);
