<?php
// student/save_answer.php - AJAX Handler for All Question Types
require_once '../config/config.php';

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

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

$student_exam_id = $_POST['student_exam_id'] ?? null;
$question_id = $_POST['question_id'] ?? null;
$selected_answer = $_POST['selected_answer'] ?? null;
$answer_text = $_POST['answer_text'] ?? null;
$marked_for_review = isset($_POST['marked_for_review']) ? intval($_POST['marked_for_review']) : 0;

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

try {
    // Build dynamic update query based on what's provided
    $updates = [];
    $params = [];
    
    // Handle selected_answer (for MCQ, True/False, Fill in Blank)
    if (isset($_POST['selected_answer'])) {
        $updates[] = "selected_answer = ?";
        $params[] = $selected_answer;
    }
    
    // Handle answer_text (for Essay, Short Answer)
    if (isset($_POST['answer_text'])) {
        $updates[] = "answer_text = ?";
        $params[] = $answer_text;
    }
    
    // Handle marked_for_review
    if ($marked_for_review) {
        $updates[] = "marked_for_review = ?";
        $params[] = $marked_for_review;
    }
    
    // If no updates, just return success
    if (empty($updates)) {
        echo json_encode([
            'success' => true, 
            'message' => 'No changes to save'
        ]);
        exit;
    }
    
    // Add WHERE clause params
    $params[] = $student_exam_id;
    $params[] = $question_id;
    
    $sql = "UPDATE student_answers SET " . implode(", ", $updates) . " WHERE student_exam_id = ? AND question_id = ?";
    
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute($params);
    
    if ($result) {
        // Check if row was actually updated or if it just didn't exist
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'success' => true, 
                'message' => 'Answer saved successfully',
                'rows_affected' => $stmt->rowCount()
            ]);
        } else {
            // Try to check if record exists
            $check = $pdo->prepare("SELECT id FROM student_answers WHERE student_exam_id = ? AND question_id = ?");
            $check->execute([$student_exam_id, $question_id]);
            
            if ($check->fetch()) {
                // Record exists but values were the same
                echo json_encode([
                    'success' => true, 
                    'message' => 'Answer saved (no changes)',
                    'rows_affected' => 0
                ]);
            } else {
                // Record doesn't exist - create it
                $insert_sql = "INSERT INTO student_answers (student_exam_id, question_id, selected_answer, answer_text, marked_for_review) VALUES (?, ?, ?, ?, ?)";
                $insert_stmt = $pdo->prepare($insert_sql);
                $insert_result = $insert_stmt->execute([
                    $student_exam_id, 
                    $question_id, 
                    $selected_answer, 
                    $answer_text, 
                    $marked_for_review
                ]);
                
                if ($insert_result) {
                    echo json_encode([
                        'success' => true, 
                        'message' => 'Answer created successfully',
                        'rows_affected' => 1
                    ]);
                } else {
                    echo json_encode([
                        'success' => false, 
                        'error' => 'Failed to create answer record'
                    ]);
                }
            }
        }
    } else {
        echo json_encode([
            'success' => false, 
            'error' => 'Database update failed'
        ]);
    }
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false, 
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}