<?php
/**
 * Test Login Script
 * This will attempt to log in and show detailed results
 */

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/database.php';
require_once dirname(__DIR__) . '/config/auth.php';

echo "<h1>Test Login</h1>";

if ($_POST) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    echo "<h2>Testing login for: $username</h2>";
    
    // Direct database check
    $user = db_fetch_one("SELECT * FROM users WHERE username = ? OR email = ?", [$username, $username]);
    
    if ($user) {
        echo "<p style='color: green'>✓ User found in database</p>";
        echo "<pre>";
        echo "User ID: " . $user['user_id'] . "\n";
        echo "Username: " . $user['username'] . "\n";
        echo "Email: " . $user['email'] . "\n";
        echo "Active: " . ($user['is_active'] ? 'Yes' : 'No') . "\n";
        echo "Password Hash: " . $user['password_hash'] . "\n";
        echo "</pre>";
        
        // Test password
        if (password_verify($password, $user['password_hash'])) {
            echo "<p style='color: green'>✓ Password correct!</p>";
        } else {
            echo "<p style='color: red'>✗ Password incorrect</p>";
            
            // Generate new hash
            $new_hash = password_hash($password, PASSWORD_DEFAULT);
            echo "<p>New hash for this password: <code>$new_hash</code></p>";
        }
    } else {
        echo "<p style='color: red'>✗ User not found</p>";
    }
    
    // Test through auth function
    echo "<h3>Testing through auth function:</h3>";
    $result = authenticate_user($username, $password, false);
    
    if (is_array($result) && isset($result['error'])) {
        echo "<p style='color: red'>Auth error: " . $result['error'] . "</p>";
    } elseif ($result) {
        echo "<p style='color: green'>✓ Auth function succeeded!</p>";
        echo "<pre>";
        print_r($result);
        echo "</pre>";
    } else {
        echo "<p style='color: red'>✗ Auth function failed</p>";
    }
    
} else {
    ?>
    <form method="POST">
        <div>
            <label>Username:</label>
            <input type="text" name="username" value="admin">
        </div>
        <div>
            <label>Password:</label>
            <input type="password" name="password" value="Admin@123">
        </div>
        <button type="submit">Test Login</button>
    </form>
    <?php
}