<?php
/**
 * Batch script to update all PHP files for multi-tenant SaaS compatibility
 */

$filesToUpdate = [
    'proposals.php',
    'invoices.php', 
    'contracts.php',
    'generate.php',
    'invoice_create.php',
    'invoice_view.php',
    'invoice_items.php',
    'invoice_settings.php',
    'contract_create.php',
    'contract_templates.php',
    'contract_modules.php',
    'contract_sign.php',
    'template_create.php',
    'templates.php',
    'modules.php',
    'settings.php',
    'upload-image.php',
    'download.php'
];

$saasHeader = "require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';

// Require authentication
AuthManager::requireAuth();

// Initialize tenant context
TenantManager::initialize();";

foreach ($filesToUpdate as $file) {
    $filePath = __DIR__ . '/public/' . $file;
    if (file_exists($filePath)) {
        echo "Updating $file...\n";
        $content = file_get_contents($filePath);
        
        // Find the first require_once statement and add SaaS headers after it
        $lines = explode("\n", $content);
        $newLines = [];
        $added = false;
        
        foreach ($lines as $line) {
            $newLines[] = $line;
            
            // Add SaaS headers after the first require_once block
            if (!$added && strpos($line, 'require_once') === 0) {
                $newLines[] = $saasHeader;
                $added = true;
            }
        }
        
        // If no require_once was found, add at the beginning
        if (!$added) {
            array_unshift($newLines, "<?php", $saasHeader);
        }
        
        file_put_contents($filePath, implode("\n", $newLines));
        echo "✓ Updated $file\n";
    } else {
        echo "✗ File not found: $file\n";
    }
}

echo "\nBatch update completed!\n";
echo "Review all files for any additional multi-tenant requirements.\n";
