<?php
/**
 * Check and create login_attempts table if it doesn't exist
 */

require_once __DIR__ . '/config/database.php';

try {
    // Check if login_attempts table exists
    $result = $pdo->query("SHOW TABLES LIKE 'login_attempts'");
    $exists = $result->rowCount() > 0;

    if (!$exists) {
        echo "Creating login_attempts table...\n";
        
        // Create the login_attempts table
        $pdo->exec("
            CREATE TABLE login_attempts (
                id BIGINT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(50),
                ip_address VARCHAR(45) NOT NULL,
                user_agent VARCHAR(255),
                attempt_status ENUM('success', 'failed') NOT NULL,
                failure_reason VARCHAR(255),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_ip_time (ip_address, created_at),
                INDEX idx_username (username)
            )
        ");
        
        echo "✅ login_attempts table created successfully!\n";
    } else {
        echo "✅ login_attempts table already exists.\n";
    }
    
    // Test inserting a sample record to verify everything works
    $stmt = $pdo->prepare("
        INSERT INTO login_attempts (username, ip_address, user_agent, attempt_status) 
        VALUES (?, ?, ?, 'success')
    ");
    $stmt->execute(['test_user', $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]);
    
    echo "✅ Test record inserted successfully!\n";
    echo "✅ All checks passed! The login_attempts.php page should now work correctly.\n";
    
} catch (PDOException $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>