<?php
// Quick fix for missing last_login column
include '../includes/db.php';

try {
    echo "Checking and fixing database structure...\n\n";
    
    // Check if last_login column exists
    $columns = $pdo->query("DESCRIBE users")->fetchAll(PDO::FETCH_COLUMN);
    
    if (!in_array('last_login', $columns)) {
        echo "Adding missing last_login column...\n";
        $pdo->exec("ALTER TABLE users ADD COLUMN last_login TIMESTAMP NULL");
        echo "✓ Added last_login column to users table\n";
    } else {
        echo "✓ last_login column already exists\n";
    }
    
    // Check if user_profiles table exists
    try {
        $pdo->query("SELECT 1 FROM user_profiles LIMIT 1");
        echo "✓ user_profiles table exists\n";
    } catch (Exception $e) {
        echo "Creating user_profiles table...\n";
        $pdo->exec("
            CREATE TABLE user_profiles (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                full_name VARCHAR(255) NOT NULL,
                email VARCHAR(255) UNIQUE,
                phone VARCHAR(50),
                address TEXT,
                emergency_contact VARCHAR(255),
                emergency_phone VARCHAR(50),
                notes TEXT,
                avatar VARCHAR(255),
                is_active TINYINT(1) DEFAULT 1,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            )
        ");
        echo "✓ Created user_profiles table\n";
    }
    
    // Check if user_groups table exists
    try {
        $pdo->query("SELECT 1 FROM user_groups LIMIT 1");
        echo "✓ user_groups table exists\n";
    } catch (Exception $e) {
        echo "Creating user_groups table...\n";
        $pdo->exec("
            CREATE TABLE user_groups (
                id INT AUTO_INCREMENT PRIMARY KEY,
                name VARCHAR(100) NOT NULL UNIQUE,
                description TEXT,
                color VARCHAR(7) DEFAULT '#007bff',
                is_active TINYINT(1) DEFAULT 1,
                created_by INT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
            )
        ");
        echo "✓ Created user_groups table\n";
    }
    
    // Create default profiles for existing users without profiles
    echo "\nCreating profiles for existing users...\n";
    $users_without_profiles = $pdo->query("
        SELECT u.id, u.username, u.role 
        FROM users u 
        LEFT JOIN user_profiles p ON u.id = p.user_id 
        WHERE p.id IS NULL
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($users_without_profiles as $user) {
        $full_name = ucwords(str_replace('_', ' ', $user['username']));
        $email = $user['username'] . '@example.com';
        
        $stmt = $pdo->prepare("
            INSERT INTO user_profiles (user_id, full_name, email, created_at) 
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->execute([$user['id'], $full_name, $email]);
        echo "✓ Created profile for: {$user['username']}\n";
    }
    
    echo "\n🎉 Database structure fixed successfully!\n";
    echo "You can now access the user management system.\n";
    
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>
