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

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Get exam ID from URL
$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;

if ($exam_id <= 0) {
    // If no exam ID provided, show list of exams to select from
    $stmt = $pdo->query("
        SELECT e.*, c.name as class_name, c.section as class_section,
               COUNT(es.id) as subject_count
        FROM exams e
        JOIN classes c ON e.class_id = c.id
        LEFT JOIN exam_subjects es ON e.id = es.exam_id
        GROUP BY e.id
        ORDER BY e.created_at DESC
    ");
    $exams = $stmt->fetchAll();
} else {
    // Get exam details
    $stmt = $pdo->prepare("
        SELECT e.*, c.name as class_name, c.section as class_section
        FROM exams e
        JOIN classes c ON e.class_id = c.id
        WHERE e.id = ?
    ");
    $stmt->execute([$exam_id]);
    $exam = $stmt->fetch();

    if (!$exam) {
        $error_message = 'পরীক্ষা খুঁজে পাওয়া যায়নি';
    } else {
        // Get exam subjects
        $stmt = $pdo->prepare("
            SELECT es.*, s.name as subject_name
            FROM exam_subjects es
            JOIN subjects s ON es.subject_id = s.id
            WHERE es.exam_id = ?
            ORDER BY s.name
        ");
        $stmt->execute([$exam_id]);
        $exam_subjects = $stmt->fetchAll();

        // Get students in this class
        $stmt = $pdo->prepare("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
            FROM students s
            WHERE s.class_id = ? AND s.status = 'active'
            ORDER BY s.roll_number
        ");
        $stmt->execute([$exam['class_id']]);
        $students = $stmt->fetchAll();

        // Handle result submission
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_results'])) {
            try {
                $pdo->beginTransaction();

                // Process each student's results
                foreach ($students as $student) {
                    $student_id = $student['id'];
                    
                    // Process each subject for this student
                    foreach ($exam_subjects as $subject) {
                        $subject_id = $subject['subject_id'];
                        $marks_key = "marks_{$student_id}_{$subject_id}";
                        $grade_key = "grade_{$student_id}_{$subject_id}";
                        $remarks_key = "remarks_{$student_id}_{$subject_id}";
                        
                        $marks_obtained = isset($_POST[$marks_key]) ? (float)$_POST[$marks_key] : null;
                        $grade = isset($_POST[$grade_key]) ? trim($_POST[$grade_key]) : '';
                        $remarks = isset($_POST[$remarks_key]) ? trim($_POST[$remarks_key]) : '';
                        
                        // Check if result already exists
                        $stmt = $pdo->prepare("
                            SELECT id FROM results 
                            WHERE student_id = ? AND exam_id = ? AND subject_id = ?
                        ");
                        $stmt->execute([$student_id, $exam_id, $subject_id]);
                        $existing_result = $stmt->fetch();
                        
                        if ($existing_result) {
                            // Update existing result
                            $stmt = $pdo->prepare("
                                UPDATE results 
                                SET marks_obtained = ?, grade = ?, remarks = ?
                                WHERE id = ?
                            ");
                            $stmt->execute([
                                $marks_obtained !== null ? $marks_obtained : null,
                                $grade,
                                $remarks,
                                $existing_result['id']
                            ]);
                        } else {
                            // Insert new result
                            if ($marks_obtained !== null || !empty($grade) || !empty($remarks)) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO results (student_id, exam_id, subject_id, marks_obtained, grade, remarks)
                                    VALUES (?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->execute([
                                    $student_id,
                                    $exam_id,
                                    $subject_id,
                                    $marks_obtained !== null ? $marks_obtained : null,
                                    $grade,
                                    $remarks
                                ]);
                            }
                        }
                    }
                }
                
                $pdo->commit();
                $success_message = 'ফলাফল সফলভাবে সংরক্ষণ করা হয়েছে';
                
            } catch (Exception $e) {
                $pdo->rollBack();
                $error_message = 'ফলাফল সংরক্ষণে সমস্যা হয়েছে: ' . $e->getMessage();
            }
        }

        // Get existing results for this exam
        $stmt = $pdo->prepare("
            SELECT r.*, s.student_id as student_identifier
            FROM results r
            JOIN students s ON r.student_id = s.id
            WHERE r.exam_id = ?
            ORDER BY s.roll_number, r.subject_id
        ");
        $stmt->execute([$exam_id]);
        $existing_results = $stmt->fetchAll();
        
        // Organize results by student and subject for easier access
        $results_map = [];
        foreach ($existing_results as $result) {
            $results_map[$result['student_id']][$result['subject_id']] = $result;
        }
        
        // Also get detailed marks from the marks entry system (if any)
        // This will include data from the marks/entry.php system
        $detailed_marks_map = [];
        foreach ($exam_subjects as $subject) {
            $subject_id = $subject['subject_id'];
            
            // Try to get detailed marks for this subject from the marks entry system
            $stmt = $pdo->prepare("
                SELECT r.*, s.student_id as student_identifier
                FROM results r
                JOIN students s ON r.student_id = s.id
                WHERE r.subject_id = ? AND r.exam_id IS NULL AND r.session = ? AND r.exam_type IN ('midterm', 'final')
                AND s.class_id = ?
                ORDER BY s.roll_number
            ");
            // Use exam date as session for now, or you could use academic year
            $session = date('Y', strtotime($exam['exam_date']));
            $stmt->execute([$subject_id, $session, $exam['class_id']]);
            $detailed_results = $stmt->fetchAll();
            
            foreach ($detailed_results as $detailed_result) {
                $detailed_marks_map[$detailed_result['student_id']][$subject_id] = $detailed_result;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পরীক্ষার ফলাফল - স্কুল ম্যানেজমেন্ট সিস্টেম</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">
    <style>
        body { font-family: 'Kalpurush', Arial, sans-serif; }
        .table th { background-color: #f8f9fa; }
        .marks-input { width: 80px; }
        .grade-input { width: 80px; }
        .subject-header { 
            writing-mode: vertical-lr; 
            text-orientation: mixed;
            transform: rotate(180deg);
            white-space: nowrap;
            height: 150px;
            padding: 5px;
        }
        .student-row:hover { background-color: #f8f9fa; }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="manage.php">
                    <i class="fas fa-arrow-left"></i> পরীক্ষা ব্যবস্থাপনা
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($exam_id <= 0): ?>
            <!-- Exam Selection Page -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-list"></i> পরীক্ষা নির্বাচন করুন</h5>
                        </div>
                        <div class="card-body">
                            <?php if (empty($exams)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">কোন পরীক্ষা নেই</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>পরীক্ষার নাম</th>
                                                <th>ক্লাস</th>
                                                <th>তারিখ</th>
                                                <th>বিষয়</th>
                                                <th>অবস্থা</th>
                                                <th>কার্যক্রম</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($exams as $exam): ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo htmlspecialchars($exam['name']); ?></strong>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-primary">
                                                            <?php echo $exam['class_name'] . '-' . $exam['class_section']; ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo date('d/m/Y', strtotime($exam['exam_date'])); ?></td>
                                                    <td>
                                                        <span class="badge bg-info"><?php echo $exam['subject_count']; ?> টি</span>
                                                    </td>
                                                    <td>
                                                        <?php
                                                        $status_class = '';
                                                        $status_text = '';
                                                        switch ($exam['status']) {
                                                            case 'scheduled':
                                                                $status_class = 'bg-info';
                                                                $status_text = 'নির্ধারিত';
                                                                break;
                                                            case 'ongoing':
                                                                $status_class = 'bg-warning';
                                                                $status_text = 'চলমান';
                                                                break;
                                                            case 'completed':
                                                                $status_class = 'bg-success';
                                                                $status_text = 'সম্পন্ন';
                                                                break;
                                                            case 'cancelled':
                                                                $status_class = 'bg-danger';
                                                                $status_text = 'বাতিল';
                                                                break;
                                                        }
                                                        ?>
                                                        <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                                    </td>
                                                    <td>
                                                        <a href="?exam_id=<?php echo $exam['id']; ?>" 
                                                           class="btn btn-success btn-sm">
                                                            <i class="fas fa-chart-line"></i> ফলাফল এন্ট্রি
                                                        </a>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <!-- Results Entry Page -->
            <?php if (isset($exam) && $exam): ?>
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <div>
                                    <h5><i class="fas fa-chart-line"></i> <?php echo htmlspecialchars($exam['name']); ?> - ফলাফল এন্ট্রি</h5>
                                    <p class="mb-0">
                                        ক্লাস: <?php echo $exam['class_name'] . '-' . $exam['class_section']; ?> | 
                                        তারিখ: <?php echo date('d/m/Y', strtotime($exam['exam_date'])); ?> |
                                        পূর্ণমান: <?php echo $exam['total_marks']; ?> | 
                                        পাশ নম্বর: <?php echo $exam['pass_marks']; ?>
                                    </p>
                                </div>
                                <div>
                                    <a href="?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">
                                        <i class="fas fa-sync"></i> রিফ্রেশ
                                    </a>
                                    <a href="manage.php" class="btn btn-secondary">
                                        <i class="fas fa-arrow-left"></i> পরীক্ষা তালিকা
                                    </a>
                                </div>
                            </div>
                            <div class="card-body">
                                <?php if (empty($students)): ?>
                                    <div class="text-center py-4">
                                        <i class="fas fa-user-graduate fa-3x text-muted mb-3"></i>
                                        <p class="text-muted">এই ক্লাসে কোন শিক্ষার্থী নেই</p>
                                    </div>
                                <?php else: ?>
                                    <form method="POST" action="">
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-sm">
                                                <thead>
                                                    <tr>
                                                        <th rowspan="2" class="align-middle">রোল</th>
                                                        <th rowspan="2" class="align-middle">শিক্ষার্থীর নাম</th>
                                                        <th rowspan="2" class="align-middle">আইডি</th>
                                                        <th colspan="<?php echo count($exam_subjects); ?>" class="text-center">বিষয়সমূহ</th>
                                                        <th rowspan="2" class="align-middle">মোট</th>
                                                        <th rowspan="2" class="align-middle">গ্রেড</th>
                                                        <th rowspan="2" class="align-middle">জিপি</th>
                                                        <th rowspan="2" class="align-middle">জিপিএ</th>
                                                    </tr>
                                                    <tr>
                                                        <?php foreach ($exam_subjects as $subject): ?>
                                                            <th class="subject-header">
                                                                <?php echo htmlspecialchars($subject['subject_name']); ?>
                                                                <div class="small">(পূর্ণমান: <?php echo $subject['max_marks']; ?>)</div>
                                                            </th>
                                                        <?php endforeach; ?>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($students as $student): ?>
                                                        <tr class="student-row">
                                                            <td><?php echo $student['roll_number']; ?></td>
                                                            <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                            <td><?php echo $student['student_id']; ?></td>
                                                            
                                                            <?php 
                                                            $total_marks = 0;
                                                            $total_grade_points = 0;
                                                            $subject_count = 0;
                                                            
                                                            foreach ($exam_subjects as $subject): 
                                                                $subject_id = $subject['subject_id'];
                                                                $marks_key = "marks_{$student['id']}_{$subject_id}";
                                                                $grade_key = "grade_{$student['id']}_{$subject_id}";
                                                                $remarks_key = "remarks_{$student['id']}_{$subject_id}";
                                                                
                                                                // Check if we have detailed marks from marks entry system
                                                                $detailed_marks = isset($detailed_marks_map[$student['id']][$subject_id]) ? 
                                                                    $detailed_marks_map[$student['id']][$subject_id] : null;
                                                                
                                                                $existing_result = isset($results_map[$student['id']][$subject_id]) ? 
                                                                    $results_map[$student['id']][$subject_id] : null;
                                                                
                                                                // Use detailed marks if available, otherwise use exam results
                                                                if ($detailed_marks) {
                                                                    $marks_value = $detailed_marks['marks_obtained'];
                                                                    $grade_value = $detailed_marks['grade'];
                                                                    // Calculate grade point based on detailed marks
                                                                    $grade_point = 0;
                                                                    if ($marks_value !== null && $marks_value !== '') {
                                                                        $percentage = ($marks_value / $subject['max_marks']) * 100;
                                                                        if ($percentage >= 80) $grade_point = 5.0;
                                                                        elseif ($percentage >= 70) $grade_point = 4.0;
                                                                        elseif ($percentage >= 60) $grade_point = 3.5;
                                                                        elseif ($percentage >= 50) $grade_point = 3.0;
                                                                        elseif ($percentage >= 40) $grade_point = 2.0;
                                                                        elseif ($percentage >= 33) $grade_point = 1.0;
                                                                        else $grade_point = 0.0;
                                                                    }
                                                                } else {
                                                                    $marks_value = $existing_result ? $existing_result['marks_obtained'] : '';
                                                                    $grade_value = $existing_result ? $existing_result['grade'] : '';
                                                                    
                                                                    // Calculate grade point based on marks
                                                                    $grade_point = 0;
                                                                    if ($marks_value !== null && $marks_value !== '') {
                                                                        $percentage = ($marks_value / $subject['max_marks']) * 100;
                                                                        if ($percentage >= 80) $grade_point = 5.0;
                                                                        elseif ($percentage >= 70) $grade_point = 4.0;
                                                                        elseif ($percentage >= 60) $grade_point = 3.5;
                                                                        elseif ($percentage >= 50) $grade_point = 3.0;
                                                                        elseif ($percentage >= 40) $grade_point = 2.0;
                                                                        elseif ($percentage >= 33) $grade_point = 1.0;
                                                                        else $grade_point = 0.0;
                                                                    }
                                                                }
                                                                
                                                                if ($marks_value !== null && $marks_value !== '') {
                                                                    $total_marks += (float)$marks_value;
                                                                    $total_grade_points += $grade_point;
                                                                    $subject_count++;
                                                                }
                                                            ?>
                                                                <td>
                                                                    <input type="number" 
                                                                           name="<?php echo $marks_key; ?>" 
                                                                           class="form-control form-control-sm marks-input" 
                                                                           placeholder="নম্বর" 
                                                                           min="0" 
                                                                           max="<?php echo $subject['max_marks']; ?>"
                                                                           step="0.01"
                                                                           value="<?php echo $marks_value; ?>"
                                                                           data-max-marks="<?php echo $subject['max_marks']; ?>"
                                                                           <?php echo $detailed_marks ? 'readonly' : ''; ?>>
                                                                    <input type="text" 
                                                                           name="<?php echo $grade_key; ?>" 
                                                                           class="form-control form-control-sm grade-input mt-1" 
                                                                           placeholder="গ্রেড" 
                                                                           maxlength="5"
                                                                           value="<?php echo htmlspecialchars($grade_value); ?>"
                                                                           readonly>
                                                                    <div class="small text-muted mt-1 gp-display">
                                                                        <?php echo $marks_value !== '' && $marks_value !== null ? number_format($grade_point, 1) : ''; ?>
                                                                    </div>
                                                                    <?php if ($detailed_marks): ?>
                                                                        <div class="small text-info mt-1">
                                                                            <i class="fas fa-check-circle"></i> মার্কস এন্ট্রি থেকে
                                                                        </div>
                                                                    <?php endif; ?>
                                                                </td>
                                                            <?php endforeach; ?>
                                                            
                                                            <td>
                                                                <strong><?php echo $subject_count > 0 ? number_format($total_marks, 2) : ''; ?></strong>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                // Calculate overall grade based on average
                                                                $overall_grade = '';
                                                                if ($subject_count > 0 && $exam['total_marks'] > 0) {
                                                                    $percentage = ($total_marks / ($subject_count * $exam['total_marks'])) * 100;
                                                                    if ($percentage >= 80) $overall_grade = 'A+';
                                                                    elseif ($percentage >= 70) $overall_grade = 'A';
                                                                    elseif ($percentage >= 60) $overall_grade = 'A-';
                                                                    elseif ($percentage >= 50) $overall_grade = 'B';
                                                                    elseif ($percentage >= 40) $overall_grade = 'C';
                                                                    elseif ($percentage >= 33) $overall_grade = 'D';
                                                                    else $overall_grade = 'F';
                                                                }
                                                                echo $overall_grade;
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                // Display total grade points
                                                                echo $subject_count > 0 ? number_format($total_grade_points, 1) : '';
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                // Calculate GPA (Grade Point Average)
                                                                $gpa = 0;
                                                                if ($subject_count > 0) {
                                                                    $gpa = $total_grade_points / $subject_count;
                                                                }
                                                                echo $subject_count > 0 ? number_format($gpa, 2) : '';
                                                                ?>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mt-3">
                                            <button type="submit" name="save_results" class="btn btn-success">
                                                <i class="fas fa-save"></i> ফলাফল সংরক্ষণ করুন
                                            </button>
                                            <a href="manage.php" class="btn btn-secondary">
                                                <i class="fas fa-arrow-left"></i> পরীক্ষা তালিকা
                                            </a>
                                        </div>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-calculate grade, GP, and GPA when marks input changes
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('marks-input')) {
                // Find the student row
                const row = e.target.closest('.student-row');
                if (row) {
                    // Get max marks for this subject
                    const maxMarks = parseFloat(e.target.dataset.maxMarks) || 100;
                    
                    // Get the marks value
                    const marksValue = parseFloat(e.target.value);
                    
                    // Find the corresponding grade input and GP display
                    const gradeInput = e.target.closest('td').querySelector('.grade-input');
                    const gpDisplay = e.target.closest('td').querySelector('.gp-display');
                    
                    // Calculate grade and grade point based on marks
                    let grade = '';
                    let gradePoint = 0;
                    
                    if (!isNaN(marksValue) && marksValue >= 0) {
                        const percentage = (marksValue / maxMarks) * 100;
                        
                        if (percentage >= 80) {
                            grade = 'A+';
                            gradePoint = 5.0;
                        } else if (percentage >= 70) {
                            grade = 'A';
                            gradePoint = 4.0;
                        } else if (percentage >= 60) {
                            grade = 'A-';
                            gradePoint = 3.5;
                        } else if (percentage >= 50) {
                            grade = 'B';
                            gradePoint = 3.0;
                        } else if (percentage >= 40) {
                            grade = 'C';
                            gradePoint = 2.0;
                        } else if (percentage >= 33) {
                            grade = 'D';
                            gradePoint = 1.0;
                        } else {
                            grade = 'F';
                            gradePoint = 0.0;
                        }
                    }
                    
                    // Update grade input and GP display
                    if (gradeInput) gradeInput.value = grade;
                    if (gpDisplay) gpDisplay.textContent = !isNaN(marksValue) && marksValue >= 0 ? gradePoint.toFixed(1) : '';
                    
                    // Calculate total marks for this student
                    let total = 0;
                    let totalGradePoints = 0;
                    let count = 0;
                    const marksInputs = row.querySelectorAll('.marks-input');
                    
                    marksInputs.forEach(input => {
                        const value = parseFloat(input.value);
                        const max = parseFloat(input.dataset.maxMarks) || 100;
                        
                        if (!isNaN(value) && value >= 0) {
                            total += value;
                            count++;
                            
                            // Calculate grade point for this subject
                            const percentage = (value / max) * 100;
                            let gp = 0;
                            if (percentage >= 80) gp = 5.0;
                            else if (percentage >= 70) gp = 4.0;
                            else if (percentage >= 60) gp = 3.5;
                            else if (percentage >= 50) gp = 3.0;
                            else if (percentage >= 40) gp = 2.0;
                            else if (percentage >= 33) gp = 1.0;
                            else gp = 0.0;
                            
                            totalGradePoints += gp;
                        }
                    });
                    
                    // Update total marks display
                    const totalCell = row.querySelector('td:nth-last-child(4) strong');
                    if (totalCell) {
                        totalCell.textContent = count > 0 ? total.toFixed(2) : '';
                    }
                    
                    // Calculate and update grade
                    const gradeCell = row.querySelector('td:nth-last-child(3)');
                    if (gradeCell && count > 0) {
                        // Get exam total marks from the first subject (assuming all subjects have same max marks)
                        const examTotalMarks = <?php echo isset($exam_subjects[0]) ? $exam_subjects[0]['max_marks'] : 100; ?>;
                        if (examTotalMarks > 0) {
                            const percentage = (total / (count * examTotalMarks)) * 100;
                            let overallGrade = '';
                            if (percentage >= 80) overallGrade = 'A+';
                            else if (percentage >= 70) overallGrade = 'A';
                            else if (percentage >= 60) overallGrade = 'A-';
                            else if (percentage >= 50) overallGrade = 'B';
                            else if (percentage >= 40) overallGrade = 'C';
                            else if (percentage >= 33) overallGrade = 'D';
                            else overallGrade = 'F';
                            
                            gradeCell.textContent = overallGrade;
                        }
                    }
                    
                    // Update total GP display
                    const gpCell = row.querySelector('td:nth-last-child(2)');
                    if (gpCell) {
                        gpCell.textContent = count > 0 ? totalGradePoints.toFixed(1) : '';
                    }
                    
                    // Update GPA display
                    const gpaCell = row.querySelector('td:nth-last-child(1)');
                    if (gpaCell && count > 0) {
                        const gpa = totalGradePoints / count;
                        gpaCell.textContent = gpa.toFixed(2);
                    } else if (gpaCell) {
                        gpaCell.textContent = '';
                    }
                }
            }
        });
    </script>
</body>
</html>