<?php

/**
 * Debug Subject Delete Error Display
 * This script will help us understand why errors aren't showing
 */

echo "🔍 DEBUGGING SUBJECT DELETE ERROR DISPLAY\n";
echo "=" . str_repeat("=", 60) . "\n\n";

// Test what happens when we simulate the delete process
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);
}

// Get a subject with relationships to test
try {
    $stmt = $pdo->query("
        SELECT 
            s.id,
            s.name,
            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
        WHERE s.id = 1
        GROUP BY s.id, s.name
    ");
    
    $subject = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($subject) {
        echo "📚 Testing with subject: {$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 {
        echo "❌ No subject found with ID 1\n";
        exit(1);
    }
    
} catch (PDOException $e) {
    echo "❌ Database query failed: " . $e->getMessage() . "\n";
    exit(1);
}

// Test the actual delete route
echo "🌐 Testing DELETE route...\n";

$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => [
            'Content-Type: application/x-www-form-urlencoded',
            'X-Requested-With: XMLHttpRequest',
            'Accept: application/json'
        ],
        'content' => '_method=DELETE&_token=test',
        'timeout' => 10,
        'ignore_errors' => true
    ]
]);

$deleteUrl = "http://localhost:8000/subjects/{$subject['id']}";
$response = @file_get_contents($deleteUrl, false, $context);

if ($response !== false) {
    echo "✅ DELETE request completed\n";
    echo "Response: " . substr($response, 0, 500) . "...\n\n";
    
    // Check response headers
    if (isset($http_response_header)) {
        echo "📋 Response Headers:\n";
        foreach ($http_response_header as $header) {
            echo "   $header\n";
        }
        echo "\n";
    }
} else {
    echo "❌ DELETE request failed\n\n";
}

// Check if the Vue component is correctly accessing the error
echo "🎨 Checking Vue Component Error Access...\n";

$vueFile = 'resources/js/pages/Academic/Subjects/Index.vue';
if (file_exists($vueFile)) {
    $content = file_get_contents($vueFile);
    
    // Look for different ways errors might be accessed
    $errorPatterns = [
        '$page.props.errors.error' => strpos($content, '$page.props.errors.error') !== false,
        '$page.props.flash.error' => strpos($content, '$page.props.flash.error') !== false,
        'errors.error' => strpos($content, 'errors.error') !== false,
        'flash.error' => strpos($content, 'flash.error') !== false,
    ];
    
    echo "Error access patterns found:\n";
    foreach ($errorPatterns as $pattern => $found) {
        echo $found ? "✅ $pattern\n" : "❌ $pattern\n";
    }
    echo "\n";
    
    // Check the exact error display code
    $lines = explode("\n", $content);
    $errorDisplayLines = [];
    
    for ($i = 0; $i < count($lines); $i++) {
        if (strpos($lines[$i], 'errors.error') !== false || strpos($lines[$i], 'flash') !== false) {
            $start = max(0, $i - 2);
            $end = min(count($lines) - 1, $i + 2);
            
            for ($j = $start; $j <= $end; $j++) {
                $errorDisplayLines[] = sprintf("%3d: %s", $j + 1, $lines[$j]);
            }
            $errorDisplayLines[] = "---";
        }
    }
    
    if (!empty($errorDisplayLines)) {
        echo "📄 Error display code in Vue component:\n";
        foreach ($errorDisplayLines as $line) {
            echo "$line\n";
        }
        echo "\n";
    }
    
} else {
    echo "❌ Vue component file not found\n\n";
}

// Check what the HandleInertiaRequests middleware is actually sharing
echo "🔧 Checking HandleInertiaRequests Middleware...\n";

$middlewareFile = 'app/Http/Middleware/HandleInertiaRequests.php';
if (file_exists($middlewareFile)) {
    $content = file_get_contents($middlewareFile);
    
    // Extract the share method
    $lines = explode("\n", $content);
    $shareMethodLines = [];
    $inShareMethod = false;
    
    for ($i = 0; $i < count($lines); $i++) {
        if (strpos($lines[$i], 'public function share(') !== false) {
            $inShareMethod = true;
        }
        
        if ($inShareMethod) {
            $shareMethodLines[] = sprintf("%3d: %s", $i + 1, $lines[$i]);
            
            if (strpos($lines[$i], '}') !== false && strpos($lines[$i], 'return') === false) {
                break;
            }
        }
    }
    
    if (!empty($shareMethodLines)) {
        echo "📄 HandleInertiaRequests share method:\n";
        foreach ($shareMethodLines as $line) {
            echo "$line\n";
        }
        echo "\n";
    }
    
} else {
    echo "❌ HandleInertiaRequests middleware file not found\n\n";
}

// Test what Laravel session actually contains after an error
echo "🧪 Testing Laravel Session Error Structure...\n";

// Create a simple test to see how Laravel stores errors
$testScript = '
<?php
require_once "vendor/autoload.php";

$app = require_once "bootstrap/app.php";
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

// Simulate what happens when we call back()->withErrors()
$request = new Illuminate\Http\Request();
$session = app("session");

// Test different error formats
$session->flash("errors", new Illuminate\Support\ViewErrorBag([
    "default" => new Illuminate\Support\MessageBag([
        "error" => ["Cannot delete subject with existing results."]
    ])
]));

echo "Session errors structure:\n";
var_dump($session->get("errors"));

echo "\nErrors bag messages:\n";
$errors = $session->get("errors");
if ($errors) {
    var_dump($errors->getBag("default")->getMessages());
}
';

file_put_contents('test-session-errors.php', $testScript);

echo "Running Laravel session test...\n";
$sessionOutput = shell_exec('php test-session-errors.php 2>&1');
echo $sessionOutput . "\n";

// Clean up
unlink('test-session-errors.php');

echo "🎯 DEBUGGING SUMMARY\n";
echo "=" . str_repeat("=", 60) . "\n";

echo "Based on the debugging above, the issue might be:\n\n";

echo "1. **Error Structure Mismatch**:\n";
echo "   - Vue component expects: \$page.props.errors.error[0]\n";
echo "   - Laravel might be providing a different structure\n\n";

echo "2. **Session Flash vs Validation Errors**:\n";
echo "   - withErrors() creates validation errors\n";
echo "   - with('error', 'message') creates flash messages\n";
echo "   - These are handled differently by Inertia\n\n";

echo "3. **Inertia Response Type**:\n";
echo "   - DELETE requests might not preserve errors the same way\n";
echo "   - May need to use redirect()->back() instead of back()\n\n";

echo "📋 NEXT STEPS TO TRY:\n";
echo "1. Change withErrors() to with('error', 'message')\n";
echo "2. Update Vue component to check \$page.props.flash.error\n";
echo "3. Use redirect()->back() instead of back()\n";
echo "4. Add console.log to Vue component to see actual props structure\n\n";

echo "✨ Debugging completed! Please try the suggested fixes.\n";
