<?php

/**
 * Comprehensive School Management System Test Script
 * 
 * This script tests all major functionality of the school management system
 * including frontend and backend features.
 */

echo "🚀 Starting School Management System Comprehensive Tests\n";
echo "=" . str_repeat("=", 60) . "\n\n";

// Test 1: Check if all required files exist
echo "📁 Testing File Structure...\n";
$requiredFiles = [
    // Vue Components
    'resources/js/pages/Students/Index.vue',
    'resources/js/pages/Students/Create.vue',
    'resources/js/pages/Teachers/Index.vue',
    'resources/js/pages/Teachers/Create.vue',
    'resources/js/pages/Guardians/Index.vue',
    'resources/js/pages/Guardians/Create.vue',
    'resources/js/pages/Academic/AcademicYears/Index.vue',
    'resources/js/pages/Academic/AcademicYears/Create.vue',
    'resources/js/pages/Academic/Subjects/Index.vue',
    'resources/js/pages/Academic/Subjects/Create.vue',
    'resources/js/pages/Academic/Classrooms/Index.vue',
    'resources/js/pages/Academic/Classrooms/Create.vue',
    'resources/js/pages/Academic/ExamTypes/Index.vue',
    'resources/js/pages/Academic/ExamTypes/Create.vue',
    'resources/js/pages/Enrollment/Index.vue',
    'resources/js/pages/Enrollment/Create.vue',
    'resources/js/pages/Enrollment/BulkEnroll.vue',
    'resources/js/pages/Results/Index.vue',
    'resources/js/pages/Results/Create.vue',
    'resources/js/pages/Configuration/Index.vue',
    'resources/js/pages/Configuration/GradingRules.vue',
    'resources/js/pages/Configuration/DivisionRules.vue',
    
    // Controllers
    'Modules/Students/app/Http/Controllers/StudentController.php',
    'Modules/Teachers/app/Http/Controllers/TeacherController.php',
    'Modules/Guardians/app/Http/Controllers/GuardianController.php',
    'Modules/Academic/app/Http/Controllers/AcademicYearController.php',
    'Modules/Academic/app/Http/Controllers/SubjectController.php',
    'Modules/Academic/app/Http/Controllers/ClassroomController.php',
    'Modules/Academic/app/Http/Controllers/ExamTypeController.php',
    'Modules/Enrollment/app/Http/Controllers/EnrollmentController.php',
    'Modules/Results/app/Http/Controllers/ResultController.php',
    'Modules/Configuration/app/Http/Controllers/ConfigurationController.php',
    
    // Models
    'Modules/Students/app/Models/Student.php',
    'Modules/Teachers/app/Models/Teacher.php',
    'Modules/Guardians/app/Models/Guardian.php',
    'Modules/Academic/app/Models/AcademicYear.php',
    'Modules/Academic/app/Models/Subject.php',
    'Modules/Academic/app/Models/Classroom.php',
    'Modules/Academic/app/Models/ExamType.php',
    'Modules/Enrollment/app/Models/Enrollment.php',
    'Modules/Results/app/Models/Result.php',
    'Modules/Configuration/app/Models/GradingRule.php',
    'Modules/Configuration/app/Models/DivisionRule.php',
];

$missingFiles = [];
foreach ($requiredFiles as $file) {
    if (!file_exists($file)) {
        $missingFiles[] = $file;
    }
}

if (empty($missingFiles)) {
    echo "✅ All required files exist\n\n";
} else {
    echo "❌ Missing files:\n";
    foreach ($missingFiles as $file) {
        echo "   - $file\n";
    }
    echo "\n";
}

// Test 2: Check database connection and tables
echo "🗄️  Testing Database Structure...\n";
try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=schoolapp', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $requiredTables = [
        'users', 'students', 'teachers', 'guardians',
        'academic_years', 'subjects', 'classrooms', 'exam_types',
        'enrollments', 'results', 'grading_rules', 'division_rules',
        'student_guardians', 'teacher_subjects', 'classroom_subjects'
    ];
    
    $stmt = $pdo->query("SHOW TABLES");
    $existingTables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $missingTables = array_diff($requiredTables, $existingTables);
    
    if (empty($missingTables)) {
        echo "✅ All required database tables exist\n";
        
        // Check if tables have data
        $dataCheck = [];
        foreach ($requiredTables as $table) {
            $stmt = $pdo->query("SELECT COUNT(*) FROM $table");
            $count = $stmt->fetchColumn();
            $dataCheck[$table] = $count;
        }
        
        echo "📊 Table data counts:\n";
        foreach ($dataCheck as $table => $count) {
            echo "   - $table: $count records\n";
        }
        echo "\n";
        
    } else {
        echo "❌ Missing database tables:\n";
        foreach ($missingTables as $table) {
            echo "   - $table\n";
        }
        echo "\n";
    }
    
} catch (PDOException $e) {
    echo "❌ Database connection failed: " . $e->getMessage() . "\n\n";
}

// Test 3: Check Laravel routes
echo "🛣️  Testing Routes...\n";
$routeCommands = [
    'php artisan route:list --name=students' => 'Student routes',
    'php artisan route:list --name=teachers' => 'Teacher routes',
    'php artisan route:list --name=guardians' => 'Guardian routes',
    'php artisan route:list --name=academic-years' => 'Academic Year routes',
    'php artisan route:list --name=subjects' => 'Subject routes',
    'php artisan route:list --name=classrooms' => 'Classroom routes',
    'php artisan route:list --name=exam-types' => 'Exam Type routes',
    'php artisan route:list --name=enrollment' => 'Enrollment routes',
    'php artisan route:list --name=results' => 'Result routes',
    'php artisan route:list --name=configuration' => 'Configuration routes',
];

foreach ($routeCommands as $command => $description) {
    $output = shell_exec($command . ' 2>&1');
    if (strpos($output, 'GET') !== false || strpos($output, 'POST') !== false) {
        echo "✅ $description exist\n";
    } else {
        echo "❌ $description missing or error\n";
    }
}
echo "\n";

// Test 4: Check Vue.js compilation
echo "🎨 Testing Frontend Build...\n";
if (file_exists('public/build/manifest.json')) {
    echo "✅ Frontend assets compiled successfully\n";
} else {
    echo "❌ Frontend assets not compiled. Run 'npm run build'\n";
}

// Check if critical Vue components can be parsed
$vueFiles = [
    'resources/js/pages/Students/Index.vue',
    'resources/js/pages/Teachers/Index.vue',
    'resources/js/pages/Guardians/Index.vue',
];

foreach ($vueFiles as $file) {
    if (file_exists($file)) {
        $content = file_get_contents($file);
        if (strpos($content, '<template>') !== false && strpos($content, '<script') !== false) {
            echo "✅ " . basename($file) . " has valid Vue structure\n";
        } else {
            echo "❌ " . basename($file) . " has invalid Vue structure\n";
        }
    }
}
echo "\n";

// Test 5: Check pagination fixes
echo "🔧 Testing Pagination Fixes...\n";
$paginationFiles = [
    'resources/js/pages/Students/Index.vue',
    'resources/js/pages/Teachers/Index.vue',
    'resources/js/pages/Guardians/Index.vue',
];

foreach ($paginationFiles as $file) {
    if (file_exists($file)) {
        $content = file_get_contents($file);
        if (strpos($content, 'v-if="link.url"') !== false && strpos($content, 'v-else') !== false) {
            echo "✅ " . basename($file) . " has pagination fix applied\n";
        } else {
            echo "❌ " . basename($file) . " missing pagination fix\n";
        }
    }
}
echo "\n";

// Test 6: Test API endpoints (if server is running)
echo "🌐 Testing API Endpoints...\n";
$testUrls = [
    'http://localhost:8000/login' => 'Login page',
    'http://localhost:8000/dashboard' => 'Dashboard (requires auth)',
    'http://localhost:8000/students' => 'Students page (requires auth)',
    'http://localhost:8000/teachers' => 'Teachers page (requires auth)',
];

foreach ($testUrls as $url => $description) {
    $context = stream_context_create([
        'http' => [
            'timeout' => 5,
            'ignore_errors' => true
        ]
    ]);
    
    $response = @file_get_contents($url, false, $context);
    if ($response !== false) {
        $httpCode = explode(' ', $http_response_header[0])[1];
        if ($httpCode == '200' || $httpCode == '302') {
            echo "✅ $description accessible (HTTP $httpCode)\n";
        } else {
            echo "⚠️  $description returned HTTP $httpCode\n";
        }
    } else {
        echo "❌ $description not accessible (server may not be running)\n";
    }
}
echo "\n";

// Test 7: Check configuration files
echo "⚙️  Testing Configuration...\n";
$configFiles = [
    '.env' => 'Environment configuration',
    'config/app.php' => 'Application configuration',
    'config/database.php' => 'Database configuration',
    'package.json' => 'Node.js dependencies',
    'composer.json' => 'PHP dependencies',
];

foreach ($configFiles as $file => $description) {
    if (file_exists($file)) {
        echo "✅ $description exists\n";
    } else {
        echo "❌ $description missing\n";
    }
}
echo "\n";

// Summary
echo "📋 Test Summary\n";
echo "=" . str_repeat("=", 60) . "\n";
echo "✅ File Structure: " . (empty($missingFiles) ? "PASS" : "FAIL") . "\n";
echo "✅ Database: " . (isset($pdo) ? "PASS" : "FAIL") . "\n";
echo "✅ Routes: Check individual results above\n";
echo "✅ Frontend: " . (file_exists('public/build/manifest.json') ? "PASS" : "NEEDS BUILD") . "\n";
echo "✅ Pagination Fixes: Check individual results above\n";
echo "✅ Configuration: Check individual results above\n";
echo "\n";

echo "🎯 Next Steps:\n";
echo "1. Run 'php artisan test' to execute backend tests\n";
echo "2. Run 'php artisan dusk' to execute frontend tests (requires Chrome)\n";
echo "3. Start server with 'php artisan serve' if not running\n";
echo "4. Run 'npm run build' if frontend assets need compilation\n";
echo "5. Access http://localhost:8000 to test manually\n";
echo "\n";

echo "🔐 Test Login Credentials:\n";
echo "Email: admin@example.com\n";
echo "Password: password\n";
echo "\n";

echo "✨ Test completed! Check results above for any issues.\n";
