<?php
/**
 * Deep Diagnostic - Tests API endpoints and runtime issues
 * Access: yourdomain.com/debug2.php
 */

header('Content-Type: text/html');
echo "<pre style='font-family:monospace;font-size:13px;padding:20px;background:#0d1117;color:#c9d1d9;line-height:1.6;'>";
echo "╔══════════════════════════════════════════════════════════════╗\n";
echo "║         DEEP DIAGNOSTIC - API & Runtime Check                  ║\n";
echo "╚══════════════════════════════════════════════════════════════╝\n\n";

// 1. Test Homepage Content
echo "1. HOMEPAGE HTML ANALYSIS\n";
echo str_repeat("═", 60) . "\n";
$ch = curl_init('http://' . $_SERVER['HTTP_HOST'] . '/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP Code: $httpCode\n";
echo "HTML Length: " . strlen($html) . " chars\n\n";

// Check for critical elements
$checks = [
    'Has DOCTYPE' => strpos($html, '<!DOCTYPE') !== false,
    'Has html tag' => strpos($html, '<html') !== false,
    'Has head tag' => strpos($html, '<head>') !== false,
    'Has body tag' => strpos($html, '<body') !== false,
    'Has div#app' => preg_match('/<div[^>]*id=["\']app["\']/', $html),
    'Has script tag' => strpos($html, '<script') !== false,
    'Has CSS link' => strpos($html, '<link') !== false,
    'Has Vite reference' => strpos($html, 'vite') !== false || strpos($html, 'manifest') !== false,
];

foreach ($checks as $label => $result) {
    echo ($result ? "✅" : "❌") . " $label\n";
}

// Extract script src
preg_match_all('/<script[^>]+src=["\']([^"\']+)["\']/', $html, $scripts);
echo "\nScript sources found:\n";
foreach ($scripts[1] ?? [] as $src) {
    echo "  → $src\n";
}

// Extract CSS links
preg_match_all('/<link[^>]+href=["\']([^"\']+)["\']/', $html, $links);
echo "\nCSS/Link sources found:\n";
foreach ($links[1] ?? [] as $href) {
    echo "  → $href\n";
}

// Check for Laravel error in HTML
if (strpos($html, 'Whoops') !== false || strpos($html, 'Stack trace') !== false || strpos($html, 'Fatal error') !== false) {
    echo "\n⚠️ LARAVEL ERROR DETECTED IN HTML!\n";
    echo substr($html, 0, 2000) . "\n";
}

echo "\n\n";

// 2. Test if JS files are actually accessible and have content
echo "2. JS/CSS FILE VERIFICATION\n";
echo str_repeat("═", 60) . "\n";

foreach ($scripts[1] ?? [] as $src) {
    $url = (strpos($src, 'http') === 0) ? $src : 'http://' . $_SERVER['HTTP_HOST'] . $src;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $js = curl_exec($ch);
    $jsCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $jsSize = strlen($js);
    curl_close($ch);
    
    echo "Script: $src\n";
    echo "  HTTP: $jsCode | Size: " . round($jsSize/1024, 2) . " KB\n";
    
    if ($jsCode == 200 && $jsSize > 1000) {
        echo "  ✅ File loads correctly\n";
        // Check for common JS issues
        if (strpos($js, 'React') !== false || strpos($js, 'createElement') !== false) {
            echo "  ✅ Contains React code\n";
        }
    } else {
        echo "  ❌ File issue (code: $jsCode, size: $jsSize)\n";
    }
    echo "\n";
}

foreach ($links[1] ?? [] as $href) {
    if (strpos($href, '.css') !== false) {
        $url = (strpos($href, 'http') === 0) ? $href : 'http://' . $_SERVER['HTTP_HOST'] . $href;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $css = curl_exec($ch);
        $cssCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        echo "CSS: $href\n";
        echo "  HTTP: $cssCode | Size: " . round(strlen($css)/1024, 2) . " KB\n";
        echo ($cssCode == 200 ? "  ✅ CSS loads\n" : "  ❌ CSS issue\n");
        echo "\n";
    }
}

// 3. Test API Endpoints
echo "3. API ENDPOINT TESTS\n";
echo str_repeat("═", 60) . "\n";

// First, we need to authenticate. Try a simple health check first.
$endpoints = [
    ['GET', '/api/login', false],  // Should return 405 (method not allowed) or login form
    ['GET', '/api/dashboard', true],  // Requires auth
    ['GET', '/api/companies', true],  // Requires auth
    ['GET', '/sanctum/csrf-cookie', false],  // CSRF cookie
];

// Test without auth first
echo "Testing public endpoints:\n";
$testUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/api/login';
$ch = curl_init($testUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "  GET /api/login → HTTP $code\n";

$testUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/sanctum/csrf-cookie';
$ch = curl_init($testUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "  GET /sanctum/csrf-cookie → HTTP $code\n";

echo "\n\n";

// 4. Check Laravel Routes
echo "4. ROUTES CHECK\n";
echo str_repeat("═", 60) . "\n";
try {
    $vendorPath = __DIR__.'/../vendor/autoload.php';
    if (file_exists($vendorPath)) {
        require $vendorPath;
        $app = require __DIR__.'/../bootstrap/app.php';
        
        $router = $app->make('router');
        $routes = $router->getRoutes();
        
        $apiRoutes = [];
        $webRoutes = [];
        
        foreach ($routes as $route) {
            $uri = $route->uri();
            if (strpos($uri, 'api/') === 0) {
                $apiRoutes[] = $uri;
            } elseif (strpos($uri, '/') === 0 && strpos($uri, 'api/') !== 0) {
                $webRoutes[] = $uri;
            }
        }
        
        echo "API Routes found: " . count($apiRoutes) . "\n";
        if (count($apiRoutes) < 10) {
            echo "⚠️ Very few API routes - may indicate route loading issue!\n";
        }
        
        // Check specific critical routes
        $criticalRoutes = ['api/login', 'api/dashboard', 'api/companies', 'api/employees'];
        foreach ($criticalRoutes as $cr) {
            $found = in_array($cr, $apiRoutes);
            echo ($found ? "✅" : "❌") . " Route: $cr\n";
        }
        
        echo "\nWeb Routes found: " . count($webRoutes) . "\n";
    }
} catch (Throwable $e) {
    echo "❌ Error checking routes: " . $e->getMessage() . "\n";
}

echo "\n\n";

// 5. Check for JavaScript Console Errors (simulated)
echo "5. FRONTEND DIAGNOSTIC\n";
echo str_repeat("═", 60) . "\n";
echo "⚠️  IMPORTANT: Open your browser and press F12\n";
echo "    Go to Console tab and check for red errors\n";
echo "    Common white screen causes:\n";
echo "    • React error boundary caught an error\n";
echo "    • Undefined variable in JSX\n";
echo "    • Import error (missing component)\n";
echo "    • API call failing (CORS, 500 error)\n";
echo "    • Router configuration issue\n\n";

echo "To capture console errors, add this to your browser:\n";
echo "    (function(){\n";
echo "        var errs=[];\n";
echo "        window.onerror=function(m,u,l,c,e){errs.push({msg:m,url:u,line:l,col:c,error:e});return true;};\n";
echo "        setTimeout(function(){console.log('ERRORS:',errs);},5000);\n";
echo "    })();\n\n";

// 6. Check storage/logs for latest errors
echo "6. LATEST LOG ERRORS (since last upload)\n";
echo str_repeat("═", 60) . "\n";
$logPath = __DIR__.'/../storage/logs/laravel.log';
if (file_exists($logPath)) {
    $log = file_get_contents($logPath);
    // Get last 50 lines
    $lines = explode("\n", $log);
    $lastLines = array_slice($lines, -50);
    
    // Filter for recent errors (today only)
    $today = date('Y-m-d');
    $recentErrors = array_filter($lastLines, function($l) use ($today) {
        return strpos($l, $today) !== false && (strpos($l, 'ERROR') !== false || strpos($l, 'Exception') !== false);
    });
    
    if (empty($recentErrors)) {
        echo "✅ No errors found for today ($today)\n";
        echo "This means the backend is NOT throwing errors currently.\n";
        echo "The white screen is likely a FRONTEND JavaScript issue.\n\n";
    } else {
        echo "⚠️ Recent errors found:\n";
        foreach (array_slice($recentErrors, -5) as $err) {
            echo "  " . htmlspecialchars(substr($err, 0, 200)) . "\n";
        }
    }
} else {
    echo "❌ Log file not found\n";
}

echo "\n\n";

// 7. Summary
echo "╔══════════════════════════════════════════════════════════════╗\n";
echo "║                      DIAGNOSIS SUMMARY                        ║\n";
echo "╚══════════════════════════════════════════════════════════════╝\n\n";

echo "If ALL of these are true:\n";
echo "  ✅ Homepage HTML loads (200 OK)\n";
echo "  ✅ JS files load with content\n";
echo "  ✅ CSS files load\n";
echo "  ✅ No recent backend errors\n";
echo "  ✅ API routes exist\n";
echo "\nThen the problem is: FRONTEND JAVASCRIPT CRASH\n\n";

echo "NEXT STEPS:\n";
echo "1. Open https://sarkinmotagroup.com in Chrome/Firefox\n";
echo "2. Press F12 → Console tab\n";
echo "3. Look for RED error messages\n";
echo "4. Copy and share those errors\n\n";

echo "═════════════════════════════════════════════════════════════\n";
echo "END OF DIAGNOSTIC\n";
echo "═════════════════════════════════════════════════════════════\n";
echo "</pre>";

// Also output a simple inline script to help debug
echo "\n<script>\n";
echo "console.log('=== Sarkin Mota Debug Helper ===');\n";
echo "window.addEventListener('error', function(e) {\n";
echo "    console.error('CAUGHT ERROR:', e.message, 'at', e.filename, ':', e.lineno);\n";
echo "    document.body.innerHTML = '<div style=\"padding:20px;background:red;color:white;font-size:18px;\">JS ERROR: ' + e.message + ' at ' + e.filename + ':' + e.lineno + '</div>';\n";
echo "});\n";
echo "setTimeout(function() {\n";
echo "    var root = document.getElementById('app');\n";
echo "    if (root && root.children.length === 0) {\n";
echo "        console.warn('Root div #app is empty after 5s - React may have failed to render');\n";
echo "        document.body.innerHTML += '<div style=\"padding:20px;background:orange;color:black;font-size:18px;\">WARNING: React app did not render. Check console for errors.</div>';\n";
echo "    }\n";
echo "}, 5000);\n";
echo "</script>\n";
