<?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();
}

// For online exams, we'll show questions and student responses
// Fetch exam questions
if ($exam_type == 'online') {
    $stmt = $pdo->prepare("SELECT * FROM online_exam_questions WHERE online_exam_id = ? ORDER BY id ASC");
    $stmt->execute([$online_exam_id]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY id ASC");
    $stmt->execute([$exam_id]);
}
$questions = $stmt->fetchAll();

// If user is student, show their responses (if any)
if ($user_role == 'student') {
    try {
        // Get the actual student ID from the students table
        $stmt = $pdo->prepare("SELECT id FROM students WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $student = $stmt->fetch();
        
        if (!$student) {
            error_log("Student record not found for user_id: " . $_SESSION['user_id']);
            $student_responses = [];
        } else {
            $student_id = $student['id'];
            // Fetch student's responses for this online exam
            error_log("Fetching responses for exam_id: $online_exam_id, student_id: $student_id");
            $stmt = $pdo->prepare("SELECT sr.*, q.question_text, q.correct_answer, q.marks as question_marks FROM online_exam_student_responses sr JOIN online_exam_questions q ON sr.question_id = q.id WHERE sr.online_exam_id = ? AND sr.student_id = ? ORDER BY q.id ASC");
            $stmt->execute([$online_exam_id, $student_id]);
            $student_responses = $stmt->fetchAll();
            error_log("Found " . count($student_responses) . " responses");
        }
    } catch (Exception $e) {
        // If table doesn't exist or other database error, initialize empty array
        $student_responses = [];
        error_log("Error fetching student responses: " . $e->getMessage());
    }
} else if ($user_role == 'admin' || $user_role == 'teacher') {
    // For admin/teacher, fetch statistics
    try {
        // Get number of participants
        $stmt = $pdo->prepare("SELECT COUNT(DISTINCT student_id) as participant_count FROM online_exam_student_responses WHERE online_exam_id = ?");
        $stmt->execute([$online_exam_id]);
        $participant_data = $stmt->fetch();
        $participant_count = $participant_data['participant_count'] ?? 0;
        
        // Get average score
        $stmt = $pdo->prepare("SELECT AVG(total_score) as avg_score FROM (SELECT student_id, SUM(marks_obtained) as total_score FROM online_exam_student_responses WHERE online_exam_id = ? GROUP BY student_id) as student_scores");
        $stmt->execute([$online_exam_id]);
        $avg_score_data = $stmt->fetch();
        $avg_score = $avg_score_data['avg_score'] ?? 0;
        
        // Get average percentage
        if (count($questions) > 0) {
            $total_marks = 0;
            foreach ($questions as $question) {
                $total_marks += $question['marks'];
            }
            $avg_percentage = $total_marks > 0 ? round(($avg_score / $total_marks) * 100, 2) : 0;
        } else {
            $avg_percentage = 0;
        }
    } catch (Exception $e) {
        error_log("Error fetching statistics: " . $e->getMessage());
        $participant_count = 0;
        $avg_percentage = 0;
    }
}
?>

<!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;
        }
        
        .student-response {
            background-color: #e8f4f8;
            border-left: 4px solid #17a2b8;
            padding: 15px;
            margin-top: 15px;
            border-radius: 0 8px 8px 0;
        }
        
        .correct-answer {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin-top: 15px;
            border-radius: 0 8px 8px 0;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
        }
    </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-chart-bar me-2"></i>
                    <?php echo htmlspecialchars($exam['name']); ?> - ফলাফল
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / অনলাইন পরীক্ষা / ফলাফল
                </p>
            </div>
            
            <!-- Content Body -->
            <div class="content-body">
                <div class="exam-header">
                    <div class="row">
                        <div class="col-md-12">
                            <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 $exam['total_marks']; ?> | পাস মার্কস: <?php echo $exam['pass_marks']; ?></p>
                        </div>
                    </div>
                </div>
                
                <?php if ($user_role == 'admin' || $user_role == 'teacher'): ?>
                    <!-- Teacher/Admin View - Show statistics and all questions -->
                    <div class="row">
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo count($questions); ?></div>
                                <div>মোট প্রশ্ন</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $participant_count ?? 0; ?></div>
                                <div>অংশগ্রহণকারী</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $avg_percentage ?? 0; ?>%</div>
                                <div>গড় নম্বর</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number">N/A</div>
                                <div>গড় গ্রেড</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-question-circle me-2"></i>
                                প্রশ্ন ও উত্তর
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php if (count($questions) > 0): ?>
                                <?php foreach ($questions as $index => $question): ?>
                                    <div class="question-container">
                                        <h5>প্রশ্ন <?php echo $index + 1; ?>: <?php echo htmlspecialchars($question['question_text']); ?></h5>
                                        <p><small class="text-muted">নম্বর: <?php echo $question['marks']; ?> | ধরন: <?php echo $question['question_type'] == 'mcq' ? 'MCQ' : ($question['question_type'] == 'short' ? 'সংক্ষিপ্ত' : 'বিস্তারিত'); ?></small></p>
                                        
                                        <?php if ($question['question_type'] === 'mcq'): ?>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p><strong>অপশনসমূহ:</strong></p>
                                                    <ul class="list-group">
                                                        <li class="list-group-item <?php echo $question['correct_answer'] === 'A' ? 'list-group-item-success' : ''; ?>">
                                                            A. <?php echo htmlspecialchars($question['option_a']); ?>
                                                            <?php if ($question['correct_answer'] === 'A'): ?>
                                                                <span class="badge bg-success float-end">সঠিক উত্তর</span>
                                                            <?php endif; ?>
                                                        </li>
                                                        <li class="list-group-item <?php echo $question['correct_answer'] === 'B' ? 'list-group-item-success' : ''; ?>">
                                                            B. <?php echo htmlspecialchars($question['option_b']); ?>
                                                            <?php if ($question['correct_answer'] === 'B'): ?>
                                                                <span class="badge bg-success float-end">সঠিক উত্তর</span>
                                                            <?php endif; ?>
                                                        </li>
                                                        <li class="list-group-item <?php echo $question['correct_answer'] === 'C' ? 'list-group-item-success' : ''; ?>">
                                                            C. <?php echo htmlspecialchars($question['option_c']); ?>
                                                            <?php if ($question['correct_answer'] === 'C'): ?>
                                                                <span class="badge bg-success float-end">সঠিক উত্তর</span>
                                                            <?php endif; ?>
                                                        </li>
                                                        <li class="list-group-item <?php echo $question['correct_answer'] === 'D' ? 'list-group-item-success' : ''; ?>">
                                                            D. <?php echo htmlspecialchars($question['option_d']); ?>
                                                            <?php if ($question['correct_answer'] === 'D'): ?>
                                                                <span class="badge bg-success float-end">সঠিক উত্তর</span>
                                                            <?php endif; ?>
                                                        </li>
                                                    </ul>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="correct-answer">
                                                        <h6><i class="fas fa-check-circle me-2"></i>সঠিক উত্তর</h6>
                                                        <p>Option <?php echo $question['correct_answer']; ?></p>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="correct-answer">
                                                <h6><i class="fas fa-check-circle me-2"></i>উত্তরের ধরন</h6>
                                                <p>সংক্ষিপ্ত/বিস্তারিত উত্তর - মূল্যায়ন করা হবে</p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    এই পরীক্ষার জন্য কোন প্রশ্ন পাওয়া যায়নি।
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <!-- Student View - Show their responses -->
                    <div class="card">
                        <div class="card-header bg-success text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-user-graduate me-2"></i>
                                আপনার উত্তর
                            </h5>
                        </div>
                        <div class="card-body">
                            <?php if (isset($student_responses) && count($student_responses) > 0): ?>
                                <?php 
                                $total_marks = 0;
                                $obtained_marks = 0;
                                foreach ($student_responses as $index => $response): 
                                    $total_marks += $response['question_marks'];
                                    $obtained_marks += $response['marks_obtained'];
                                ?>
                                    <div class="question-container">
                                        <h5>প্রশ্ন <?php echo $index + 1; ?>: <?php echo htmlspecialchars($response['question_text']); ?></h5>
                                        <p><small class="text-muted">প্রাপ্ত নম্বর: <?php echo $response['marks_obtained']; ?>/<?php echo $response['question_marks']; ?></small></p>
                                        
                                        <div class="student-response">
                                            <h6><i class="fas fa-user me-2"></i>আপনার উত্তর</h6>
                                            <?php if ($response['selected_option']): ?>
                                                <p>Option <?php echo htmlspecialchars($response['selected_option']); ?></p>
                                            <?php else: ?>
                                                <p><?php echo htmlspecialchars($response['written_answer']); ?></p>
                                            <?php endif; ?>
                                            
                                            <?php if ($response['selected_option'] == $response['correct_answer']): ?>
                                                <span class="badge bg-success">সঠিক</span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">ভুল</span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="correct-answer">
                                            <h6><i class="fas fa-check-circle me-2"></i>সঠিক উত্তর</h6>
                                            <p>Option <?php echo htmlspecialchars($response['correct_answer']); ?></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                
                                <div class="alert alert-info">
                                    <h5>মোট নম্বর: <?php echo $obtained_marks; ?>/<?php echo $total_marks; ?></h5>
                                    <p>শতাংশ: <?php echo $total_marks > 0 ? round(($obtained_marks / $total_marks) * 100, 2) : 0; ?>%</p>
                                </div>
                            <?php elseif (count($questions) > 0): ?>
                                <?php foreach ($questions as $index => $question): ?>
                                    <div class="question-container">
                                        <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="student-response">
                                                <h6><i class="fas fa-user me-2"></i>আপনার উত্তর</h6>
                                                <p class="text-muted">[উত্তর পাওয়া যায়নি]</p>
                                            </div>
                                            
                                            <div class="correct-answer">
                                                <h6><i class="fas fa-check-circle me-2"></i>সঠিক উত্তর</h6>
                                                <p>Option <?php echo $question['correct_answer']; ?></p>
                                            </div>
                                        <?php else: ?>
                                            <div class="student-response">
                                                <h6><i class="fas fa-user me-2"></i>আপনার উত্তর</h6>
                                                <p class="text-muted">[উত্তর পাওয়া যায়নি]</p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    এই পরীক্ষার জন্য কোন প্রশ্ন পাওয়া যায়নি।
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>