<?php
/**
 * Complete Keelance SaaS Platform Final Setup
 * This script completes the entire SaaS conversion
 */

echo "🚀 KEELANCE SAAS PLATFORM - FINAL SETUP\n";
echo "========================================\n\n";

// Step 1: Run the original setup
echo "Step 1: Running initial database setup...\n";
if (file_exists(__DIR__ . '/setup.php')) {
    include __DIR__ . '/setup.php';
} else {
    echo "⚠️  setup.php not found, skipping database setup\n";
}

// Step 2: Update all PHP files for SaaS
echo "\nStep 2: Updating PHP files for multi-tenant support...\n";
if (file_exists(__DIR__ . '/update_saas_files.php')) {
    include __DIR__ . '/update_saas_files.php';
} else {
    echo "⚠️  update_saas_files.php not found, skipping file updates\n";
}

// Step 3: Migrate files to company structure
echo "\nStep 3: Migrating files to company-specific storage...\n";
if (file_exists(__DIR__ . '/migrate_files.php')) {
    include __DIR__ . '/migrate_files.php';
} else {
    echo "⚠️  migrate_files.php not found, skipping file migration\n";
}

// Step 4: Create .htaccess for storage access
echo "\nStep 4: Setting up storage access...\n";
$storageHtaccess = "
# Storage Access Handler
RewriteEngine On
RewriteRule ^storage/(.*)$ storage.php [L,QSA]

# Security headers
<Files \"*.php\">
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
</Files>

# Deny access to sensitive files
<FilesMatch \"\\.(env|log|sql)$\">
    Order allow,deny
    Deny from all
</FilesMatch>
";

file_put_contents(__DIR__ . '/public/.htaccess', $storageHtaccess);
echo "✅ Storage access configured\n";

// Step 5: Update main router
echo "\nStep 5: Updating main router...\n";
$routerContent = "<?php
/**
 * Keelance SaaS Platform Router
 */

// Enable error reporting in development
if (getenv('APP_ENV') === 'development') {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
}

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

// Handle storage requests first
if (strpos(\$_SERVER['REQUEST_URI'], '/storage/') === 0) {
    require_once __DIR__ . '/storage.php';
    exit;
}

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

// Route the request
\$requestUri = \$_SERVER['REQUEST_URI'];
\$requestUri = explode('?', \$requestUri)[0]; // Remove query string

\$routes = [
    '/' => 'login.php',
    '/login' => 'login.php',
    '/register' => 'login.php',
    '/dashboard' => 'dashboard.php',
    '/billing' => 'billing.php',
    '/logout' => 'logout.php',
    '/proposals' => 'proposals.php',
    '/invoices' => 'invoices.php',
    '/clients' => 'clients.php',
    '/contracts' => 'contracts.php',
    '/settings' => 'settings.php',
    '/profile' => 'profile.php',
    '/team' => 'team.php',
    '/generate' => 'generate.php',
    '/invoice_create' => 'invoice_create.php',
    '/invoice_view' => 'invoice_view.php',
    '/templates' => 'templates.php',
    '/modules' => 'modules.php',
    '/contract_create' => 'contract_create.php',
    '/contract_templates' => 'contract_templates.php',
    '/upload-image' => 'upload-image.php',
    '/download' => 'download.php',
];

// API routes
if (strpos(\$requestUri, '/api/') === 0) {
    \$apiPath = str_replace('/api/', '', \$requestUri);
    \$apiFile = __DIR__ . '/api/' . \$apiPath . '.php';
    
    if (file_exists(\$apiFile)) {
        require_once \$apiFile;
        exit;
    }
}

// Webhook routes
if (strpos(\$requestUri, '/webhooks/') === 0) {
    \$webhookPath = str_replace('/webhooks/', '', \$requestUri);
    \$webhookFile = __DIR__ . '/webhooks/' . \$webhookPath . '.php';
    
    if (file_exists(\$webhookFile)) {
        require_once \$webhookFile;
        exit;
    }
}

// Regular routes
if (isset(\$routes[\$requestUri])) {
    require_once \$routes[\$requestUri];
} else {
    // Try to find direct file
    \$file = __DIR__ . \$requestUri . '.php';
    if (file_exists(\$file)) {
        require_once \$file;
    } else {
        // 404
        http_response_code(404);
        echo '<h1>404 - Page Not Found</h1>';
        echo '<p>The page you requested could not be found.</p>';
    }
}
";

file_put_contents(__DIR__ . '/public/index.php', $routerContent);
echo "✅ Main router updated\n";

// Step 6: Create missing pages
echo "\nStep 6: Creating missing SaaS pages...\n";

$missingPages = [
    'profile.php' => "<?php\nrequire_once __DIR__ . '/../src/Auth/AuthManager.php';\nrequire_once __DIR__ . '/../src/MultiTenant/TenantManager.php';\nAuthManager::requireAuth();\nTenantManager::initialize();\n\n\$user = AuthManager::getCurrentUser();\n\$company = TenantManager::getCurrentCompany();\n\n?>\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <title>Profile - Keelance</title>\n    <script src=\"https://cdn.tailwindcss.com\"></script>\n    <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css\">\n</head>\n<body class=\"bg-gray-50\">\n    <?php require_once 'navigation.php'; renderNavigation(); ?>\n    <div class=\"max-w-4xl mx-auto py-6\">\n        <h1 class=\"text-2xl font-bold mb-6\">Profile Settings</h1>\n        <div class=\"bg-white rounded-lg shadow p-6\">\n            <p>Profile settings coming soon...</p>\n        </div>\n    </div>\n</body>\n</html>",
    
    'team.php' => "<?php\nrequire_once __DIR__ . '/../src/Auth/AuthManager.php';\nrequire_once __DIR__ . '/../src/MultiTenant/TenantManager.php';\nAuthManager::requireAuth();\nTenantManager::initialize();\n\n\$user = AuthManager::getCurrentUser();\n\$company = TenantManager::getCurrentCompany();\n\n?>\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <title>Team - Keelance</title>\n    <script src=\"https://cdn.tailwindcss.com\"></script>\n    <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css\">\n</head>\n<body class=\"bg-gray-50\">\n    <?php require_once 'navigation.php'; renderNavigation(); ?>\n    <div class=\"max-w-4xl mx-auto py-6\">\n        <h1 class=\"text-2xl font-bold mb-6\">Team Management</h1>\n        <div class=\"bg-white rounded-lg shadow p-6\">\n            <p>Team management coming soon...</p>\n        </div>\n    </div>\n</body>\n</html>",
];

foreach ($missingPages as $page => $content) {
    $filePath = __DIR__ . '/public/' . $page;
    if (!file_exists($filePath)) {
        file_put_contents($filePath, $content);
        echo "✅ Created {$page}\n";
    } else {
        echo "ℹ️  {$page} already exists\n";
    }
}

// Step 7: Final verification
echo "\nStep 7: Final verification...\n";

$requiredFiles = [
    'src/Auth/AuthManager.php',
    'src/MultiTenant/TenantManager.php', 
    'src/Billing/SubscriptionManager.php',
    'src/Billing/PaymentManager.php',
    'src/FileManager.php',
    'src/Client.php',
    'src/Invoice.php',
    'src/Proposal.php',
    'public/login.php',
    'public/dashboard.php',
    'public/billing.php',
    'public/navigation.php',
    'public/storage.php',
    'database/saas_schema.sql',
    '.env.example'
];

$allFilesExist = true;
foreach ($requiredFiles as $file) {
    if (file_exists(__DIR__ . '/' . $file)) {
        echo "✅ {$file}\n";
    } else {
        echo "❌ {$file} - MISSING\n";
        $allFilesExist = false;
    }
}

if ($allFilesExist) {
    echo "\n🎉 KEELANCE SAAS PLATFORM SETUP COMPLETE!\n";
    echo "\n📋 NEXT STEPS:\n";
    echo "1. Configure your .env file with database credentials\n";
    echo "2. Set up payment gateway keys (Stripe/Razorpay)\n";
    echo "3. Configure your domain for subdomain access\n";
    echo "4. Visit: http://yourdomain.com/welcome.html\n";
    echo "5. Login with: admin@keelance.com / admin123\n";
    echo "\n🚀 Your SaaS platform is ready to generate revenue!\n";
} else {
    echo "\n⚠️  Some files are missing. Please review the setup.\n";
}

echo "\n📊 PLATFORM FEATURES:\n";
echo "✅ Multi-tenant architecture\n";
echo "✅ User authentication & roles\n";
echo "✅ Subscription billing system\n";
echo "✅ Company-specific file storage\n";
echo "✅ Payment gateway integration\n";
echo "✅ Usage tracking & limits\n";
echo "✅ Modern dashboard UI\n";
echo "✅ Complete proposal/invoice system\n";
echo "\n💰 READY TO START GENERATING REVENUE!\n";
