<?php

/**
 * Frontend Error Checker
 * This script quickly tests all frontend pages for JavaScript errors and toast functionality
 */

echo "🧪 FRONTEND ERROR CHECKER\n";
echo "=" . str_repeat("=", 60) . "\n\n";

// Check if server is running
$serverUrl = 'http://localhost:8000';
$context = stream_context_create([
    'http' => [
        'timeout' => 5,
        'ignore_errors' => true
    ]
]);

echo "🔍 Checking if server is running...\n";
$response = @file_get_contents($serverUrl, false, $context);
if ($response === false) {
    echo "❌ Server is not running on {$serverUrl}\n";
    echo "   Please run: php artisan serve --host=0.0.0.0 --port=8000\n\n";
    exit(1);
}
echo "✅ Server is running\n\n";

// Test pages to check
$pages = [
    '/subjects' => 'Subjects Index',
    '/subjects/create' => 'Subject Create',
    '/classrooms' => 'Classrooms Index', 
    '/classrooms/create' => 'Classroom Create',
    '/academic-years' => 'Academic Years Index',
    '/academic-years/create' => 'Academic Year Create',
    '/exam-types' => 'Exam Types Index',
    '/students' => 'Students Index',
    '/teachers' => 'Teachers Index',
];

echo "📄 CHECKING PAGE LOADS...\n";
echo "-" . str_repeat("-", 40) . "\n";

foreach ($pages as $path => $name) {
    $url = $serverUrl . $path;
    $response = @file_get_contents($url, false, $context);
    
    if ($response === false) {
        echo "❌ {$name}: Failed to load\n";
        continue;
    }
    
    // Check for common errors in the HTML
    $errors = [];
    
    if (strpos($response, 'ReferenceError') !== false) {
        $errors[] = 'ReferenceError found';
    }
    if (strpos($response, 'TypeError') !== false) {
        $errors[] = 'TypeError found';
    }
    if (strpos($response, 'SyntaxError') !== false) {
        $errors[] = 'SyntaxError found';
    }
    if (strpos($response, 'useToast is not defined') !== false) {
        $errors[] = 'useToast not defined';
    }
    if (strpos($response, 'toast is not defined') !== false) {
        $errors[] = 'toast not defined';
    }
    if (strpos($response, 'Cannot read property') !== false) {
        $errors[] = 'Property access error';
    }
    if (strpos($response, 'Uncaught') !== false) {
        $errors[] = 'Uncaught error';
    }
    
    // Check if required components are present
    $hasToastContainer = strpos($response, 'ToastContainer') !== false;
    $hasUseToast = strpos($response, 'useToast') !== false;
    $hasAppShell = strpos($response, 'AppShell') !== false;
    
    if (!empty($errors)) {
        echo "❌ {$name}: " . implode(', ', $errors) . "\n";
    } else {
        echo "✅ {$name}: Loads successfully\n";
    }
    
    // Additional checks
    if (!$hasToastContainer && in_array($path, ['/subjects', '/classrooms', '/academic-years'])) {
        echo "   ⚠️  ToastContainer not found in response\n";
    }
}

echo "\n";

// Check specific toast functionality
echo "🍞 CHECKING TOAST IMPLEMENTATION...\n";
echo "-" . str_repeat("-", 40) . "\n";

$toastFiles = [
    'resources/js/composables/useToast.ts' => 'Toast Composable',
    'resources/js/components/ui/toast/Toast.vue' => 'Toast Component',
    'resources/js/components/ui/toast/ToastContainer.vue' => 'Toast Container',
    'resources/js/components/AppShell.vue' => 'AppShell with Toast',
];

foreach ($toastFiles as $file => $name) {
    if (file_exists($file)) {
        $content = file_get_contents($file);
        
        if ($file === 'resources/js/composables/useToast.ts') {
            $hasAddToast = strpos($content, 'addToast') !== false;
            $hasSuccess = strpos($content, 'success') !== false;
            $hasError = strpos($content, 'error') !== false;
            
            if ($hasAddToast && $hasSuccess && $hasError) {
                echo "✅ {$name}: Complete implementation\n";
            } else {
                echo "❌ {$name}: Missing methods\n";
            }
        } elseif ($file === 'resources/js/components/ui/toast/ToastContainer.vue') {
            $hasUseToast = strpos($content, 'useToast') !== false;
            $hasToastsRef = strpos($content, 'toasts') !== false;
            
            if ($hasUseToast && $hasToastsRef) {
                echo "✅ {$name}: Properly connected to composable\n";
            } else {
                echo "❌ {$name}: Not connected to composable\n";
            }
        } elseif ($file === 'resources/js/components/AppShell.vue') {
            $hasToastContainer = strpos($content, 'ToastContainer') !== false;
            
            if ($hasToastContainer) {
                echo "✅ {$name}: ToastContainer included\n";
            } else {
                echo "❌ {$name}: ToastContainer not included\n";
            }
        } else {
            echo "✅ {$name}: File exists\n";
        }
    } else {
        echo "❌ {$name}: File not found\n";
    }
}

echo "\n";

// Check specific pages for toast implementation
echo "🔧 CHECKING PAGE TOAST INTEGRATION...\n";
echo "-" . str_repeat("-", 40) . "\n";

$pageFiles = [
    'resources/js/pages/Academic/Subjects/Index.vue' => 'Subjects Index',
    'resources/js/pages/Academic/Subjects/Create.vue' => 'Subject Create',
    'resources/js/pages/Academic/Classrooms/Index.vue' => 'Classrooms Index',
    'resources/js/pages/Academic/Classrooms/Create.vue' => 'Classroom Create',
    'resources/js/pages/Academic/AcademicYears/Index.vue' => 'Academic Years Index',
];

foreach ($pageFiles as $file => $name) {
    if (file_exists($file)) {
        $content = file_get_contents($file);
        
        $hasUseToast = strpos($content, 'useToast') !== false;
        $hasToastSuccess = strpos($content, 'toast.success') !== false;
        $hasToastError = strpos($content, 'toast.error') !== false;
        $hasDeleteFunction = strpos($content, 'delete') !== false;
        
        $issues = [];
        if (!$hasUseToast) $issues[] = 'No useToast import';
        if (!$hasToastSuccess && !$hasToastError) $issues[] = 'No toast calls';
        
        if (empty($issues)) {
            echo "✅ {$name}: Toast properly implemented\n";
        } else {
            echo "❌ {$name}: " . implode(', ', $issues) . "\n";
        }
    } else {
        echo "❌ {$name}: File not found\n";
    }
}

echo "\n";

// Summary and recommendations
echo "📋 SUMMARY & RECOMMENDATIONS\n";
echo "=" . str_repeat("=", 60) . "\n";

echo "✅ **Quick Tests Completed**\n";
echo "   - Page load tests\n";
echo "   - Toast file existence\n";
   echo "   - Basic implementation checks\n\n";

echo "🔧 **To run comprehensive tests:**\n";
echo "   1. Backend tests: php artisan test tests/Feature/Frontend/ToastNotificationTest.php\n";
echo "   2. Browser tests: php artisan dusk tests/Browser/ToastFunctionalityTest.php\n\n";

echo "🌐 **To test manually:**\n";
echo "   1. Visit: {$serverUrl}/subjects\n";
echo "   2. Try creating a subject\n";
echo "   3. Try deleting a subject\n";
echo "   4. Check browser console (F12) for errors\n";
echo "   5. Look for toast notifications\n\n";

echo "🐛 **If you see errors:**\n";
echo "   1. Check browser console for specific JavaScript errors\n";
echo "   2. Verify all imports are correct\n";
echo "   3. Ensure ToastContainer is in AppShell\n";
echo "   4. Check that useToast composable is properly exported\n\n";

echo "🎉 **Testing complete!**\n";
