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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Get exam ID from URL (support both online and offline exams)
$online_exam_id = $_GET['online_exam_id'] ?? null;
$exam_id = $_GET['exam_id'] ?? null;

if (!$online_exam_id && !$exam_id) {
    header('Location: online_exams.php');
    exit();
}

// Fetch exam details
if ($online_exam_id) {
    // Online exam
    $stmt = $pdo->prepare("SELECT oe.*, c.name as class_name, s.name as subject_name FROM online_exams oe 
                           JOIN classes c ON oe.class_id = c.id 
                           JOIN subjects s ON oe.subject_id = s.id 
                           WHERE oe.id = ?");
    $stmt->execute([$online_exam_id]);
    $exam = $stmt->fetch();
    $exam_type = 'online';
} else {
    // Regular exam
    $stmt = $pdo->prepare("SELECT e.*, c.name as class_name, s.name as subject_name FROM exams e 
                           JOIN classes c ON e.class_id = c.id 
                           JOIN exam_subjects es ON e.id = es.exam_id 
                           JOIN subjects s ON es.subject_id = s.id 
                           WHERE e.id = ?");
    $stmt->execute([$exam_id]);
    $exam = $stmt->fetch();
    $exam_type = 'offline';
}

if (!$exam) {
    header('Location: online_exams.php');
    exit();
}

// Fetch exam questions
if ($exam_type == 'online') {
    $stmt = $pdo->prepare("SELECT * FROM online_exam_questions WHERE online_exam_id = ? ORDER BY RAND()");
    $stmt->execute([$online_exam_id]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY RAND()");
    $stmt->execute([$exam_id]);
}
$questions = $stmt->fetchAll();

// Add function to shuffle options
function get_shuffled_options($question) {
    if ($question['question_type'] !== 'mcq') {
        return $question;
    }
    
    // Create an array of options with their values
    $options = [
        'A' => $question['option_a'],
        'B' => $question['option_b'],
        'C' => $question['option_c'],
        'D' => $question['option_d']
    ];
    
    // Store original correct answer value
    $original_correct_value = $options[$question['correct_answer']];
    
    // Convert to array of values and shuffle
    $option_values = array_values($options);
    shuffle($option_values);
    
    // Map shuffled values back to labels
    $shuffled_options = [
        'option_a' => $option_values[0],
        'option_b' => $option_values[1],
        'option_c' => $option_values[2],
        'option_d' => $option_values[3]
    ];
    
    // Find the new correct answer label
    $new_correct_answer = '';
    foreach (['A', 'B', 'C', 'D'] as $i => $label) {
        if ($option_values[$i] === $original_correct_value) {
            $new_correct_answer = $label;
            break;
        }
    }
    
    // Update the question with shuffled options
    $question['option_a'] = $shuffled_options['option_a'];
    $question['option_b'] = $shuffled_options['option_b'];
    $question['option_c'] = $shuffled_options['option_c'];
    $question['option_d'] = $shuffled_options['option_d'];
    $question['correct_answer'] = $new_correct_answer;
    
    return $question;
}

// Process questions to randomize options
foreach ($questions as &$question) {
    $question = get_shuffled_options($question);
}
unset($question); // Break the reference with the last element

// Calculate exam duration
$duration = 60; // Default 60 minutes
if ($exam_type == 'online') {
    $duration = $exam['duration'] ?? 60;
} else {
    if ($exam['start_time'] && $exam['end_time']) {
        $start = new DateTime($exam['start_time']);
        $end = new DateTime($exam['end_time']);
        $interval = $start->diff($end);
        $duration = $interval->h * 60 + $interval->i;
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($exam['name']); ?> - অনলাইন পরীক্ষা</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .exam-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .question-container {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .option-item {
            background-color: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .option-item:hover {
            background-color: #e9ecef;
            border-color: #adb5bd;
        }
        
        .option-item.selected {
            background-color: #d1ecf1;
            border-color: #0c5460;
        }
        
        .timer-container {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .timer-value {
            font-size: 2rem;
            font-weight: bold;
        }
        
        .navigation-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        
        .question-nav {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-bottom: 20px;
        }
        
        .question-nav .btn {
            width: 40px;
            height: 40px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/online_exams.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-file-alt me-2"></i>
                    <?php echo htmlspecialchars($exam['name']); ?>
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / অনলাইন পরীক্ষা / <?php echo htmlspecialchars($exam['name']); ?>
                </p>
            </div>
            
            <!-- Content Body -->
            <div class="content-body">
                <div class="exam-header">
                    <div class="row">
                        <div class="col-md-8">
                            <h3><?php echo htmlspecialchars($exam['name']); ?></h3>
                            <p class="mb-1"><i class="fas fa-book me-2"></i> বিষয়: <?php echo htmlspecialchars($exam['subject_name']); ?></p>
                            <p class="mb-1"><i class="fas fa-school me-2"></i> ক্লাস: <?php echo htmlspecialchars($exam['class_name']); ?></p>
                            <p class="mb-0"><i class="fas fa-clock me-2"></i> সময়কাল: <?php echo $duration; ?> মিনিট</p>
                        </div>
                        <div class="col-md-4">
                            <div class="timer-container">
                                <h5>অবশিষ্ট সময়</h5>
                                <div class="timer-value" id="timer">00:00:00</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-lg-8">
                        <?php if (count($questions) > 0): ?>
                            <?php foreach ($questions as $index => $question): ?>
                                <div class="question-container" id="question-<?php echo $index + 1; ?>" style="<?php echo $index > 0 ? 'display: none;' : ''; ?>">
                                    <h5>প্রশ্ন <?php echo $index + 1; ?>: <?php echo htmlspecialchars($question['question_text']); ?></h5>
                                    <p><small class="text-muted">নম্বর: <?php echo $question['marks']; ?></small></p>
                                    
                                    <?php if ($question['question_type'] === 'mcq'): ?>
                                        <div class="option-item" data-question="<?php echo $index + 1; ?>" data-option="A">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="question<?php echo $question['id']; ?>" id="option<?php echo $index + 1; ?>a" value="A">
                                                <label class="form-check-label" for="option<?php echo $index + 1; ?>a">
                                                    A. <?php echo htmlspecialchars($question['option_a']); ?>
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="option-item" data-question="<?php echo $index + 1; ?>" data-option="B">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="question<?php echo $question['id']; ?>" id="option<?php echo $index + 1; ?>b" value="B">
                                                <label class="form-check-label" for="option<?php echo $index + 1; ?>b">
                                                    B. <?php echo htmlspecialchars($question['option_b']); ?>
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="option-item" data-question="<?php echo $index + 1; ?>" data-option="C">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="question<?php echo $question['id']; ?>" id="option<?php echo $index + 1; ?>c" value="C">
                                                <label class="form-check-label" for="option<?php echo $index + 1; ?>c">
                                                    C. <?php echo htmlspecialchars($question['option_c']); ?>
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div class="option-item" data-question="<?php echo $index + 1; ?>" data-option="D">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="question<?php echo $question['id']; ?>" id="option<?php echo $index + 1; ?>d" value="D">
                                                <label class="form-check-label" for="option<?php echo $index + 1; ?>d">
                                                    D. <?php echo htmlspecialchars($question['option_d']); ?>
                                                </label>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <div class="mb-3">
                                            <label for="answer<?php echo $index + 1; ?>" class="form-label">উত্তর লিখুন:</label>
                                            <textarea class="form-control" id="answer<?php echo $index + 1; ?>" name="question<?php echo $question['id']; ?>" rows="4" placeholder="আপনার উত্তর এখানে লিখুন..."></textarea>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                            
                            <div class="navigation-buttons">
                                <button class="btn btn-secondary" id="prevBtn" disabled>
                                    <i class="fas fa-arrow-left me-2"></i>
                                    পিছনে
                                </button>
                                <button class="btn btn-primary" id="nextBtn">
                                    পরবর্তী
                                    <i class="fas fa-arrow-right ms-2"></i>
                                </button>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                এই পরীক্ষার জন্য কোন প্রশ্ন পাওয়া যায়নি।
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-list-ol me-2"></i>
                                    প্রশ্ন তালিকা
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="question-nav">
                                    <?php for ($i = 1; $i <= count($questions); $i++): ?>
                                        <button class="btn btn-sm btn-outline-primary question-nav-btn" data-question="<?php echo $i; ?>">
                                            <?php echo $i; ?>
                                        </button>
                                    <?php endfor; ?>
                                </div>
                                
                                <div class="d-grid">
                                    <button class="btn btn-danger" id="submitExamBtn">
                                        <i class="fas fa-paper-plane me-2"></i>
                                        পরীক্ষা জমা দিন
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Timer functionality
            let totalSeconds = <?php echo $duration * 60; ?>;
            const timerElement = document.getElementById('timer');
            
            function updateTimer() {
                const hours = Math.floor(totalSeconds / 3600);
                const minutes = Math.floor((totalSeconds % 3600) / 60);
                const seconds = totalSeconds % 60;
                
                timerElement.textContent = 
                    String(hours).padStart(2, '0') + ':' +
                    String(minutes).padStart(2, '0') + ':' +
                    String(seconds).padStart(2, '0');
                
                if (totalSeconds > 0) {
                    totalSeconds--;
                } else {
                    // Auto submit exam when time is up
                    alert('সময় শেষ! পরীক্ষা স্বয়ংক্রিয়ভাবে জমা হবে।');
                    submitExam();
                }
            }
            
            // Update timer every second
            setInterval(updateTimer, 1000);
            updateTimer(); // Initial call
            
            // Question navigation
            let currentQuestion = 1;
            const totalQuestions = <?php echo count($questions); ?>;
            
            // Option selection
            const options = document.querySelectorAll('.option-item');
            options.forEach(option => {
                option.addEventListener('click', function() {
                    const questionNum = this.getAttribute('data-question');
                    const selectedOption = this.getAttribute('data-option');
                    
                    // Remove selected class from all options of this question
                    document.querySelectorAll(`.option-item[data-question="${questionNum}"]`).forEach(opt => {
                        opt.classList.remove('selected');
                    });
                    
                    // Add selected class to clicked option
                    this.classList.add('selected');
                    
                    // Check the radio button
                    const radio = this.querySelector(`input[name="question${questionNum}"]`);
                    if (radio) {
                        radio.checked = true;
                    }
                });
            });
            
            // Navigation buttons
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            
            prevBtn.addEventListener('click', function() {
                if (currentQuestion > 1) {
                    document.getElementById(`question-${currentQuestion}`).style.display = 'none';
                    currentQuestion--;
                    document.getElementById(`question-${currentQuestion}`).style.display = 'block';
                    updateNavigationButtons();
                }
            });
            
            nextBtn.addEventListener('click', function() {
                if (currentQuestion < totalQuestions) {
                    document.getElementById(`question-${currentQuestion}`).style.display = 'none';
                    currentQuestion++;
                    document.getElementById(`question-${currentQuestion}`).style.display = 'block';
                    updateNavigationButtons();
                }
            });
            
            // Question nav buttons
            const navButtons = document.querySelectorAll('.question-nav-btn');
            navButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const questionNum = parseInt(this.getAttribute('data-question'));
                    document.getElementById(`question-${currentQuestion}`).style.display = 'none';
                    currentQuestion = questionNum;
                    document.getElementById(`question-${currentQuestion}`).style.display = 'block';
                    updateNavigationButtons();
                });
            });
            
            function updateNavigationButtons() {
                prevBtn.disabled = currentQuestion === 1;
                nextBtn.disabled = currentQuestion === totalQuestions;
            }
            
            // Submit exam
            const submitExamBtn = document.getElementById('submitExamBtn');
            submitExamBtn.addEventListener('click', function() {
                if (confirm('আপনি কি নিশ্চিত যে পরীক্ষা জমা দিতে চান?')) {
                    submitExam();
                }
            });
            
            function submitExam() {
                // Collect all answers
                const answers = {};
                
                // Collect radio button answers
                const radioGroups = document.querySelectorAll('input[type=radio]:checked');
                radioGroups.forEach(radio => {
                    const questionId = radio.name.replace('question', '');
                    answers[questionId] = radio.value;
                });
                
                // Collect textarea answers
                const textAnswers = document.querySelectorAll('textarea[name^="question"]');
                textAnswers.forEach(textarea => {
                    const questionId = textarea.name.replace('question', '');
                    if (textarea.value.trim() !== '') {
                        answers[questionId] = textarea.value;
                    }
                });
                
                // Debug: Log collected answers
                console.log('Collected answers:', answers);
                
                // Send answers to server using AJAX
                fetch('api/submit_exam.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        online_exam_id: <?php echo $online_exam_id; ?>,
                        answers: answers
                    })
                })
                .then(response => response.json())
                .then(data => {
                    console.log('Server response:', data);
                    if (data.success) {
                        alert('পরীক্ষা সফলভাবে জমা হয়েছে!');
                        window.location.href = 'online_exams.php';
                    } else {
                        alert('ত্রুটি: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('পরীক্ষা জমা দিতে সমস্যা হয়েছে!');
                });
            }
            
            // Initialize navigation buttons
            updateNavigationButtons();
        });
    </script>
</body>
</html>