<?php
echo "<h1>🚀 FULL APPLICATION TEST</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;font-size:14px;} .error{color:red;font-weight:bold;} .success{color:green;font-weight:bold;} .warning{color:orange;font-weight:bold;} .info{color:blue;} pre{background:#f5f5f5;padding:10px;border-radius:4px;margin:10px 0;max-height:200px;overflow:auto;}</style>";

// Enable full error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h2>🔍 FINAL APPLICATION TEST</h2>";
echo "<p class='info'>This script will simulate the exact same request that causes 500 error</p>";

try {
    // Step 1: Initialize Laravel exactly like web request
    echo "<h3>Step 1: Laravel Initialization</h3>";
    require_once '../vendor/autoload.php';
    $app = require_once '../bootstrap/app.php';
    $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
    echo "<p class='success'>✅ Laravel initialized successfully</p>";

    // Step 2: Create the same request as browser
    echo "<h3>Step 2: Creating HTTP Request</h3>";
    $request = \Illuminate\Http\Request::create('/', 'GET', [], [], [], [
        'REQUEST_METHOD' => 'GET',
        'REQUEST_URI' => '/',
        'SERVER_NAME' => '192.168.10.70',
        'SERVER_PORT' => '80',
        'HTTP_HOST' => '192.168.10.70',
        'HTTP_USER_AGENT' => 'Debug Script',
        'REMOTE_ADDR' => '127.0.0.1',
    ]);

    echo "<p class='success'>✅ HTTP Request created</p>";
    echo "<p class='info'>Request URI: {$request->getRequestUri()}</p>";
    echo "<p class='info'>Request Method: {$request->getMethod()}</p>";

    // Step 3: Handle the request through kernel
    echo "<h3>Step 3: Processing Request Through Kernel</h3>";
    $response = $kernel->handle($request);
    echo "<p class='success'>✅ Request processed by HTTP Kernel</p>";

    // Step 4: Check response
    echo "<h3>Step 4: Analyzing Response</h3>";
    $statusCode = $response->getStatusCode();
    $content = $response->getContent();

    echo "<p><strong>Response Status:</strong> $statusCode</p>";
    echo "<p><strong>Content Length:</strong> " . strlen($content) . " characters</p>";

    if ($statusCode === 200) {
        echo "<p class='success'>✅ SUCCESS! Response status is 200 OK</p>";

        // Check content for errors
        if (strpos($content, 'Whoops') !== false) {
            echo "<p class='error'>❌ Laravel error page detected in content</p>";
            // Extract error details
            if (preg_match('/<h1>(.*?)<\/h1>/s', $content, $matches)) {
                echo "<p class='error'>Error title: {$matches[1]}</p>";
            }
        } elseif (strpos($content, 'Fatal error') !== false) {
            echo "<p class='error'>❌ PHP Fatal error detected in content</p>";
        } elseif (strpos($content, 'Symfony\\Component\\Debug\\Exception') !== false) {
            echo "<p class='error'>❌ Symfony exception detected in content</p>";
        } else {
            echo "<p class='success'>✅ Content appears to be valid HTML</p>";

            // Check for basic HTML structure
            if (strpos($content, '<!DOCTYPE') !== false || strpos($content, '<html') !== false) {
                echo "<p class='success'>✅ Valid HTML structure detected</p>";
            }

            // Check for Laravel-specific content
            if (strpos($content, 'laravel') !== false || strpos($content, 'Laravel') !== false) {
                echo "<p class='success'>✅ Laravel-specific content found</p>";
            }
        }

        // Show first 500 characters of content
        echo "<h4>Response Content Preview:</h4>";
        echo "<pre>" . htmlspecialchars(substr($content, 0, 500)) . "...</pre>";

    } elseif ($statusCode === 500) {
        echo "<p class='error'>❌ ERROR 500 DETECTED!</p>";
        echo "<p class='error'>This confirms the 500 error issue</p>";

        // Try to get more details from the response
        if (!empty($content)) {
            echo "<h4>Error Response Content:</h4>";
            echo "<pre>" . htmlspecialchars(substr($content, 0, 1000)) . "...</pre>";
        }

        // Check Laravel logs for this request
        $logFile = '../storage/logs/laravel.log';
        if (file_exists($logFile)) {
            $logContent = file_get_contents($logFile);
            $lines = explode("\n", $logContent);
            $recentLines = array_slice($lines, -20); // Last 20 lines
            echo "<h4>Recent Laravel Log Entries:</h4>";
            echo "<pre>" . implode("\n", $recentLines) . "</pre>";
        }

    } else {
        echo "<p class='warning'>⚠️ Unexpected status code: $statusCode</p>";
    }

    // Step 5: Clean up
    echo "<h3>Step 5: Cleanup</h3>";
    $kernel->terminate($request, $response);
    echo "<p class='success'>✅ Request cleanup completed</p>";

} catch (Exception $e) {
    echo "<h2 class='error'>💥 EXCEPTION CAUGHT!</h2>";
    echo "<p class='error'>This is the source of your 500 error:</p>";
    echo "<div style='background:#f8d7da;padding:15px;border-radius:8px;margin:10px 0;border:1px solid #f5c6cb;'>";
    echo "<h3 style='color:#721c24;'>Exception Details:</h3>";
    echo "<p style='color:#721c24;'><strong>Type:</strong> " . get_class($e) . "</p>";
    echo "<p style='color:#721c24;'><strong>Message:</strong> " . $e->getMessage() . "</p>";
    echo "<p style='color:#721c24;'><strong>File:</strong> " . $e->getFile() . "</p>";
    echo "<p style='color:#721c24;'><strong>Line:</strong> " . $e->getLine() . "</p>";
    echo "</div>";

    echo "<h3>Stack Trace:</h3>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";

    // Try to provide specific fix
    echo "<h3>🔧 Suggested Fix:</h3>";
    $errorMessage = $e->getMessage();
    $errorFile = basename($e->getFile());

    if (strpos($errorMessage, 'Class') !== false && strpos($errorMessage, 'not found') !== false) {
        echo "<p class='error'>This is an autoload/class loading error. Try running: <code>composer dump-autoload</code></p>";
    } elseif (strpos($errorMessage, 'syntax error') !== false) {
        echo "<p class='error'>PHP syntax error in file: $errorFile</p>";
    } elseif (strpos($errorMessage, 'Permission denied') !== false) {
        echo "<p class='error'>File permission issue. Run the permission fix script.</p>";
    } elseif (strpos($errorFile, 'BpmController.php') !== false) {
        echo "<p class='error'>Error in BpmController. Check the controller code.</p>";
    } elseif (strpos($errorMessage, 'View') !== false) {
        echo "<p class='error'>View rendering error. Check view files.</p>";
    }
}

echo "<hr>";
echo "<p><strong>Test completed at:</strong> " . date('Y-m-d H:i:s') . "</p>";
echo "<p><strong>Server:</strong> " . $_SERVER['SERVER_ADDR'] . "</p>";
?>
