<?php
// Test script for authentication system
// Run this file to verify the authentication system is working

require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'config/rbac.php';
require_once 'config/security.php';

echo "<h1>Mutalex Academy LMS - Authentication System Test</h1>";
echo "<style>body { font-family: Arial, sans-serif; margin: 20px; } .success { color: green; } .error { color: red; } .info { color: blue; }</style>";

// Test database connection
try {
    $pdo = getDB();
    echo "<p class='success'>✓ Database connection successful</p>";
} catch (Exception $e) {
    echo "<p class='error'>✗ Database connection failed: " . $e->getMessage() . "</p>";
    exit;
}

// Test user table structure
try {
    $stmt = $pdo->query("DESCRIBE users");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $requiredColumns = ['id', 'username', 'email', 'password', 'role', 'email_verified'];

    $missingColumns = array_diff($requiredColumns, $columns);
    if (empty($missingColumns)) {
        echo "<p class='success'>✓ Users table structure is correct</p>";
    } else {
        echo "<p class='error'>✗ Missing columns in users table: " . implode(', ', $missingColumns) . "</p>";
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ Error checking users table: " . $e->getMessage() . "</p>";
}

// Test default admin user
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute(['admin']);
    $admin = $stmt->fetch();

    if ($admin) {
        echo "<p class='success'>✓ Default admin user exists</p>";
        echo "<p class='info'>Admin role: " . $admin['role'] . "</p>";
        echo "<p class='info'>Email verified: " . ($admin['email_verified'] ? 'Yes' : 'No') . "</p>";
    } else {
        echo "<p class='error'>✗ Default admin user not found</p>";
    }
} catch (Exception $e) {
    echo "<p class='error'>✗ Error checking admin user: " . $e->getMessage() . "</p>";
}

// Test RBAC functions
echo "<h2>Testing RBAC Functions</h2>";

// Test role definitions
$roles = getAllRoles();
echo "<p class='info'>Available roles: " . implode(', ', $roles) . "</p>";

// Test permission checking (without logged in user)
echo "<p class='info'>Testing permissions (not logged in):</p>";
echo "<p>" . (hasPermission('view_posts') ? '✓' : '✗') . " Guest can view posts</p>";
echo "<p>" . (hasPermission('manage_users') ? '✗' : '✓') . " Guest cannot manage users</p>";

// Test password validation
echo "<h2>Testing Password Validation</h2>";
$testPasswords = [
    'weak' => false,
    'Stronger1' => true,
    'verylongpasswordwithnumb3rs' => true,
    'Short1' => false
];

foreach ($testPasswords as $password => $expected) {
    $result = validatePassword($password);
    $status = ($result === $expected) ? 'success' : 'error';
    echo "<p class='$status'>" . (($result === $expected) ? '✓' : '✗') . " Password '$password' validation: " . ($result ? 'valid' : 'invalid') . "</p>";
}

// Test CSRF token generation
echo "<h2>Testing Security Functions</h2>";
$token1 = generateCSRFToken();
$token2 = generateCSRFToken();
echo "<p class='success'>✓ CSRF token generated: " . substr($token1, 0, 20) . "...</p>";
echo "<p class='" . (validateCSRFToken($token1) ? 'success' : 'error') . "'>" . (validateCSRFToken($token1) ? '✓' : '✗') . " CSRF token validation works</p>";

// Test secure token generation
$secureToken = generateSecureToken(16);
echo "<p class='success'>✓ Secure token generated: " . $secureToken . "</p>";

// Test file paths
echo "<h2>Testing File Structure</h2>";
$requiredFiles = [
    'config/auth.php',
    'config/rbac.php',
    'config/security.php',
    'includes/middleware.php',
    'login.php',
    'register.php',
    'forgot-password.php',
    'reset-password.php',
    'verify-email.php'
];

foreach ($requiredFiles as $file) {
    echo "<p class='" . (file_exists($file) ? 'success' : 'error') . "'>" . (file_exists($file) ? '✓' : '✗') . " $file exists</p>";
}

$requiredDirs = [
    'admin',
    'instructor',
    'student',
    'logs',
    'uploads'
];

foreach ($requiredDirs as $dir) {
    echo "<p class='" . (is_dir($dir) ? 'success' : 'error') . "'>" . (is_dir($dir) ? '✓' : '✗') . " Directory $dir exists</p>";
}

echo "<h2>Test Summary</h2>";
echo "<p class='info'>Authentication system test completed. Check the results above.</p>";
echo "<p class='info'>To test login functionality:</p>";
echo "<ul>";
echo "<li>Visit <a href='login.php'>login.php</a> and try logging in with admin/admin123</li>";
echo "<li>Visit <a href='register.php'>register.php</a> to test user registration</li>";
echo "<li>Test password reset at <a href='forgot-password.php'>forgot-password.php</a></li>";
echo "</ul>";
?>