<?php
/**
 * Storage Migration Script
 * Migrates existing storage structure to company-specific folders
 */

echo "🗂️  KEELANCE SAAS - STORAGE MIGRATION\n";
echo "===================================\n\n";

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

// Get all companies from database
$pdo = getPDO();
$stmt = $pdo->query('SELECT id, name FROM companies ORDER BY id');
$companies = $stmt->fetchAll();

if (empty($companies)) {
    echo "❌ No companies found in database. Please run final_mysql_setup.php first.\n";
    exit(1);
}

echo "Found " . count($companies) . " companies in database\n\n";

// Get current storage structure
$storageBase = __DIR__ . '/storage';
$existingDirs = ['contracts', 'pdfs', 'receipts'];

echo "📁 CURRENT STORAGE STRUCTURE\n";
echo "===========================\n";

foreach ($existingDirs as $dir) {
    $dirPath = $storageBase . '/' . $dir;
    if (is_dir($dirPath)) {
        $files = scandir($dirPath);
        $fileCount = count(array_diff($files, ['.', '..']));
        echo "✅ {$dir}: {$fileCount} files\n";
    } else {
        echo "⚠️  {$dir}: directory not found\n";
    }
}

echo "\n🔄 MIGRATION PROCESS\n";
echo "====================\n";

// Create company-specific directories and migrate files
foreach ($companies as $company) {
    $companyId = $company['id'];
    $companyName = $company['name'];
    
    echo "\n🏢 Processing Company: {$companyName} (ID: {$companyId})\n";
    
    // Ensure company directories exist
    FileManager::ensureCompanyDirectories($companyId);
    
    // Migrate files from each directory
    foreach ($existingDirs as $dir) {
        $sourceDir = $storageBase . '/' . $dir;
        $targetDir = FileManager::getCompanyStoragePath($companyId, $dir);
        
        if (is_dir($sourceDir)) {
            $files = scandir($sourceDir);
            $migratedCount = 0;
            
            foreach (array_diff($files, ['.', '..']) as $file) {
                $sourceFile = $sourceDir . '/' . $file;
                $targetFile = $targetDir . '/' . $file;
                
                if (is_file($sourceFile)) {
                    // Check if file already exists in target
                    if (file_exists($targetFile)) {
                        // Add timestamp to avoid conflicts
                        $timestamp = date('Y-m-d_H-i-s');
                        $targetFile = $targetDir . '/' . pathinfo($file, PATHINFO_FILENAME) . '_migrated_' . $timestamp . '.' . pathinfo($file, PATHINFO_EXTENSION);
                    }
                    
                    if (copy($sourceFile, $targetFile)) {
                        $migratedCount++;
                        echo "  ✅ Migrated: {$file}\n";
                    } else {
                        echo "  ❌ Failed to migrate: {$file}\n";
                    }
                }
            }
            
            if ($migratedCount > 0) {
                echo "  📊 {$dir}: {$migratedCount} files migrated\n";
            }
        } else {
            echo "  ⚠️  {$dir}: source directory not found\n";
        }
    }
}

echo "\n🔗 UPDATING DATABASE PATHS\n";
echo "==========================\n";

// Update database records to use new storage paths
$updates = [
    'proposals' => 'pdf_path',
    'invoices' => 'pdf_path', 
    'contracts' => 'pdf_path'
];

foreach ($updates as $table => $field) {
    echo "\n📝 Updating {$table}.{$field}...\n";
    
    // Get all records with old paths
    $stmt = $pdo->query("SELECT id, company_id, {$field} FROM {$table} WHERE {$field} IS NOT NULL AND {$field} != ''");
    $records = $stmt->fetchAll();
    
    $updatedCount = 0;
    foreach ($records as $record) {
        $recordId = $record['id'];
        $recordCompanyId = $record['company_id'];
        $oldPath = $record[$field];
        
        // Extract filename from old path
        $filename = basename($oldPath);
        
        // Determine the subfolder based on table
        $subfolder = match($table) {
            'proposals' => 'proposals',
            'invoices' => 'pdfs',
            'contracts' => 'contracts',
            default => 'pdfs'
        };
        
        // Create new path
        $newPath = '/storage/companies/' . $recordCompanyId . '/' . $subfolder . '/' . $filename;
        
        // Update database
        $updateStmt = $pdo->prepare("UPDATE {$table} SET {$field} = ? WHERE id = ?");
        if ($updateStmt->execute([$newPath, $recordId])) {
            $updatedCount++;
            echo "  ✅ Record {$recordId}: {$oldPath} → {$newPath}\n";
        } else {
            echo "  ❌ Failed to update record {$recordId}\n";
        }
    }
    
    echo "  📊 {$table}: {$updatedCount} records updated\n";
}

echo "\n🧹 CLEANUP OPTIONS\n";
echo "==================\n";
echo "After verifying the migration is successful, you can:\n";
echo "1. Remove old storage directories: rm -rf storage/contracts storage/pdfs storage/receipts\n";
echo "2. Keep them as backup until you're confident everything works\n";
echo "3. Run this script again if you add more companies\n";

echo "\n✅ STORAGE MIGRATION COMPLETE!\n";
echo "==============================\n";
echo "✅ Company-specific directories created\n";
echo "✅ Files migrated to company folders\n";
echo "✅ Database paths updated\n";
echo "✅ Multi-tenant storage structure ready\n";

echo "\n🎯 NEW STORAGE STRUCTURE:\n";
echo "========================\n";
echo "storage/\n";
echo "├── companies/\n";
echo "│   ├── 1/ (Company ID 1)\n";
echo "│   │   ├── contracts/\n";
echo "│   │   ├── pdfs/\n";
echo "│   │   ├── receipts/\n";
echo "│   │   ├── proposals/\n";
echo "│   │   ├── invoices/\n";
echo "│   │   ├── logos/\n";
echo "│   │   ├── signatures/\n";
echo "│   │   └── temp/\n";
echo "│   ├── 2/ (Company ID 2)\n";
echo "│   └── ... (other companies)\n";
echo "└── ... (other storage directories)\n";

echo "\n🚀 NEXT STEPS:\n";
echo "==============\n";
echo "1. Test the platform to ensure all files download correctly\n";
echo "2. Verify PDF generation works for proposals, invoices, and contracts\n";
echo "3. Check that file uploads work properly\n";
echo "4. Remove old storage directories when confident\n";
echo "5. Update any remaining hardcoded paths in custom code\n";

echo "\n🎉 YOUR MULTI-TENANT STORAGE IS READY!\n";
