<?php
require_once 'config/database.php';

try {
    // First, let's check what students exist
    $stmt = $pdo->query("SELECT id, student_id, first_name, last_name FROM students LIMIT 5");
    $students = $stmt->fetchAll();
    
    echo "Available students:\n";
    foreach ($students as $student) {
        echo "ID: " . $student['id'] . " | Student ID: " . $student['student_id'] . " | Name: " . $student['first_name'] . " " . $student['last_name'] . "\n";
    }
    
    if (count($students) > 0) {
        $valid_student_id = $students[0]['id'];
        echo "\nUsing valid student ID: $valid_student_id for testing\n";
        
        // Now test inserting a response with this valid student ID
        $online_exam_id = 1;
        $question_id = 14; // We know this exists from our previous tests
        $selected_option = 'A';
        $marks_obtained = 1;
        
        echo "Attempting to insert response with valid student ID...\n";
        
        // Try to insert a response
        $stmt = $pdo->prepare("INSERT INTO online_exam_student_responses (online_exam_id, student_id, question_id, selected_option, marks_obtained) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE selected_option = VALUES(selected_option), marks_obtained = VALUES(marks_obtained)");
        $result = $stmt->execute([$online_exam_id, $valid_student_id, $question_id, $selected_option, $marks_obtained]);
        
        if ($result) {
            echo "Successfully inserted response with valid student ID!\n";
            
            // Clean up - delete the test record
            $stmt = $pdo->prepare("DELETE FROM online_exam_student_responses WHERE online_exam_id = ? AND student_id = ? AND question_id = ?");
            $stmt->execute([$online_exam_id, $valid_student_id, $question_id]);
            echo "Cleaned up test record.\n";
        } else {
            echo "Failed to insert response even with valid student ID.\n";
        }
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>