<?php
require_once 'db/config.php';

// Test credentials
$test_username = 'testuser_debug';
$test_email = 'testuser_debug@example.com';
$test_password = 'password';

$errors = [];

// 1. Clean up any previous test user
$pdo = db();
$stmt = $pdo->prepare('DELETE FROM users WHERE email = ?');
$stmt->execute([$test_email]);
echo "Cleaned up previous test user.\n";

// 2. Register a new user
$hashed_password = password_hash($test_password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare('INSERT INTO users (username, email, password) VALUES (?, ?, ?)');
if ($stmt->execute([$test_username, $test_email, $hashed_password])) {
    echo "User registered successfully.\n";
} else {
    $errors[] = 'Failed to register user.';
    print_r($stmt->errorInfo());
}

// 3. Fetch the user from the database
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$test_email]);
$user = $stmt->fetch();

if ($user) {
    echo "User fetched successfully.\n";
    echo "Stored hash: " . $user['password'] . "\n";
} else {
    $errors[] = 'Failed to fetch user after registration.';
}

// 4. Verify the password
if ($user && password_verify($test_password, $user['password'])) {
    echo "Password verification successful.\n";
} else {
    $errors[] = 'Password verification failed.';
}

// 5. Final result
if (empty($errors)) {
    echo "\nSUCCESS: Registration and login test passed.\n";
} else {
    echo "\nERROR: Test failed.\n";
    foreach ($errors as $error) {
        echo "- $error\n";
    }
}

// Clean up the created user
$stmt = $pdo->prepare('DELETE FROM users WHERE email = ?');
$stmt->execute([$test_email]);
echo "Cleaned up the created test user.\n";

