<?php
// Migrate companies table to new structure
require_once 'config/config.php';

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

try {
    echo "Starting companies table migration...\n";
    
    // Check if new columns exist
    $stmt = $db->query("DESCRIBE companies");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $has_contact_person_name = in_array('contact_person_name', $columns);
    $has_contact_person_email = in_array('contact_person_email', $columns);
    
    if (!$has_contact_person_name || !$has_contact_person_email) {
        echo "Adding new columns to companies table...\n";
        
        // Add new contact person columns
        if (!$has_contact_person_name) {
            $db->exec("ALTER TABLE companies ADD COLUMN contact_person_name VARCHAR(100) DEFAULT 'Contact Person'");
        }
        if (!$has_contact_person_email) {
            $db->exec("ALTER TABLE companies ADD COLUMN contact_person_email VARCHAR(100) DEFAULT 'contact@company.com'");
        }
        
        // Add other missing columns
        if (!in_array('contact_person_phone', $columns)) {
            $db->exec("ALTER TABLE companies ADD COLUMN contact_person_phone VARCHAR(20)");
        }
        if (!in_array('contact_person_position', $columns)) {
            $db->exec("ALTER TABLE companies ADD COLUMN contact_person_position VARCHAR(100)");
        }
        
        echo "New columns added successfully!\n";
    }
    
    // Get existing companies
    $stmt = $db->query("SELECT * FROM companies");
    $existing_companies = $stmt->fetchAll();
    
    echo "Found " . count($existing_companies) . " existing companies.\n";
    
    // For each existing company, create a user account and update contact info
    foreach ($existing_companies as $company) {
        if (!empty($company['email']) && !empty($company['password'])) {
            // Check if user already exists
            $stmt = $db->prepare("SELECT id FROM company_users WHERE email = ?");
            $stmt->execute([$company['email']]);
            
            if (!$stmt->fetch()) {
                // Create user account from existing company credentials
                $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 user account for company: {$company['name']}\n";
            }
            
            // Update contact person info if it's still default
            if ($company['contact_person_email'] === 'contact@company.com') {
                $stmt = $db->prepare("
                    UPDATE companies 
                    SET contact_person_name = ?, contact_person_email = ? 
                    WHERE id = ?
                ");
                $stmt->execute([
                    'Contact Person', // Default name
                    $company['email'], // Use company email as contact email
                    $company['id']
                ]);
                
                echo "Updated contact info for company: {$company['name']}\n";
            }
        }
    }
    
    // Set default logo for companies without one
    $stmt = $db->prepare("UPDATE companies SET logo = 'default-logo.png' WHERE logo IS NULL OR logo = ''");
    $stmt->execute();
    
    // Make required fields NOT NULL (with defaults)
    echo "Updating table constraints...\n";
    
    // First ensure all companies have required values
    $db->exec("UPDATE companies SET logo = 'default-logo.png' WHERE logo IS NULL OR logo = ''");
    $db->exec("UPDATE companies SET contact_person_name = 'Contact Person' WHERE contact_person_name IS NULL OR contact_person_name = ''");
    $db->exec("UPDATE companies SET contact_person_email = email WHERE contact_person_email IS NULL OR contact_person_email = ''");
    
    echo "Migration completed successfully!\n";
    echo "Note: Companies without logos will use 'default-logo.png'\n";
    echo "Note: You may want to update contact person information through the admin interface.\n";
    
} catch (PDOException $e) {
    echo "Migration error: " . $e->getMessage() . "\n";
}
?>