<?php
/**
 * Shared Hosting Setup Script
 * 
 * INSTRUCTIONS:
 * 1. Upload this file to your public/ folder
 * 2. Visit: https://yourdomain.com/setup.php?run=setup
 * 3. Wait for completion
 * 4. DELETE THIS FILE IMMEDIATELY FOR SECURITY!
 * 
 * This script runs Laravel artisan commands via web interface.
 */

// Security check - prevents accidental execution
if (!isset($_GET['run']) || $_GET['run'] !== 'setup') {
    die('
    <h1>Laravel Setup Script</h1>
    <p>To run setup, add <code>?run=setup</code> to the URL</p>
    <p><strong>Example:</strong> <code>https://yourdomain.com/setup.php?run=setup</code></p>
    <hr>
    <p><strong>⚠️ SECURITY WARNING:</strong> Delete this file after setup is complete!</p>
    ');
}

// Additional security - check if already configured
if (file_exists(__DIR__ . '/../.env') && !empty(env('APP_KEY'))) {
    $confirm = $_GET['confirm'] ?? 'no';
    if ($confirm !== 'yes') {
        die('
        <h1>Setup Already Configured</h1>
        <p>Your application appears to be already set up.</p>
        <p>If you want to run setup again, add <code>&confirm=yes</code> to the URL</p>
        <p><strong>Example:</strong> <code>https://yourdomain.com/setup.php?run=setup&confirm=yes</code></p>
        <hr>
        <p><strong>⚠️ SECURITY WARNING:</strong> Delete this file after setup is complete!</p>
        ');
    }
}

// Bootstrap Laravel
require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

// Start output
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Setup</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
        .success { color: #10b981; }
        .error { color: #ef4444; }
        .info { color: #3b82f6; }
        pre { background: #f3f4f6; padding: 15px; border-radius: 5px; overflow-x: auto; }
        .warning { background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0; }
    </style>
</head>
<body>
    <h1>🚀 Laravel Setup Running...</h1>
    <pre><?php

$errors = [];
$success = [];

// 1. Generate APP_KEY if not set
echo "1. Checking APP_KEY...\n";
if (empty(env('APP_KEY'))) {
    try {
        $kernel->call('key:generate', ['--force' => true]);
        echo "   ✓ APP_KEY generated successfully\n";
        $success[] = 'APP_KEY generated';
    } catch (Exception $e) {
        echo "   ✗ Error: " . $e->getMessage() . "\n";
        $errors[] = 'APP_KEY generation failed: ' . $e->getMessage();
    }
} else {
    echo "   ✓ APP_KEY already set\n";
    $success[] = 'APP_KEY already configured';
}

// 2. Run migrations
echo "\n2. Running database migrations...\n";
try {
    $kernel->call('migrate', ['--force' => true]);
    echo "   ✓ Migrations completed successfully\n";
    $success[] = 'Database migrations completed';
} catch (Exception $e) {
    echo "   ✗ Error: " . $e->getMessage() . "\n";
    $errors[] = 'Migrations failed: ' . $e->getMessage();
}

// 3. Create storage link
echo "\n3. Creating storage link...\n";
try {
    if (!file_exists(__DIR__ . '/storage')) {
        $kernel->call('storage:link');
        echo "   ✓ Storage link created\n";
        $success[] = 'Storage link created';
    } else {
        echo "   ✓ Storage link already exists\n";
        $success[] = 'Storage link already exists';
    }
} catch (Exception $e) {
    echo "   ✗ Error: " . $e->getMessage() . "\n";
    $errors[] = 'Storage link failed: ' . $e->getMessage();
}

// 4. Cache configuration
echo "\n4. Caching configuration...\n";
try {
    $kernel->call('config:cache');
    echo "   ✓ Configuration cached\n";
    $success[] = 'Configuration cached';
} catch (Exception $e) {
    echo "   ⚠ Warning: " . $e->getMessage() . "\n";
    // Not critical, continue
}

// 5. Cache routes
echo "\n5. Caching routes...\n";
try {
    $kernel->call('route:cache');
    echo "   ✓ Routes cached\n";
    $success[] = 'Routes cached';
} catch (Exception $e) {
    echo "   ⚠ Warning: " . $e->getMessage() . "\n";
    // Not critical, continue
}

echo "\n" . str_repeat("=", 50) . "\n";

?></pre>

<?php if (count($success) > 0): ?>
    <div class="success">
        <h2>✅ Successfully Completed:</h2>
        <ul>
            <?php foreach ($success as $item): ?>
                <li><?php echo htmlspecialchars($item); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (count($errors) > 0): ?>
    <div class="error">
        <h2>❌ Errors Encountered:</h2>
        <ul>
            <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
        <p>Check <code>storage/logs/laravel.log</code> for more details.</p>
    </div>
<?php endif; ?>

<div class="warning">
    <h2>⚠️ SECURITY WARNING</h2>
    <p><strong>IMPORTANT:</strong> Delete this file (<code>setup.php</code>) immediately after setup is complete!</p>
    <p>This file allows running system commands and should NOT remain on your server.</p>
</div>

<div class="info">
    <h2>📋 Next Steps:</h2>
    <ol>
        <li>Delete this <code>setup.php</code> file</li>
        <li>Test your website: <a href="/">Visit Homepage</a></li>
        <li>Test admin: <a href="/admin">Visit Admin</a></li>
        <li>Check logs: <code>storage/logs/laravel.log</code></li>
    </ol>
</div>

</body>
</html>
