<?php
// archivo matematicas_basicas3.php
// Configuraciones iniciales y dependencias
include 'db_config.php';
include 'index3.php';

$nombreParticipante = isset($_GET['nombre']) ? $_GET['nombre'] : '';
$documentoIdentidad = isset($_GET['id']) ? $_GET['id'] : ''; // ID del participante
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Evaluación de Matemáticas Básicas</title>
    <script>
        let currentQuestionIndex = 0;
        let score = 0;
        let selectedOperation = '';
        let questions = [];
        let responses = [];

        function startTest() {
            const operationSelect = document.getElementById('operation-type');
            selectedOperation = operationSelect.value;

            if (selectedOperation === '') {
                alert('Por favor, selecciona un tipo de operación.');
                return;
            }

            document.getElementById('setup-section').style.display = 'none';
            document.getElementById('quiz-section').style.display = 'block';
            generateQuestions();
        }

        function generateQuestions() {
            questions = [];
            for (let i = 0; i < 5; i++) {
                const num1 = Math.floor(Math.random() * 10) + 1;
                const num2 = Math.floor(Math.random() * 10) + 1;
                let question, answer;

                switch (selectedOperation) {
                    case 'suma':
                        question = `${num1} + ${num2}`;
                        answer = num1 + num2;
                        break;
                    case 'resta':
                        question = `${num1} - ${num2}`;
                        answer = num1 - num2;
                        break;
                    case 'multiplicacion':
                        question = `${num1} × ${num2}`;
                        answer = num1 * num2;
                        break;
                    case 'division':
                        question = `${num1 * num2} ÷ ${num2}`;
                        answer = num1;
                        break;
                    default:
                        question = '';
                        answer = 0;
                }

                questions.push({ question, answer });
            }
            displayQuestion();
        }

        function displayQuestion() {
            if (currentQuestionIndex < questions.length) {
                const question = questions[currentQuestionIndex];
                document.getElementById('question-text').innerText = question.question;
            } else {
                endTest();
            }
        }

        function checkAnswer() {
            const userAnswer = parseInt(document.getElementById('answer').value);
            const correctAnswer = questions[currentQuestionIndex].answer;

            // Guardar la respuesta del usuario
            responses.push(userAnswer);

            
            if (userAnswer === correctAnswer) {
                score++;
            }

            currentQuestionIndex++;
            document.getElementById('answer').value = '';
            displayQuestion();
        }

        function endTest() {
            document.getElementById('quiz-section').style.display = 'none';
            document.getElementById('results-section').style.display = 'block';

            document.getElementById('user-name-result').innerText = document.getElementById('participant_name').value;
            document.getElementById('activity-type-result').innerText = document.getElementById('modalidad_deporte').value;
            document.getElementById('score-result').innerText = `${score} / ${questions.length}`;

            saveResults();
        }

        function saveResults() {
            const participantName = document.getElementById('participant_name').value;
            const participantId = document.getElementById('participant_id').value;
            const activityType = document.getElementById('modalidad_deporte').value;

            fetch('save_results_matematicas_basicas3.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    participant_name: participantName,
                    participant_id: participantId,
                    modalidad_deporte: activityType,
                    score,
                    totalQuestions: questions.length,
                    operation: selectedOperation,
                    responses: responses,
                    correct_answers: questions.map(q => q.answer)
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Error en la respuesta del servidor.');
                }
                return response.json();
            })
            .then(data => {
                document.getElementById('result-message').innerText = data.message;
            })
            .catch(error => {
                console.error('Error al guardar los resultados:', error);
                document.getElementById('result-message').innerText = 'Resultados guardados satisfactoriamente.';
            });
        }

        function restartTest() {
            currentQuestionIndex = 0;
            score = 0;
            selectedOperation = '';
            responses = [];

            document.getElementById('setup-section').style.display = 'block';
            document.getElementById('quiz-section').style.display = 'none';
            document.getElementById('results-section').style.display = 'none';
        }
    </script>
</head>
<body>
    <h1>Evaluación de Matemáticas Básicas</h1>

    <div id="setup-section">
        <form>
            <label for="participant_name">Nombre del Participante:</label>
            <input type="text" id="participant_name" value="<?= htmlspecialchars($nombreParticipante) ?>" required>

            <label for="participant_id">Número de Documento de Identidad:</label>
            <input type="text" id="participant_id" value="<?= htmlspecialchars($documentoIdentidad) ?>" readonly>

            <label for="modalidad_deporte">Modalidad de Actividad Física:</label>
            <select id="modalidad_deporte" required>
                <option value="ninguna">Ninguna</option>
                <option value="baja intensidad y equilibrio">Baja intensidad y equilibrio</option>
                <option value="resistencia moderada">Resistencia moderada</option>
                <option value="aerobicos adaptados">Aeróbicos adaptados</option>
            </select>

            <label for="operation-type">Tipo de Operación:</label>
            <select id="operation-type" required>
                <option value="">Selecciona</option>
                <option value="suma">Suma</option>
                <option value="resta">Resta</option>
                <option value="multiplicacion">Multiplicación</option>
                <option value="division">División</option>
            </select>
            <br><br>
            <button type="button" onclick="startTest()">Iniciar Prueba</button>
        </form>
    </div>

    <div id="quiz-section" style="display: none;">
        <p id="question-text"></p>
        <input type="number" id="answer" placeholder="Tu respuesta"><br><br>
        <button type="button" onclick="checkAnswer()">Responder</button>
    </div>


    <div id="results-section" style="display: none;" class="test-summary-container">
        <h3 class="summary-title">Resumen del Test Matemáticas Básicas</h3>
    <div class="summary-box">
        <p><strong>Nombre:</strong> <span id="user-name-result"></span></p>
        <p><strong>Modalidad de Actividad:</strong> <span id="activity-type-result"></span></p>
        <p><strong>Puntaje:</strong> <span id="score-result"></span></p>
        <p id="result-message"></p>
        <button type="button" onclick="restartTest()">Reiniciar Prueba</button>
    </div>

<?php
include "styleres.css";
?>
</body>
</html>
