<?php
// Fix company users migration
require_once 'config/config.php';

$database = new Database();
$db = $database->getConnection();

try {
    // Check what companies exist
    $stmt = $db->query("SELECT * FROM companies");
    $companies = $stmt->fetchAll();
    
    echo "Found " . count($companies) . " companies:\n";
    foreach ($companies as $company) {
        echo "- Company ID: {$company['id']}, Name: {$company['name']}\n";
        if (isset($company['email'])) {
            echo "  Email: {$company['email']}\n";
        }
    }
    
    // Check existing company users
    $stmt = $db->query("SELECT * FROM company_users");
    $users = $stmt->fetchAll();
    
    echo "\nFound " . count($users) . " company users:\n";
    foreach ($users as $user) {
        echo "- User: {$user['name']} ({$user['email']}) - Company ID: {$user['company_id']}\n";
    }
    
    // If no users exist, create them from company data
    if (count($users) === 0 && count($companies) > 0) {
        echo "\nNo company users found. Creating users from company data...\n";
        
        foreach ($companies as $company) {
            if (isset($company['email']) && !empty($company['email'])) {
                // Create primary user from company email/password
                $stmt = $db->prepare("
                    INSERT INTO company_users (company_id, name, email, password, is_primary, status) 
                    VALUES (?, ?, ?, ?, 1, 'active')
                ");
                $stmt->execute([
                    $company['id'],
                    'Primary User', // Default name
                    $company['email'],
                    $company['password'] // Already hashed
                ]);
                
                echo "Created primary user for {$company['name']}\n";
            }
        }
    }
    
    // Check again
    $stmt = $db->query("SELECT * FROM company_users");
    $users = $stmt->fetchAll();
    
    echo "\nAfter migration - Found " . count($users) . " company users:\n";
    foreach ($users as $user) {
        echo "- User: {$user['name']} ({$user['email']}) - Company ID: {$user['company_id']}\n";
    }
    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>