<?php
/**
 * Keelance SaaS Platform Setup Script
 * Run this script to initialize the entire platform
 */

echo "<h1>🚀 Keelance SaaS Platform Setup</h1>\n";

// Check if running in CLI or web
$isWeb = php_sapi_name() !== 'cli';

if ($isWeb) {
    echo "<style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .warning { color: orange; }
        pre { background: #f5f5f5; padding: 10px; border-radius: 5px; }
        .step { margin: 20px 0; padding: 15px; border-left: 4px solid #007bff; background: #f8f9fa; }
    </style>";
}

function logMessage($message, $type = 'info') {
    global $isWeb;
    $class = $type;
    $prefix = strtoupper($type) . ': ';
    
    if ($isWeb) {
        echo "<div class='step'><span class='{$class}'>{$prefix}</span>{$message}</div>\n";
    } else {
        echo "{$prefix}{$message}\n";
    }
}

// Step 1: Check requirements
logMessage("Checking system requirements...", 'info');

$requirements = [
    'PHP Version >= 8.0' => version_compare(PHP_VERSION, '8.0.0', '>='),
    'PDO MySQL Extension' => extension_loaded('pdo_mysql'),
    'JSON Extension' => extension_loaded('json'),
    'cURL Extension' => extension_loaded('curl'),
    'OpenSSL Extension' => extension_loaded('openssl'),
];

$allRequirementsMet = true;
foreach ($requirements as $requirement => $met) {
    $status = $met ? '✅' : '❌';
    logMessage("{$status} {$requirement}", $met ? 'success' : 'error');
    if (!$met) $allRequirementsMet = false;
}

if (!$allRequirementsMet) {
    logMessage("Please install missing requirements before continuing.", 'error');
    exit(1);
}

// Step 2: Load environment
logMessage("Loading environment configuration...", 'info');

if (!file_exists(__DIR__ . '/.env')) {
    if (file_exists(__DIR__ . '/.env.example')) {
        copy(__DIR__ . '/.env.example', __DIR__ . '/.env');
        logMessage("Created .env file from .env.example", 'success');
        logMessage("Please update your database credentials in .env file", 'warning');
    } else {
        logMessage("No .env.example file found", 'error');
        exit(1);
    }
}

// Load environment variables
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos($line, '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        
        list($key, $value) = explode('=', $line, 2);
        $key = trim($key);
        $value = trim($value);
        
        // Remove quotes if present
        if (strpos($value, '"') === 0) $value = substr($value, 1, -1);
        if (strpos($value, "'") === 0) $value = substr($value, 1, -1);
        
        $_ENV[$key] = $value;
        $_SERVER[$key] = $value;
    }
    logMessage("Environment variables loaded", 'success');
}

// Step 3: Database setup
logMessage("Setting up database...", 'info');

try {
    require_once __DIR__ . '/src/db.php';
    
    // Create database if not exists
    createDatabaseIfNotExists();
    logMessage("Database created/verified", 'success');
    
    // Run SaaS schema migration
    $saasSchema = __DIR__ . '/database/saas_schema.sql';
    if (file_exists($saasSchema)) {
        runMigration($saasSchema);
        logMessage("SaaS database schema created", 'success');
    }
    
    // Run multi-tenant migration
    $migrationScript = __DIR__ . '/database/migrate_to_multitenant.php';
    if (file_exists($migrationScript)) {
        // We'll run the migration logic directly here since we can't call it from web
        require_once __DIR__ . '/src/db.php';
        require_once __DIR__ . '/src/Auth/AuthManager.php';
        require_once __DIR__ . '/src/MultiTenant/TenantManager.php';
        require_once __DIR__ . '/src/Billing/SubscriptionManager.php';
        
        $pdo = getPDO();
        
        // Add company_id to existing tables
        $tables = ['clients', 'proposals', 'invoices', 'contracts', 'invoice_items', 'invoice_items_line', 'invoice_payments', 'tax_brackets', 'invoice_settings', 'templates', 'modules', 'template_modules', 'contract_modules'];
        
        foreach ($tables as $table) {
            $stmt = $pdo->prepare("SHOW TABLES LIKE ?");
            $stmt->execute([$table]);
            
            if ($stmt->rowCount() > 0) {
                try {
                    $pdo->exec("ALTER TABLE {$table} ADD COLUMN company_id INT NOT NULL DEFAULT 1");
                    logMessage("Added company_id to {$table}", 'success');
                } catch (Exception $e) {
                    logMessage("company_id already exists in {$table}", 'info');
                }
                
                $pdo->exec("UPDATE {$table} SET company_id = 1 WHERE company_id IS NULL OR company_id = 0");
            }
        }
        
        logMessage("Multi-tenant migration completed", 'success');
    }
    
} catch (Exception $e) {
    logMessage("Database setup failed: " . $e->getMessage(), 'error');
    exit(1);
}

// Step 4: Create directories
logMessage("Creating necessary directories...", 'info');

$directories = [
    'storage',
    'storage/pdfs',
    'storage/logs',
    'storage/cache',
    'storage/uploads',
    'storage/temp'
];

foreach ($directories as $dir) {
    $fullPath = __DIR__ . '/' . $dir;
    if (!is_dir($fullPath)) {
        mkdir($fullPath, 0755, true);
        logMessage("Created directory: {$dir}", 'success');
    } else {
        logMessage("Directory already exists: {$dir}", 'info');
    }
}

// Step 5: Set permissions
logMessage("Setting file permissions...", 'info');

$writableDirs = ['storage', 'storage/pdfs', 'storage/logs', 'storage/cache'];
foreach ($writableDirs as $dir) {
    $fullPath = __DIR__ . '/' . $dir;
    if (is_dir($fullPath)) {
        chmod($fullPath, 0755);
        logMessage("Set permissions for: {$dir}", 'success');
    }
}

// Step 6: Create .htaccess for pretty URLs
logMessage("Creating .htaccess for URL rewriting...", 'info');

$htaccessContent = "
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

# Security headers
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection \"1; mode=block\"

# Hide .htaccess
<Files .htaccess>
    Order allow,deny
    Deny from all
</Files>
";

file_put_contents(__DIR__ . '/public/.htaccess', $htaccessContent);
logMessage("Created public/.htaccess", 'success');

// Step 7: Create main index.php router
logMessage("Creating main router...", 'info');

$indexContent = "<?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';

// 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',
];

// 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', $indexContent);
logMessage("Created public/index.php router", 'success');

// Step 8: Create logout.php
logMessage("Creating logout handler...", 'info');

$logoutContent = "<?php
require_once __DIR__ . '/../src/Auth/AuthManager.php';

AuthManager::logout();
header('Location: /login.php');
exit;
";

file_put_contents(__DIR__ . '/public/logout.php', $logoutContent);
logMessage("Created logout.php", 'success');

// Step 9: Create welcome page
logMessage("Creating welcome page...", 'info');

$welcomeContent = "
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Keelance SaaS Platform</title>
    <script src='https://cdn.tailwindcss.com'></script>
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css'>
</head>
<body class='bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen'>
    <div class='flex items-center justify-center min-h-screen'>
        <div class='max-w-md w-full text-center'>
            <div class='mb-8'>
                <div class='mx-auto h-16 w-16 flex items-center justify-center rounded-full bg-blue-100 mb-4'>
                    <i class='fas fa-rocket text-blue-600 text-2xl'></i>
                </div>
                <h1 class='text-3xl font-bold text-gray-900 mb-2'>Keelance</h1>
                <p class='text-gray-600'>SaaS Proposal & Invoice Management Platform</p>
            </div>
            
            <div class='bg-white rounded-lg shadow-lg p-8'>
                <div class='mb-6'>
                    <i class='fas fa-check-circle text-green-500 text-4xl mb-4'></i>
                    <h2 class='text-xl font-semibold text-gray-900 mb-2'>Setup Complete!</h2>
                    <p class='text-gray-600'>Your Keelance SaaS platform is ready to use.</p>
                </div>
                
                <div class='space-y-3 text-left'>
                    <div class='flex items-center text-sm text-gray-700'>
                        <i class='fas fa-database text-blue-500 mr-3'></i>
                        <span>Multi-tenant database configured</span>
                    </div>
                    <div class='flex items-center text-sm text-gray-700'>
                        <i class='fas fa-users text-blue-500 mr-3'></i>
                        <span>User authentication system ready</span>
                    </div>
                    <div class='flex items-center text-sm text-gray-700'>
                        <i class='fas fa-credit-card text-blue-500 mr-3'></i>
                        <span>Billing & subscription management</span>
                    </div>
                    <div class='flex items-center text-sm text-gray-700'>
                        <i class='fas fa-building text-blue-500 mr-3'></i>
                        <span>Multi-workspace support</span>
                    </div>
                </div>
                
                <div class='mt-8 space-y-3'>
                    <a href='/login' class='w-full flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700'>
                        <i class='fas fa-sign-in-alt mr-2'></i> Login to Dashboard
                    </a>
                    
                    <div class='text-xs text-gray-500'>
                        <p>Default Admin: admin@keelance.com / admin123</p>
                    </div>
                </div>
                
                <div class='mt-6 p-4 bg-blue-50 rounded-lg'>
                    <h3 class='text-sm font-medium text-blue-800 mb-2'>Next Steps:</h3>
                    <ol class='text-xs text-blue-700 space-y-1'>
                        <li>1. Configure your payment gateways (.env file)</li>
                        <li>2. Set up your domain and subdomains</li>
                        <li>3. Customize subscription plans</li>
                        <li>4. Invite team members</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
";

file_put_contents(__DIR__ . '/public/welcome.html', $welcomeContent);
logMessage("Created welcome page", 'success');

// Final summary
logMessage("🎉 Setup completed successfully!", 'success');

echo "<div class='step'>";
echo "<h2>🚀 Keelance SaaS Platform is Ready!</h2>";
echo "<p><strong>Default Login:</strong> admin@keelance.com / admin123</p>";
echo "<p><strong>Next Steps:</strong></p>";
echo "<ol>";
echo "<li>Update your .env file with real database credentials</li>";
echo "<li>Configure Stripe and Razorpay payment gateways</li>";
echo "<li>Set up your domain for multi-tenant subdomains</li>";
echo "<li>Visit <a href='/welcome.html'>Welcome Page</a> to get started</li>";
echo "</ol>";
echo "</div>";

if ($isWeb) {
    echo "<div class='step'>";
    echo "<a href='/welcome.html' class='inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700'>";
    echo "<i class='fas fa-rocket mr-2'></i> Go to Welcome Page";
    echo "</a>";
    echo "</div>";
}
