<?php

/**
 * Test Subject Delete Functionality
 * This script tests if the subject delete button is working properly
 */

echo "🗑️  TESTING 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 current subjects count
try {
    $stmt = $pdo->query("SELECT COUNT(*) FROM subjects");
    $totalSubjects = $stmt->fetchColumn();
    echo "✅ Total subjects in database: $totalSubjects\n";
    
    // Get subjects with and without results
    $stmt = $pdo->query("
        SELECT s.*, COUNT(r.id) as results_count 
        FROM subjects s 
        LEFT JOIN results r ON s.id = r.subject_id 
        GROUP BY s.id 
        ORDER BY results_count ASC
    ");
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "📊 Subject breakdown:\n";
    $subjectsWithoutResults = 0;
    $subjectsWithResults = 0;
    
    foreach ($subjects as $subject) {
        if ($subject['results_count'] == 0) {
            $subjectsWithoutResults++;
            echo "   ✅ {$subject['name']} (ID: {$subject['id']}) - {$subject['results_count']} results (DELETABLE)\n";
        } else {
            $subjectsWithResults++;
            echo "   ⚠️  {$subject['name']} (ID: {$subject['id']}) - {$subject['results_count']} results (PROTECTED)\n";
        }
    }
    
    echo "\n📈 Summary:\n";
    echo "   - Subjects without results (deletable): $subjectsWithoutResults\n";
    echo "   - Subjects with results (protected): $subjectsWithResults\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";

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";
        
        // Check if the response contains the delete functionality
        if (strpos($indexResponse, 'Delete') !== false) {
            echo "✅ Delete button appears in the page\n";
        } else {
            echo "⚠️  Delete button may not be visible\n";
        }
        
    } else {
        echo "❌ Subjects index page failed to load\n";
    }
}

echo "\n";

// Check if the SubjectController destroy method exists and is properly implemented
echo "🎮 Checking SubjectController Delete Method...\n";

$controllerFile = 'Modules/Academic/app/Http/Controllers/SubjectController.php';
if (file_exists($controllerFile)) {
    $content = file_get_contents($controllerFile);
    
    // Check for destroy method
    $hasDestroyMethod = strpos($content, 'public function destroy(') !== false;
    echo $hasDestroyMethod ? "✅ destroy() method exists\n" : "❌ destroy() method missing\n";
    
    // Check for results validation
    $hasResultsCheck = strpos($content, 'results()->exists()') !== false;
    echo $hasResultsCheck ? "✅ Results validation exists\n" : "❌ Results validation missing\n";
    
    // Check for proper error handling
    $hasErrorHandling = strpos($content, 'DB::beginTransaction()') !== false && strpos($content, 'DB::rollBack()') !== false;
    echo $hasErrorHandling ? "✅ Transaction handling exists\n" : "❌ Transaction handling missing\n";
    
} else {
    echo "❌ SubjectController file not found\n";
}

echo "\n";

// Check if the Vue component has the delete function
echo "🎨 Checking Vue Component Delete Function...\n";

$vueFile = 'resources/js/pages/Academic/Subjects/Index.vue';
if (file_exists($vueFile)) {
    $content = file_get_contents($vueFile);
    
    // Check for delete click handler
    $hasDeleteClick = strpos($content, '@click="deleteSubject') !== false;
    echo $hasDeleteClick ? "✅ Delete click handler exists\n" : "❌ Delete click handler missing\n";
    
    // Check for delete function
    $hasDeleteFunction = strpos($content, 'const deleteSubject') !== false;
    echo $hasDeleteFunction ? "✅ deleteSubject function exists\n" : "❌ deleteSubject function missing\n";
    
    // Check for confirmation dialog
    $hasConfirmation = strpos($content, 'confirm(') !== false;
    echo $hasConfirmation ? "✅ Confirmation dialog exists\n" : "❌ Confirmation dialog missing\n";
    
    // Check for router.delete call
    $hasRouterDelete = strpos($content, 'router.delete(') !== false;
    echo $hasRouterDelete ? "✅ Router delete call exists\n" : "❌ Router delete call missing\n";
    
} else {
    echo "❌ Vue component file not found\n";
}

echo "\n";

// Check if routes exist
echo "🛣️  Checking Delete Route...\n";
$routeOutput = shell_exec('php artisan route:list --name=subjects.destroy 2>&1');
if (strpos($routeOutput, 'DELETE') !== false) {
    echo "✅ subjects.destroy route exists\n";
} else {
    echo "❌ subjects.destroy route missing\n";
}

echo "\n";

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

if ($serverRunning) {
    echo "🎯 TESTING STEPS:\n\n";
    
    echo "1. **Go to Subjects Page**:\n";
    echo "   URL: http://localhost:8000/subjects\n\n";
    
    echo "2. **Test Delete on Subject WITHOUT Results**:\n";
    if ($subjectsWithoutResults > 0) {
        $deletableSubject = null;
        foreach ($subjects as $subject) {
            if ($subject['results_count'] == 0) {
                $deletableSubject = $subject;
                break;
            }
        }
        if ($deletableSubject) {
            echo "   - Find subject: '{$deletableSubject['name']}' (ID: {$deletableSubject['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 "   - No subjects without results available for testing\n\n";
    }
    
    echo "3. **Test Delete on Subject WITH Results**:\n";
    if ($subjectsWithResults > 0) {
        $protectedSubject = null;
        foreach ($subjects as $subject) {
            if ($subject['results_count'] > 0) {
                $protectedSubject = $subject;
                break;
            }
        }
        if ($protectedSubject) {
            echo "   - Find subject: '{$protectedSubject['name']}' (ID: {$protectedSubject['id']})\n";
            echo "   - Click the dropdown menu (⋮ or ...)\n";
            echo "   - Click 'Delete'\n";
            echo "   - Confirm deletion in the dialog\n";
            echo "   - ❌ EXPECTED: Should show error 'Cannot delete subject with existing results'\n\n";
        }
    } else {
        echo "   - No subjects with results available for testing\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 "   ✅ Successful deletion removes subject from list\n";
    echo "   ✅ Error message appears for protected subjects\n";
    echo "   ✅ No JavaScript errors in browser console\n";
    echo "   ✅ Page refreshes/updates after deletion\n\n";
    
} else {
    echo "⚠️  Start the server first: php artisan serve\n\n";
}

echo "🔧 FIXES APPLIED:\n";
echo "- Added @click handler to delete button\n";
echo "- Implemented deleteSubject() function\n";
echo "- Added confirmation dialog\n";
echo "- Added proper error handling\n";
echo "- Added router.delete() call with success/error callbacks\n";
echo "- Rebuilt frontend assets\n\n";

echo "✨ Subject delete functionality test completed!\n";
echo "The delete button should now work properly.\n";
