<?php
/**
 * Complete Migration Script - Migrate all files to company-specific structure
 */

require_once __DIR__ . '/src/db.php';
require_once __DIR__ . '/src/Auth/AuthManager.php';
require_once __DIR__ . '/src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/src/FileManager.php';

echo "🚀 Starting complete file migration to multi-tenant structure...\n\n";

try {
    // Get all companies
    $pdo = getPDO();
    $stmt = $pdo->query("SELECT id, name, subdomain FROM companies");
    $companies = $stmt->fetchAll();
    
    echo "Found " . count($companies) . " companies to migrate\n";
    
    foreach ($companies as $company) {
        echo "\n📁 Migrating files for company: {$company['name']} (ID: {$company['id']})\n";
        
        // Ensure company directories exist
        FileManager::ensureCompanyDirectories($company['id']);
        
        // Migrate existing files from old storage
        FileManager::migrateExistingFiles($company['id']);
        
        // Update database records to use new file paths
        migrateFilePaths($company['id']);
        
        echo "✅ Company {$company['name']} migration completed\n";
    }
    
    echo "\n🎉 File migration completed successfully!\n";
    echo "\n📊 Migration Summary:\n";
    echo "- All files moved to company-specific directories\n";
    echo "- Database paths updated to new structure\n";
    echo "- Company directories created for all companies\n";
    echo "- Legacy files preserved in original locations\n";
    
} catch (Exception $e) {
    echo "❌ Migration failed: " . $e->getMessage() . "\n";
    exit(1);
}

function migrateFilePaths(int $companyId): void
{
    global $pdo;
    
    echo "  🔄 Updating file paths in database...\n";
    
    // Update proposals PDF paths
    $stmt = $pdo->prepare("SELECT id, pdf_path FROM proposals WHERE company_id = ? AND pdf_path IS NOT NULL AND pdf_path != ''");
    $stmt->execute([$companyId]);
    $proposals = $stmt->fetchAll();
    
    foreach ($proposals as $proposal) {
        // Check if path is already in new format
        if (strpos($proposal['pdf_path'], '/storage/companies/') === 0) {
            continue; // Already migrated
        }
        
        // Extract filename from old path
        $filename = basename($proposal['pdf_path']);
        
        // Create new path
        $newPath = "/storage/companies/{$companyId}/pdfs/{$filename}";
        
        // Update database
        $updateStmt = $pdo->prepare("UPDATE proposals SET pdf_path = ? WHERE id = ?");
        $updateStmt->execute([$newPath, $proposal['id']]);
        
        echo "    Updated proposal {$proposal['id']}: {$proposal['pdf_path']} → {$newPath}\n";
    }
    
    // Update invoice PDF paths (if they exist)
    $stmt = $pdo->prepare("SELECT id, pdf_path FROM invoices WHERE company_id = ? AND pdf_path IS NOT NULL AND pdf_path != ''");
    $stmt->execute([$companyId]);
    $invoices = $stmt->fetchAll();
    
    foreach ($invoices as $invoice) {
        if (strpos($invoice['pdf_path'], '/storage/companies/') === 0) {
            continue;
        }
        
        $filename = basename($invoice['pdf_path']);
        $newPath = "/storage/companies/{$companyId}/pdfs/{$filename}";
        
        $updateStmt = $pdo->prepare("UPDATE invoices SET pdf_path = ? WHERE id = ?");
        $updateStmt->execute([$newPath, $invoice['id']]);
        
        echo "    Updated invoice {$invoice['id']}: {$invoice['pdf_path']} → {$newPath}\n";
    }
    
    // Update contract PDF paths
    $stmt = $pdo->prepare("SELECT id, pdf_path FROM contracts WHERE company_id = ? AND pdf_path IS NOT NULL AND pdf_path != ''");
    $stmt->execute([$companyId]);
    $contracts = $stmt->fetchAll();
    
    foreach ($contracts as $contract) {
        if (strpos($contract['pdf_path'], '/storage/companies/') === 0) {
            continue;
        }
        
        $filename = basename($contract['pdf_path']);
        $newPath = "/storage/companies/{$companyId}/contracts/{$filename}";
        
        $updateStmt = $pdo->prepare("UPDATE contracts SET pdf_path = ? WHERE id = ?");
        $updateStmt->execute([$newPath, $contract['id']]);
        
        echo "    Updated contract {$contract['id']}: {$contract['pdf_path']} → {$newPath}\n";
    }
    
    // Update logo paths in invoice settings
    $stmt = $pdo->prepare("SELECT id, logo_path FROM invoice_settings WHERE company_id = ? AND logo_path IS NOT NULL AND logo_path != ''");
    $stmt->execute([$companyId]);
    $settings = $stmt->fetchAll();
    
    foreach ($settings as $setting) {
        if (strpos($setting['logo_path'], '/storage/companies/') === 0) {
            continue;
        }
        
        $filename = basename($setting['logo_path']);
        $newPath = "/storage/companies/{$companyId}/logos/{$filename}";
        
        $updateStmt = $pdo->prepare("UPDATE invoice_settings SET logo_path = ? WHERE id = ?");
        $updateStmt->execute([$newPath, $setting['id']]);
        
        echo "    Updated logo {$setting['id']}: {$setting['logo_path']} → {$newPath}\n";
    }
    
    // Update signature paths
    $stmt = $pdo->prepare("SELECT id, signature_path FROM invoice_settings WHERE company_id = ? AND signature_path IS NOT NULL AND signature_path != ''");
    $stmt->execute([$companyId]);
    $settings = $stmt->fetchAll();
    
    foreach ($settings as $setting) {
        if (strpos($setting['signature_path'], '/storage/companies/') === 0) {
            continue;
        }
        
        $filename = basename($setting['signature_path']);
        $newPath = "/storage/companies/{$companyId}/signatures/{$filename}";
        
        $updateStmt = $pdo->prepare("UPDATE invoice_settings SET signature_path = ? WHERE id = ?");
        $updateStmt->execute([$newPath, $setting['id']]);
        
        echo "    Updated signature {$setting['id']}: {$setting['signature_path']} → {$newPath}\n";
    }
    
    echo "  ✅ File paths updated in database\n";
}

echo "\n🔧 To complete the migration:\n";
echo "1. Run: php migrate_files.php\n";
echo "2. Update your web server configuration to handle /storage/ routes\n";
echo "3. Test file access through the new storage.php handler\n";
echo "4. Remove old storage directories after verification\n";
