<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Science Quiz - Final Assessment</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
            background: #f0f0f0;
            color: #333;
        }

        .header {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .progress-bar {
            width: 100%;
            height: 10px;
            background: #ddd;
            border-radius: 5px;
            margin: 20px 0;
        }

        .progress {
            height: 100%;
            background: #4CAF50;
            width: 0;
            transition: width 0.3s ease;
        }

        .question-box {
            background: #fff;
            padding: 25px;
            margin: 20px 0;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .option-btn {
            display: block;
            width: 100%;
            padding: 15px;
            margin: 10px 0;
            border: 2px solid #ddd;
            border-radius: 5px;
            cursor: pointer;
            text-align: left;
            background: #fff;
        }

        .option-btn.selected {
            border-color: #4CAF50;
            background: #f8fff8;
        }

        .nav-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 25px;
            gap: 10px;
        }

        button {
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        .timer {
            font-size: 18px;
            color: #d32f2f;
            font-weight: bold;
        }

        .student-info {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .result-section {
            background: #fff;
            padding: 25px;
            border-radius: 8px;
            display: none;
        }

        .question-review {
            margin: 15px 0;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 5px;
        }

        .correct { background: #e8f5e9; }
        .incorrect { background: #ffebee; }
        .skipped { background: #fff3e0; }

        .question-numbers-bar {
            display: flex;
            overflow-x: auto;
            gap: 5px;
            padding: 10px 0;
            margin: 15px 0;
        }

        .q-number {
            min-width: 35px;
            height: 35px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .q-number.current {
            background: #2196F3;
            color: white;
        }

        .q-number.answered {
            background: #4CAF50;
            color: white;
        }

        .q-number.unanswered {
            background: #ddd;
            color: #666;
        }

        .pdf-buttons {
            margin-top: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>science 31 jan 2025</h1>
        <div class="timer" id="timer">Time: 20:00</div>
    </div>

    <div class="student-info" id="student-info">
        <h2>Student Details</h2>
        <input type="text" id="student-name" placeholder="Enter your name" style="width: 300px; padding: 8px;">
        <button onclick="startQuiz()" style="background: #4CAF50; color: white;">Start Quiz</button>
    </div>

    <div id="quiz" style="display: none;">
        <div class="progress-bar">
            <div class="progress" id="progress"></div>
        </div>
        
        <div class="question-numbers-bar" id="question-numbers"></div>

        <div id="question-container"></div>
        
        <div class="nav-buttons">
            <button onclick="prevQuestion()" id="prev-btn" style="background: #607D8B; color: white;">Previous</button>
            <div>
                <button onclick="showResult()" id="submit-btn" style="background: #d32f2f; color: white; margin-right: 10px;">Submit</button>
                <button onclick="nextQuestion()" id="next-btn" style="background: #4CAF50; color: white;">Next</button>
            </div>
        </div>
    </div>

    <div class="result-section" id="result">
        <h2>Detailed Result Analysis</h2>
        <div id="result-summary"></div>
        <div id="detailed-analysis"></div>
        
        <div class="pdf-buttons">
            <button onclick="generatePDF()" style="background: #d32f2f; color: white;">Download PDF</button>
            <button onclick="shareToWhatsApp()" style="background: #25D366; color: white;">Share via WhatsApp</button>
            <button onclick="location.reload()" style="background: #2196F3; color: white;">Retake Test</button>
        </div>
    </div>

<script>
var quizData = {
    studentName: "",
    startTime: null,
    endTime: null,
    answers: [],
    questions: [
        {
      "question": "Which element has the highest melting point?",
      "options": ["Tungsten", "Carbon", "Platinum", "Iridium"],
      "answer": "Tungsten"
    },
    {
      "question": "What is the fastest known particle in the universe?",
      "options": ["Neutrino", "Photon", "Proton", "Electron"],
      "answer": "Photon"
    },
    {
      "question": "Which of these is NOT a greenhouse gas?",
      "options": ["Carbon dioxide", "Methane", "Nitrogen", "Water vapor"],
      "answer": "Nitrogen"
    },
    {
      "question": "What is the primary function of mitochondria in cells?",
      "options": ["Protein synthesis", "Energy production", "Cell division", "Waste removal"],
      "answer": "Energy production"
    },
    {
      "question": "Which scientist proposed the quantum theory?",
      "options": ["Albert Einstein", "Max Planck", "Niels Bohr", "Werner Heisenberg"],
      "answer": "Max Planck"
    },
    {
      "question": "Which blood type is known as the universal donor?",
      "options": ["AB+", "O-", "B+", "A-"],
      "answer": "O-"
    },
    {
      "question": "What is the hardest natural substance on Earth?",
      "options": ["Graphene", "Diamond", "Titanium", "Platinum"],
      "answer": "Diamond"
    },
    {
      "question": "Which planet has the most moons in our solar system?",
      "options": ["Saturn", "Jupiter", "Uranus", "Neptune"],
      "answer": "Jupiter"
    },
    {
      "question": "What is the study of fossils called?",
      "options": ["Archaeology", "Paleontology", "Geology", "Anthropology"],
      "answer": "Paleontology"
    },
    {
      "question": "Which of these is NOT a type of electromagnetic radiation?",
      "options": ["X-rays", "Sound waves", "Gamma rays", "Ultraviolet rays"],
      "answer": "Sound waves"
    },
    {
      "question": "What is the chemical symbol for gold?",
      "options": ["Ag", "Fe", "Au", "Cu"],
      "answer": "Au"
    },
    {
      "question": "Which part of the human brain is responsible for balance and coordination?",
      "options": ["Cerebrum", "Cerebellum", "Medulla", "Hypothalamus"],
      "answer": "Cerebellum"
    },
    {
      "question": "What is the process by which plants make their own food called?",
      "options": ["Respiration", "Photosynthesis", "Fermentation", "Digestion"],
      "answer": "Photosynthesis"
    },
    {
      "question": "Which element is most abundant in Earth's atmosphere?",
      "options": ["Oxygen", "Carbon dioxide", "Nitrogen", "Hydrogen"],
      "answer": "Nitrogen"
    },
    {
      "question": "What is the smallest unit of matter?",
      "options": ["Atom", "Molecule", "Proton", "Quark"],
      "answer": "Quark"
    },
    {
      "question": "Which disease was the first to be completely eradicated globally?",
      "options": ["Polio", "Smallpox", "Tuberculosis", "Measles"],
      "answer": "Smallpox"
    },
    {
      "question": "What is the speed of light in vacuum?",
      "options": ["299,792 kilometers per second", "300,000 kilometers per second", "199,792 kilometers per second", "250,000 kilometers per second"],
      "answer": "299,792 kilometers per second"
    },
    {
      "question": "Which of these is NOT a noble gas?",
      "options": ["Helium", "Neon", "Chlorine", "Argon"],
      "answer": "Chlorine"
    },
    {
      "question": "What is the main component of the Sun?",
      "options": ["Helium", "Hydrogen", "Nitrogen", "Oxygen"],
      "answer": "Hydrogen"
    },
    {
      "question": "Which vitamin is produced when skin is exposed to sunlight?",
      "options": ["Vitamin A", "Vitamin B", "Vitamin C", "Vitamin D"],
      "answer": "Vitamin D"
    },

        // Add remaining questions here...
    ]
};

var currentQuestion = 0;
var timeLeft = 1200;
var timerId;

function startQuiz() {
    var name = document.getElementById('student-name').value;
    if (!name) return alert("Please enter your name");
    
    quizData.studentName = name;
    quizData.startTime = new Date();
    
    document.getElementById('student-info').style.display = 'none';
    document.getElementById('quiz').style.display = 'block';
    
    startTimer();
    showQuestion();
    updateQuestionNumbers();
}

function startTimer() {
    timerId = setInterval(function() {
        timeLeft--;
        var minutes = Math.floor(timeLeft / 60);
        var seconds = timeLeft % 60;
        document.getElementById('timer').textContent = 
            "Time: " + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
        
        if (timeLeft <= 0) showResult();
    }, 1000);
}

function updateQuestionNumbers() {
    var numbersHTML = '';
    for (var i = 0; i < quizData.questions.length; i++) {
        var status = '';
        if (i === currentQuestion) {
            status = 'current';
        } else if (typeof quizData.answers[i] !== 'undefined') {
            status = 'answered';
        } else {
            status = 'unanswered';
        }
        numbersHTML += '<button class="q-number ' + status + '" onclick="jumpToQuestion(' + i + ')">' + (i + 1) + '</button>';
    }
    document.getElementById('question-numbers').innerHTML = numbersHTML;
}

function jumpToQuestion(index) {
    if (index >= 0 && index < quizData.questions.length) {
        currentQuestion = index;
        showQuestion();
        updateQuestionNumbers();
    }
}
function nextQuestion() {
    if (currentQuestion < quizData.questions.length - 1) {
        currentQuestion++;
        showQuestion();
        updateQuestionNumbers();
    }
}

function prevQuestion() {
    if (currentQuestion > 0) {
        currentQuestion--;
        showQuestion();
        updateQuestionNumbers();
    }
}

function showQuestion() {
    var question = quizData.questions[currentQuestion];
    var html = '<div class="question-box">';
    html += '<h3>Question ' + (currentQuestion + 1) + ' of ' + quizData.questions.length + '</h3>';
    html += '<p>' + question.question + '</p>';
    
    question.options.forEach((option, index) => {
        var isSelected = quizData.answers[currentQuestion] === option ? "selected" : "";
        html += `<button class="option-btn ${isSelected}" onclick="selectAnswer(${currentQuestion}, '${option}')">${option}</button>`;
    });

    html += '</div>';
    document.getElementById('question-container').innerHTML = html;

    // Update button visibility
    document.getElementById('prev-btn').style.display = currentQuestion === 0 ? 'none' : 'inline-block';
    document.getElementById('next-btn').style.display = currentQuestion === quizData.questions.length - 1 ? 'none' : 'inline-block';
}

function selectAnswer(questionIndex, answer) {
    quizData.answers[questionIndex] = answer;
    showQuestion();
    updateQuestionNumbers();
}

// Submit button at the beginning
document.getElementById('submit-btn').addEventListener('click', showResult);

function showQuestion() {
    var question = quizData.questions[currentQuestion];
    var html = '<div class="question-box">';
    html += '<h3>Question ' + (currentQuestion + 1) + ' of ' + quizData.questions.length + '</h3>';
    html += '<p>' + question.question + '</p>';
    
    for (var i = 0; i < question.options.length; i++) {
        var selected = quizData.answers[currentQuestion] === i ? ' selected' : '';
        html += '<div class="option-btn' + selected + '" onclick="selectAnswer(' + i + ')">' +
                String.fromCharCode(65 + i) + '. ' + question.options[i] + '</div>';
    }
    
    html += '</div>';
    document.getElementById('question-container').innerHTML = html;
    
    var progress = (currentQuestion + 1) / quizData.questions.length * 100;
    document.getElementById('progress').style.width = progress + '%';
    
    document.getElementById('prev-btn').disabled = currentQuestion === 0;
    updateQuestionNumbers();
}

function selectAnswer(index) {
    quizData.answers[currentQuestion] = index;
    updateQuestionNumbers();
    showQuestion();
}

function showResult() {
    if (!confirm("Are you sure you want to submit the quiz?")) return;
    
    clearInterval(timerId);
    quizData.endTime = new Date();
    
    document.getElementById('quiz').style.display = 'none';
    document.getElementById('result').style.display = 'block';
    
    var correct = 0;
    var analysisHTML = '<h3>Question-wise Analysis:</h3>';
    
    for (var i = 0; i < quizData.questions.length; i++) {
        var question = quizData.questions[i];
        var userAnswer = quizData.answers[i];
        var statusClass = '';
        var statusText = '';
        
        if (typeof userAnswer === 'undefined') {
            statusClass = 'skipped';
            statusText = 'Skipped';
        } else if (question.options[userAnswer] === question.answer) {
            correct++;
            statusClass = 'correct';
            statusText = 'Correct';
        } else {
            statusClass = 'incorrect';
            statusText = 'Incorrect';
        }
        
        analysisHTML += '<div class="question-review ' + statusClass + '">' +
            '<p><strong>Question ' + (i + 1) + ':</strong> ' + question.question + '</p>' +
            '<p>Your Answer: ' + (typeof userAnswer !== 'undefined' ? 
                String.fromCharCode(65 + userAnswer) + '. ' + question.options[userAnswer] : 'Not answered') + '</p>' +
            '<p>Correct Answer: ' + String.fromCharCode(65 + question.options.indexOf(question.answer)) + 
            '. ' + question.answer + '</p>' +
            '<p>Status: ' + statusText + '</p></div>';
    }
    
    var timeTaken = Math.floor((quizData.endTime - quizData.startTime) / 1000);
    var minutes = Math.floor(timeTaken / 60);
    var seconds = timeTaken % 60;
    var avgTime = (timeTaken/quizData.questions.length).toFixed(1);
    
    var summaryHTML = '<div class="result-summary">' +
        '<h3>Student Name: ' + quizData.studentName + '</h3>' +
        '<p>Total Questions: ' + quizData.questions.length + '</p>' +
        '<p>Correct Answers: ' + correct + '</p>' +
        '<p>Score: ' + correct + '/' + quizData.questions.length + ' (' + 
        Math.round((correct / quizData.questions.length) * 100) + '%)</p>' +
        '<p>Total Time: ' + minutes + 'm ' + seconds + 's</p>' +
        '<p>Average Time per Question: ' + avgTime + ' seconds</p></div>';
    
    document.getElementById('result-summary').innerHTML = summaryHTML;
    document.getElementById('detailed-analysis').innerHTML = analysisHTML;
}

function generatePDF() {
    // Get current date and time
    var currentDateTime = new Date();
    var formattedDateTime = currentDateTime.toLocaleString();  // Formats as "MM/DD/YYYY, HH:mm:ss"

    var studentNameText = quizData.studentname ? 'Student Name: ' + quizData.studentname : '';
    
    // Define the content array for the PDF
    var contentArray = [
        { 
            text: 'Exam Result', 
            style: 'header' 
        },
        { 
            text: '--------------------------------------', 
            style: 'divider' 
        }
    ];

    // Add student name if available
    if (studentNameText) {
        contentArray.push({
            text: studentNameText, 
            style: 'studentName',
            margin: [0, 15]
        });
    }

    // Add the result summary
    contentArray.push(
        {
            text: document.getElementById('result-summary').innerText,
            style: 'resultSummary',
            margin: [0, 15]
        }
    );

    // Add detailed analysis header
    contentArray.push(
        {
            text: 'Detailed Analysis:',
            style: 'subheader',
            margin: [0, 10]
        },
        {
            ul: Array.from(document.querySelectorAll('.question-review')).map(q => ({
                text: q.innerText,
                style: 'questionReviewItem',
                margin: [0, 5]
            })),
            margin: [0, 10]
        }
    );

    // Define styles for the PDF content
    var docDefinition = {
        content: contentArray,
        styles: {
            header: {
                fontSize: 22,
                bold: true,
                alignment: 'center',
                color: '#2E3D49'
            },
            subheader: {
                fontSize: 16,
                bold: true,
                margin: [0, 10],
                color: '#1F2C38'
            },
            studentName: {
                fontSize: 14,
                italics: true,
                margin: [0, 10],
                alignment: 'center',
                color: '#4C5C68'
            },
            resultSummary: {
                fontSize: 14,
                margin: [0, 10],
                color: '#333'
            },
            questionReviewItem: {
                fontSize: 12,
                margin: [0, 5],
                color: '#555'
            },
            divider: {
                fontSize: 1,
                margin: [0, 15],
                color: '#E1E1E1',
                alignment: 'center'
            },
            footer: {
                fontSize: 10,
                color: '#777',
                alignment: 'center'
            }
        },
        pageMargins: [40, 60, 40, 60], // Margins for a neat appearance
        footer: function(currentPage, pageCount) {
            return [
                {
                    text: formattedDateTime,
                    alignment: 'center',
                    style: 'footer',
                    margin: [0, 10]
                },
                {
                    text: currentPage + ' of ' + pageCount,
                    alignment: 'center',
                    style: 'footer'
                }
            ];
        }
    };

    // Create the PDF and trigger the download
    if (navigator.userAgent.match(/Android/i)) {
        // For mobile platforms
        pdfMake.createPdf(docDefinition).download('Exam-Result.pdf');
    } else {
        // For other platforms (macOS, Linux)
        pdfMake.createPdf(docDefinition).open();
    }
}


function shareToWhatsApp() {
    var summary = document.getElementById('result-summary').innerText;
    var message = encodeURIComponent(
        "Exam Result:\n" + summary + ""
    );
    window.open('https://wa.me/?text=' + message, '_blank');
}
</script>
</body>
</html>