<?php
include 'db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate input
    if (!isset($_POST['user_id'], $_POST['topic_id'], $_POST['answers'])) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid input.']);
        exit;
    }

    $user_id = $_POST['user_id'];
    $topic_id = $_POST['topic_id'];
    $answers = json_decode($_POST['answers'], true);

    try {
        // Check if the quiz has already been attempted
        $stmt = $pdo->prepare("SELECT score, total_questions FROM user_quizzes WHERE user_id = ? AND topic_id = ?");
        $stmt->execute([$user_id, $topic_id]);
        $existingAttempt = $stmt->fetch();

        if ($existingAttempt) {
            echo json_encode([
                'status' => 'exists',
                'score' => $existingAttempt['score'],
                'total_questions' => $existingAttempt['total_questions'],
                'message' => 'Quiz already attempted.'
            ]);
            exit;
        }

        // Calculate score and store the quiz attempt
        $score = 0;
        $total_questions = count($answers);
        $pdo->beginTransaction();

        foreach ($answers as $answer) {
            $question_id = $answer['question_id'];
            $selected_option_id = $answer['selected_option_id'];

            $stmt = $pdo->prepare("SELECT is_correct FROM options WHERE id = ?");
            $stmt->execute([$selected_option_id]);
            $option = $stmt->fetch();

            if ($option && $option['is_correct']) {
                $score++;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO user_quizzes (user_id, topic_id, score, total_questions) VALUES (?, ?, ?, ?)");
        $stmt->execute([$user_id, $topic_id, $score, $total_questions]);

        $user_quiz_id = $pdo->lastInsertId();

        foreach ($answers as $answer) {
            $stmt = $pdo->prepare("INSERT INTO user_answers (user_quiz_id, question_id, selected_option_id) VALUES (?, ?, ?)");
            $stmt->execute([$user_quiz_id, $answer['question_id'], $answer['selected_option_id']]);
        }

        $pdo->commit();

        // Fetch user details (email, name, category)
        $stmt = $pdo->prepare("SELECT email, name, category_id FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();

        // Fetch the category name using category_id
        $stmt = $pdo->prepare("SELECT name FROM categories WHERE id = ?");
        $stmt->execute([$user['category_id']]);
        $category = $stmt->fetch();

        // Fetch the topic name
        $stmt = $pdo->prepare("SELECT name FROM topics WHERE id = ?");
        $stmt->execute([$topic_id]);
        $topic = $stmt->fetch();

        // Send data to Airtable
        $airtableData = [
            'fields' => [
                'User Email' => $user['email'],
                'User Name' => $user['name'],  // Add the user's name
                'Category' => $category['name'],  // Add the category name
                'Topic Name' => $topic['name'],
                'Score' => $score,
                'Total Questions' => $total_questions
            ]
        ];

        $ch = curl_init('https://api.airtable.com/v0/appbdLZk5dPBtqqQO/InternQuiz');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer patNxcdsnKKitK4P9.8d31c2965876752313c777e34f717229b4349e9d5acefed44336d744038f2186',
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($airtableData));

        // Capture Airtable response and cURL errors
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            echo json_encode(['status' => 'error', 'message' => 'cURL error: ' . $error_msg]);
        } elseif ($http_code != 200) {
            // Decode Airtable's error response and print it for debugging
            $airtable_error = json_decode($response, true);

            echo json_encode([
                'status' => 'error',
                'message' => 'Airtable API returned error. HTTP Status Code: ' . $http_code,
                'response' => $airtable_error // Display the full response for debugging
            ]);
        } else {
            echo json_encode([
                'status' => 'success',
                'score' => $score,
                'total_questions' => $total_questions,
                'airtable_response' => $response
            ]);
        }

        curl_close($ch);

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => 'Failed to submit quiz: ' . $e->getMessage()]);
    }
}

?>
