<?php

/**
 * Test Subject Relationship Fix
 * This script tests if the subject view page works after fixing the relationship issue
 */

echo "🔧 TESTING SUBJECT RELATIONSHIP FIX\n";
echo "=" . str_repeat("=", 50) . "\n\n";

// Test database connection
try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=schoolapp', 'root', '');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "✅ Database connection successful\n";
} catch (PDOException $e) {
    echo "❌ Database connection failed: " . $e->getMessage() . "\n";
    exit(1);
}

// Check if subjects table exists and has data
try {
    $stmt = $pdo->query("SELECT COUNT(*) FROM subjects");
    $subjectCount = $stmt->fetchColumn();
    echo "✅ Subjects table: $subjectCount records\n";
    
    if ($subjectCount > 0) {
        // Get a sample subject
        $stmt = $pdo->query("SELECT * FROM subjects LIMIT 1");
        $subject = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "✅ Sample subject found: {$subject['name']} (ID: {$subject['id']})\n";
        
        // Check if subject has any classroom relationships
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM classroom_subjects WHERE subject_id = ?");
        $stmt->execute([$subject['id']]);
        $classroomCount = $stmt->fetchColumn();
        echo "✅ Subject has $classroomCount classroom relationships\n";
        
        // Check if subject has any teacher relationships
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM teacher_subjects WHERE subject_id = ?");
        $stmt->execute([$subject['id']]);
        $teacherCount = $stmt->fetchColumn();
        echo "✅ Subject has $teacherCount teacher relationships\n";
        
    } else {
        echo "❌ No subjects found in database\n";
    }
    
} catch (PDOException $e) {
    echo "❌ Database query failed: " . $e->getMessage() . "\n";
}

echo "\n";

// Test if server is running
$serverRunning = false;
$context = stream_context_create([
    'http' => [
        'timeout' => 5,
        'ignore_errors' => true
    ]
]);

echo "🌐 Testing server accessibility...\n";
$response = @file_get_contents('http://localhost:8000/login', false, $context);
if ($response !== false) {
    echo "✅ Server is running on localhost:8000\n";
    $serverRunning = true;
} else {
    echo "❌ Server is not running on localhost:8000\n";
    echo "Please start the server with: php artisan serve\n";
}

echo "\n";

if ($serverRunning) {
    echo "🧪 Testing Subject Pages...\n";
    
    // Test subjects index page
    $indexResponse = @file_get_contents('http://localhost:8000/subjects', false, $context);
    if ($indexResponse !== false) {
        echo "✅ Subjects index page loads successfully\n";
    } else {
        echo "❌ Subjects index page failed to load\n";
    }
    
    // Test subject show page (the one that was failing)
    $showResponse = @file_get_contents('http://localhost:8000/subjects/1', false, $context);
    if ($showResponse !== false) {
        echo "✅ Subject show page loads successfully (FIXED!)\n";
        
        // Check if the response contains expected content
        if (strpos($showResponse, 'Subject Details') !== false || strpos($showResponse, 'subject') !== false) {
            echo "✅ Subject show page contains expected content\n";
        } else {
            echo "⚠️  Subject show page loads but may not have expected content\n";
        }
    } else {
        echo "❌ Subject show page still failing to load\n";
    }
    
    // Test subject edit page
    $editResponse = @file_get_contents('http://localhost:8000/subjects/1/edit', false, $context);
    if ($editResponse !== false) {
        echo "✅ Subject edit page loads successfully\n";
    } else {
        echo "❌ Subject edit page failed to load\n";
    }
}

echo "\n";

// Check if the Subject model relationships are correct
echo "📋 Checking Subject Model Relationships...\n";

$subjectModelFile = 'Modules/Academic/app/Models/Subject.php';
if (file_exists($subjectModelFile)) {
    $content = file_get_contents($subjectModelFile);
    
    // Check for correct relationships
    $hasClassroomsRelation = strpos($content, 'public function classrooms()') !== false;
    $hasTeachersRelation = strpos($content, 'public function teachers()') !== false;
    $hasResultsRelation = strpos($content, 'public function results()') !== false;
    
    echo "✅ Subject model exists\n";
    echo $hasClassroomsRelation ? "✅ classrooms() relationship exists\n" : "❌ classrooms() relationship missing\n";
    echo $hasTeachersRelation ? "✅ teachers() relationship exists\n" : "❌ teachers() relationship missing\n";
    echo $hasResultsRelation ? "✅ results() relationship exists\n" : "❌ results() relationship missing\n";
    
    // Check that there's no incorrect 'classroom' (singular) relationship
    $hasIncorrectClassroomRelation = strpos($content, 'public function classroom()') !== false;
    if ($hasIncorrectClassroomRelation) {
        echo "⚠️  Found incorrect classroom() (singular) relationship - should be removed\n";
    } else {
        echo "✅ No incorrect classroom() (singular) relationship found\n";
    }
    
} else {
    echo "❌ Subject model file not found\n";
}

echo "\n";

// Check if the controller was fixed
echo "🎮 Checking SubjectController Fix...\n";

$controllerFile = 'Modules/Academic/app/Http/Controllers/SubjectController.php';
if (file_exists($controllerFile)) {
    $content = file_get_contents($controllerFile);
    
    // Check if the problematic lines were fixed
    $hasClassroomLoad = strpos($content, "'classroom.academicYear'") !== false;
    $hasClassroomsLoad = strpos($content, "'classrooms.academicYear'") !== false;
    
    echo "✅ SubjectController exists\n";
    
    if ($hasClassroomLoad) {
        echo "⚠️  Still has incorrect 'classroom.academicYear' load\n";
    } else {
        echo "✅ Removed incorrect 'classroom.academicYear' load\n";
    }
    
    if ($hasClassroomsLoad) {
        echo "✅ Has correct 'classrooms.academicYear' load\n";
    } else {
        echo "⚠️  Missing correct 'classrooms.academicYear' load\n";
    }
    
} else {
    echo "❌ SubjectController file not found\n";
}

echo "\n";

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

if ($serverRunning) {
    echo "🎯 MANUAL TESTING:\n";
    echo "1. Go to: http://localhost:8000/subjects\n";
    echo "2. Click on any subject name to view details\n";
    echo "3. Verify the page loads without the 'classroom' relationship error\n";
    echo "4. Test the edit functionality\n";
    echo "5. Check browser console for any JavaScript errors\n\n";
} else {
    echo "⚠️  Start the server first: php artisan serve\n\n";
}

echo "🔧 FIXES APPLIED:\n";
echo "- Changed 'classroom' to 'classrooms' in Subject relationships\n";
echo "- Fixed SubjectController show() method\n";
echo "- Fixed SubjectController edit() method\n";
echo "- Fixed getSubjectsForClassroom() method\n";
echo "- Fixed assignTeacher() method to use many-to-many relationship\n\n";

echo "✨ Subject relationship fix test completed!\n";
