<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || !$auth->hasRole('student')) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();
$user = $auth->getCurrentUser();

// الحصول على معلومات الطالب
$student = $db->fetchOne(
    "SELECT s.*, m.name_ar as major_name, c.name_ar as college_name
     FROM students s
     JOIN majors m ON s.major_id = m.id
     JOIN colleges c ON s.college_id = c.id
     WHERE s.user_id = ?",
    [$user['id']]
);

if (!$student) {
    header('Location: dashboard.php');
    exit;
}

// جلب جميع الدرجات
$grades = $db->fetchAll(
    "SELECT sc.*, c.code as course_code, c.name_ar as course_name, c.credit_hours,
     g.marks, g.letter_grade, g.points, s.academic_year, s.semester_number
     FROM student_courses sc
     JOIN courses c ON sc.course_id = c.id
     JOIN semesters s ON sc.semester_id = s.id
     LEFT JOIN grades g ON sc.id = g.student_course_id
     WHERE sc.student_id = ?
     ORDER BY s.academic_year, s.semester_number, c.code",
    [$student['id']]
);

// جلب المعدلات الفصلية
$semester_gpas = $db->fetchAll(
    "SELECT sg.*, s.academic_year, s.semester_number
     FROM semester_gpas sg
     JOIN semesters s ON sg.semester_id = s.id
     WHERE sg.student_id = ?
     ORDER BY s.academic_year, s.semester_number",
    [$student['id']]
);

// المعدل التراكمي
$cgpa = $db->fetchOne(
    "SELECT * FROM cumulative_gpas WHERE student_id = ?",
    [$student['id']]
);

// تجميع الدرجات حسب الفصل
$grades_by_semester = [];
foreach ($grades as $grade) {
    $key = $grade['semester_id'];
    if (!isset($grades_by_semester[$key])) {
        $grades_by_semester[$key] = [
            'semester' => 'فصل ' . $grade['semester_number'] . ' - ' . $grade['academic_year'],
            'grades' => []
        ];
    }
    $grades_by_semester[$key]['grades'][] = $grade;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>عرض الدرجات</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="page-header">
            <h2>عرض الدرجات</h2>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h3>معلومات الطالب</h3>
            </div>
            <p><strong>الرقم الجامعي:</strong> <?php echo htmlspecialchars($student['student_number']); ?></p>
            <p><strong>الاسم:</strong> <?php echo htmlspecialchars($student['full_name_ar']); ?></p>
            <p><strong>الكلية:</strong> <?php echo htmlspecialchars($student['college_name']); ?></p>
            <p><strong>التخصص:</strong> <?php echo htmlspecialchars($student['major_name']); ?></p>
            <?php if ($cgpa): ?>
                <p><strong>المعدل التراكمي:</strong> <?php echo number_format($cgpa['cgpa'], 2); ?></p>
            <?php endif; ?>
        </div>
        
        <?php foreach ($grades_by_semester as $sem_id => $sem_data): ?>
            <div class="card">
                <div class="card-header">
                    <h3><?php echo htmlspecialchars($sem_data['semester']); ?></h3>
                    <?php 
                    $sem_gpa = array_filter($semester_gpas, function($g) use ($sem_id) {
                        return $g['semester_id'] == $sem_id;
                    });
                    if (!empty($sem_gpa)):
                        $gpa = reset($sem_gpa);
                    ?>
                        <p><strong>المعدل الفصلي:</strong> <?php echo number_format($gpa['gpa'], 2); ?></p>
                    <?php endif; ?>
                </div>
                
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>رمز المادة</th>
                                <th>اسم المادة</th>
                                <th>الساعات</th>
                                <th>الدرجة</th>
                                <th>التقدير</th>
                                <th>النقاط</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($sem_data['grades'] as $grade): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($grade['course_code']); ?></td>
                                    <td><?php echo htmlspecialchars($grade['course_name']); ?></td>
                                    <td><?php echo $grade['credit_hours']; ?></td>
                                    <td><?php echo $grade['marks'] ? number_format($grade['marks'], 2) : '-'; ?></td>
                                    <td><?php echo cleanLetterGrade($grade['letter_grade'] ?? '-'); ?></td>
                                    <td><?php echo $grade['points'] ?? '-'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>

