<?php
session_start();
require_once '../../config/database.php';

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

// Log the request for debugging
error_log('Submit exam API called');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    error_log('User not logged in');
    echo json_encode(['success' => false, 'message' => 'অনুমোদন ব্যর্থ']);
    exit();
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_log('Invalid request method: ' . $_SERVER['REQUEST_METHOD']);
    echo json_encode(['success' => false, 'message' => 'অবৈধ অনুরোধ']);
    exit();
}

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Log received data for debugging
    error_log('Received input: ' . print_r($input, true));
    
    if (!$input || !isset($input['online_exam_id']) || !isset($input['answers'])) {
        error_log('Incomplete data received');
        echo json_encode(['success' => false, 'message' => 'অসম্পূর্ণ ডেটা']);
        exit();
    }
    
    $online_exam_id = (int)$input['online_exam_id'];
    $answers = $input['answers'];
    $user_id = $_SESSION['user_id'];
    
    // Validate exam exists
    $stmt = $pdo->prepare("SELECT * FROM online_exams WHERE id = ?");
    $stmt->execute([$online_exam_id]);
    $exam = $stmt->fetch();
    
    if (!$exam) {
        echo json_encode(['success' => false, 'message' => 'পরীক্ষা পাওয়া যায়নি']);
        exit();
    }
    
    // Get the actual student ID from the students table
    $stmt = $pdo->prepare("SELECT id FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        error_log("Student record not found for user_id: $user_id");
        echo json_encode(['success' => false, 'message' => 'শিক্ষার্থীর রেকর্ড পাওয়া যায়নি']);
        exit();
    }
    
    $student_id = $student['id'];
    error_log("Using student_id: $student_id for user_id: $user_id");
    
    // Process each answer
    foreach ($answers as $question_id => $answer) {
        error_log("Processing answer for question $question_id: " . (is_string($answer) ? $answer : json_encode($answer)));
        
        // Get question details
        $stmt = $pdo->prepare("SELECT * FROM online_exam_questions WHERE id = ? AND online_exam_id = ?");
        $stmt->execute([$question_id, $online_exam_id]);
        $question = $stmt->fetch();
        
        if (!$question) {
            error_log("Question $question_id not found");
            continue; // Skip if question not found
        }
        
        // Calculate marks
        $marks_obtained = 0;
        if ($question['question_type'] === 'mcq' && $answer === $question['correct_answer']) {
            $marks_obtained = $question['marks'];
        }
        
        // Determine if it's a selected option or written answer
        $selected_option = null;
        $written_answer = null;
        
        if ($question['question_type'] === 'mcq') {
            $selected_option = $answer;
        } else {
            $written_answer = is_string($answer) ? $answer : '';
        }
        
        error_log("Saving response: exam_id=$online_exam_id, student_id=$student_id, question_id=$question_id, option=$selected_option, written_answer=" . ($written_answer ? substr($written_answer, 0, 50) : 'null') . ", marks=$marks_obtained");
        
        // Save response to database
        $stmt = $pdo->prepare("INSERT INTO online_exam_student_responses (online_exam_id, student_id, question_id, selected_option, written_answer, marks_obtained) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE selected_option = VALUES(selected_option), written_answer = VALUES(written_answer), marks_obtained = VALUES(marks_obtained)");
        $result = $stmt->execute([$online_exam_id, $student_id, $question_id, $selected_option, $written_answer, $marks_obtained]);
        
        if ($result) {
            error_log("Response saved successfully for question $question_id");
        } else {
            error_log("Failed to save response for question $question_id");
        }
    }
    
    echo json_encode(['success' => true, 'message' => 'পরীক্ষা সফলভাবে জমা হয়েছে!']);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'ত্রুটি: ' . $e->getMessage()]);
}
?>