<?php

/**
 * Test Enhanced Subject Delete Functionality
 * This script tests the improved delete validation that checks for all relationships
 */

echo "🔧 TESTING ENHANCED SUBJECT DELETE FUNCTIONALITY\n";
echo "=" . str_repeat("=", 60) . "\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 subjects and their relationships
try {
    echo "\n📊 ANALYZING SUBJECT RELATIONSHIPS...\n";
    echo "-" . str_repeat("-", 50) . "\n";
    
    $stmt = $pdo->query("
        SELECT 
            s.id,
            s.name,
            s.code,
            COUNT(DISTINCT r.id) as results_count,
            COUNT(DISTINCT cs.classroom_id) as classroom_count,
            COUNT(DISTINCT ts.teacher_id) as teacher_count
        FROM subjects s
        LEFT JOIN results r ON s.id = r.subject_id
        LEFT JOIN classroom_subjects cs ON s.id = cs.subject_id
        LEFT JOIN teacher_subjects ts ON s.id = ts.subject_id
        GROUP BY s.id, s.name, s.code
        ORDER BY results_count ASC, classroom_count ASC, teacher_count ASC
    ");
    
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $deletableSubjects = [];
    $protectedSubjects = [];
    
    foreach ($subjects as $subject) {
        $canDelete = ($subject['results_count'] == 0 && 
                     $subject['classroom_count'] == 0 && 
                     $subject['teacher_count'] == 0);
        
        if ($canDelete) {
            $deletableSubjects[] = $subject;
            echo "✅ DELETABLE: {$subject['name']} (ID: {$subject['id']})\n";
            echo "   - Results: {$subject['results_count']}\n";
            echo "   - Classrooms: {$subject['classroom_count']}\n";
            echo "   - Teachers: {$subject['teacher_count']}\n\n";
        } else {
            $protectedSubjects[] = $subject;
            $reasons = [];
            if ($subject['results_count'] > 0) $reasons[] = "has {$subject['results_count']} results";
            if ($subject['classroom_count'] > 0) $reasons[] = "assigned to {$subject['classroom_count']} classrooms";
            if ($subject['teacher_count'] > 0) $reasons[] = "assigned to {$subject['teacher_count']} teachers";
            
            echo "🛡️  PROTECTED: {$subject['name']} (ID: {$subject['id']}) - " . implode(', ', $reasons) . "\n";
        }
    }
    
    echo "\n📈 SUMMARY:\n";
    echo "   - Deletable subjects: " . count($deletableSubjects) . "\n";
    echo "   - Protected subjects: " . count($protectedSubjects) . "\n\n";
    
} catch (PDOException $e) {
    echo "❌ Database query failed: " . $e->getMessage() . "\n";
    exit(1);
}

// 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";

// Check if the enhanced validation is in the controller
echo "🎮 Checking Enhanced SubjectController Validation...\n";

$controllerFile = 'Modules/Academic/app/Http/Controllers/SubjectController.php';
if (file_exists($controllerFile)) {
    $content = file_get_contents($controllerFile);
    
    // Check for all validation types
    $hasResultsCheck = strpos($content, 'results()->exists()') !== false;
    $hasClassroomsCheck = strpos($content, 'classrooms()->exists()') !== false;
    $hasTeachersCheck = strpos($content, 'teachers()->exists()') !== false;
    
    echo $hasResultsCheck ? "✅ Results validation exists\n" : "❌ Results validation missing\n";
    echo $hasClassroomsCheck ? "✅ Classrooms validation exists\n" : "❌ Classrooms validation missing\n";
    echo $hasTeachersCheck ? "✅ Teachers validation exists\n" : "❌ Teachers validation missing\n";
    
    // Check for specific error messages
    $hasClassroomError = strpos($content, 'assigned to classrooms') !== false;
    $hasTeacherError = strpos($content, 'assigned to teachers') !== false;
    
    echo $hasClassroomError ? "✅ Classroom assignment error message exists\n" : "❌ Classroom assignment error message missing\n";
    echo $hasTeacherError ? "✅ Teacher assignment error message exists\n" : "❌ Teacher assignment error message missing\n";
    
} else {
    echo "❌ SubjectController file not found\n";
}

echo "\n";

echo "📋 MANUAL TESTING INSTRUCTIONS\n";
echo "=" . str_repeat("=", 60) . "\n";

if ($serverRunning) {
    echo "🎯 ENHANCED TESTING STEPS:\n\n";
    
    echo "1. **Go to Subjects Page**:\n";
    echo "   URL: http://localhost:8000/subjects\n\n";
    
    if (count($deletableSubjects) > 0) {
        echo "2. **Test Delete on DELETABLE Subject**:\n";
        $deletable = $deletableSubjects[0];
        echo "   - Find subject: '{$deletable['name']}' (ID: {$deletable['id']})\n";
        echo "   - Click the dropdown menu (⋮ or ...)\n";
        echo "   - Click 'Delete'\n";
        echo "   - Confirm deletion in the dialog\n";
        echo "   - ✅ EXPECTED: Subject should be deleted successfully\n\n";
    } else {
        echo "2. **No Deletable Subjects Available**:\n";
        echo "   - All subjects have relationships that prevent deletion\n";
        echo "   - This is normal for a system with sample data\n\n";
    }
    
    if (count($protectedSubjects) > 0) {
        echo "3. **Test Delete on PROTECTED Subjects**:\n\n";
        
        // Find subjects with different protection reasons
        $subjectWithResults = null;
        $subjectWithClassrooms = null;
        $subjectWithTeachers = null;
        
        foreach ($protectedSubjects as $subject) {
            if ($subject['results_count'] > 0 && !$subjectWithResults) {
                $subjectWithResults = $subject;
            }
            if ($subject['classroom_count'] > 0 && !$subjectWithClassrooms) {
                $subjectWithClassrooms = $subject;
            }
            if ($subject['teacher_count'] > 0 && !$subjectWithTeachers) {
                $subjectWithTeachers = $subject;
            }
        }
        
        if ($subjectWithResults) {
            echo "   a) **Subject with Results**:\n";
            echo "      - Subject: '{$subjectWithResults['name']}' (ID: {$subjectWithResults['id']})\n";
            echo "      - Try to delete it\n";
            echo "      - ❌ EXPECTED: 'Cannot delete subject with existing results.'\n\n";
        }
        
        if ($subjectWithClassrooms) {
            echo "   b) **Subject assigned to Classrooms**:\n";
            echo "      - Subject: '{$subjectWithClassrooms['name']}' (ID: {$subjectWithClassrooms['id']})\n";
            echo "      - Try to delete it\n";
            echo "      - ❌ EXPECTED: 'Cannot delete subject that is assigned to classrooms.'\n\n";
        }
        
        if ($subjectWithTeachers) {
            echo "   c) **Subject assigned to Teachers**:\n";
            echo "      - Subject: '{$subjectWithTeachers['name']}' (ID: {$subjectWithTeachers['id']})\n";
            echo "      - Try to delete it\n";
            echo "      - ❌ EXPECTED: 'Cannot delete subject that is assigned to teachers.'\n\n";
        }
    }
    
    echo "4. **What to Look For**:\n";
    echo "   ✅ Delete button appears in dropdown menu\n";
    echo "   ✅ Confirmation dialog appears when clicking delete\n";
    echo "   ✅ Appropriate error messages for different protection reasons\n";
    echo "   ✅ Successful deletion only for unassigned subjects\n";
    echo "   ✅ No JavaScript errors in browser console\n";
    echo "   ✅ Page refreshes/updates after deletion attempts\n\n";
    
} else {
    echo "⚠️  Start the server first: php artisan serve\n\n";
}

echo "🔧 ENHANCEMENTS APPLIED:\n";
echo "- Added classroom assignment validation\n";
echo "- Added teacher assignment validation\n";
echo "- Added specific error messages for each protection type\n";
echo "- Maintained existing results validation\n";
echo "- Proper transaction handling for all checks\n\n";

echo "🎯 VALIDATION HIERARCHY:\n";
echo "1. Check for existing results (highest priority)\n";
echo "2. Check for classroom assignments\n";
echo "3. Check for teacher assignments\n";
echo "4. Only delete if all checks pass\n\n";

echo "✨ Enhanced subject delete functionality test completed!\n";
echo "The delete button now properly validates ALL relationships.\n";
