<?php
// student/save_answer.php - AJAX Handler
require_once '../config/config.php';

// Set JSON header
header('Content-Type: application/json');

// Debug logging (remove after testing)
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("POST Data: " . print_r($_POST, true));

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'success' => false, 
        'error' => 'Invalid request method',
        'method_received' => $_SERVER['REQUEST_METHOD']
    ]);
    exit;
}

// Get POST parameters
$student_exam_id = $_POST['student_exam_id'] ?? null;
$question_id = $_POST['question_id'] ?? null;
$selected_answer = $_POST['selected_answer'] ?? null;
$marked_for_review = isset($_POST['marked_for_review']) ? intval($_POST['marked_for_review']) : 0;

// Validate required parameters
if (!$student_exam_id || !$question_id) {
    echo json_encode([
        'success' => false, 
        'error' => 'Missing required parameters',
        'received' => $_POST
    ]);
    exit;
}

try {
    // Update answer in database
    $stmt = $pdo->prepare("
        UPDATE student_answers 
        SET selected_answer = ?, 
            marked_for_review = ?
        WHERE student_exam_id = ? 
        AND question_id = ?
    ");
    
    $result = $stmt->execute([
        $selected_answer, 
        $marked_for_review, 
        $student_exam_id, 
        $question_id
    ]);
    
    if ($result && $stmt->rowCount() > 0) {
        echo json_encode([
            'success' => true, 
            'message' => 'Answer saved successfully',
            'rows_affected' => $stmt->rowCount()
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'message' => 'No rows updated - check if record exists',
            'rows_affected' => 0,
            'debug' => [
                'student_exam_id' => $student_exam_id,
                'question_id' => $question_id,
                'selected_answer' => $selected_answer
            ]
        ]);
    }
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false, 
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}
?>