<?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 = (int)$_POST['user_id'];
    $topic_id = (int)$_POST['topic_id'];
    $answers = json_decode($_POST['answers'], true);

    if (!is_array($answers)) {
        echo json_encode(['status' => 'error', 'message' => 'Answers must be a valid JSON array.']);
        exit;
    }

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

        // Block submission if score >= 80%
        if ($existingAttempt && ($existingAttempt['score'] / $existingAttempt['total_questions'] * 100) >= 80) {
            echo json_encode([
                'status' => 'exists',
                'score' => (int)$existingAttempt['score'],
                'total_questions' => (int)$existingAttempt['total_questions'],
                'message' => 'Quiz already attempted with sufficient score.'
            ]);
            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++;
            }
        }

        // Determine if this is a retake and set attempt_number and is_retake
        $attempt_number = $existingAttempt ? $existingAttempt['attempt_number'] + 1 : 1;
        $is_retake = $existingAttempt ? 1 : 0;

        if ($existingAttempt) {
            // Update existing record in user_quizzes for retake
            $stmt = $pdo->prepare("
                UPDATE user_quizzes 
                SET score = ?, total_questions = ?, attempt_number = ?, is_retake = ?, attempt_time = CURRENT_TIMESTAMP
                WHERE user_id = ? AND topic_id = ?
            ");
            $stmt->execute([$score, $total_questions, $attempt_number, $is_retake, $user_id, $topic_id]);
        } else {
            // Insert new record in user_quizzes for first attempt
            $stmt = $pdo->prepare("
                INSERT INTO user_quizzes (user_id, topic_id, score, total_questions, attempt_number, is_retake)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$user_id, $topic_id, $score, $total_questions, $attempt_number, $is_retake]);
        }

        // Get or create user_quiz_id
        $stmt = $pdo->prepare("
            SELECT id FROM user_quizzes WHERE user_id = ? AND topic_id = ?
        ");
        $stmt->execute([$user_id, $topic_id]);
        $user_quiz_id = $stmt->fetchColumn();

        // Delete previous answers for this user_quiz_id (for retakes)
        $stmt = $pdo->prepare("DELETE FROM user_answers WHERE user_quiz_id = ?");
        $stmt->execute([$user_quiz_id]);

        // Insert new answers
        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();

        if (!$user) {
            echo json_encode(['status' => 'error', 'message' => 'User not found.']);
            exit;
        }

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

        if (!$category) {
            echo json_encode(['status' => 'error', 'message' => 'Category not found.']);
            exit;
        }

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

        if (!$topic) {
            echo json_encode(['status' => 'error', 'message' => 'Topic not found.']);
            exit;
        }

        // Add rt- prefix to topic name for retakes
        $topic_name = $is_retake ?  $topic['name'] : $topic['name'];

        // Send data to Airtable
        $airtableData = [
            'fields' => [
                'User Email' => $user['email'],
                'User Name' => $user['name'],
                'Category' => $category['name'],
                'Topic Name' => $topic_name, // Use prefixed topic name for retakes
                'Score' => $score,
                'Total Questions' => $total_questions,
                'Attempt Number' => $attempt_number // Optional: include attempt number
            ]
        ];

        $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) {
            $airtable_error = json_decode($response, true);
            echo json_encode([
                'status' => 'error',
                'message' => 'Airtable API returned error. HTTP Status Code: ' . $http_code,
                'response' => $airtable_error
            ]);
        } else {
            echo json_encode([
                'status' => 'success',
                'score' => $score,
                'total_questions' => $total_questions,
                'attempt_number' => $attempt_number,
                'is_retake' => $is_retake,
                'airtable_response' => $response
            ]);
        }

        curl_close($ch);

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