<?php

require_once __DIR__ . '/src/db.php';

try {
    $pdo = getPDO();
    
    echo "Checking activity log table...\n";
    
    // Check if table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'workspace_activity_log'");
    $table = $stmt->fetch();
    
    if (!$table) {
        echo "Table does not exist. Creating...\n";
        
        // Create the table
        $pdo->exec('
            CREATE TABLE workspace_activity_log (
                id INT AUTO_INCREMENT PRIMARY KEY,
                company_id INT NOT NULL,
                user_id INT NULL,
                action VARCHAR(100) NOT NULL,
                entity_type VARCHAR(50) NULL,
                entity_id INT NULL,
                entity_name VARCHAR(255) NULL,
                old_values JSON NULL,
                new_values JSON NULL,
                ip_address VARCHAR(45) NULL,
                user_agent TEXT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_company (company_id),
                INDEX idx_user (user_id),
                INDEX idx_entity (entity_type, entity_id),
                INDEX idx_created (created_at)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ');
        
        echo "Table created successfully!\n";
    } else {
        echo "Table exists.\n";
        
        // Check count
        $stmt = $pdo->query('SELECT COUNT(*) as count FROM workspace_activity_log');
        $count = $stmt->fetch();
        echo "Total activities: " . $count['count'] . "\n";
    }
    
    // Get some sample data if exists
    $stmt = $pdo->query('SELECT * FROM workspace_activity_log LIMIT 5');
    $activities = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($activities)) {
        echo "\nRecent activities:\n";
        foreach ($activities as $activity) {
            echo "- {$activity['action']} by user {$activity['user_id']} at {$activity['created_at']}\n";
        }
    } else {
        echo "\nNo activities found. The table is empty.\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
