<?php
/**
 * صفحة السجل الأكاديمي للطالب
 * Academic Transcript Page
 */
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';

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

$db = Database::getInstance();

// دالة لتحويل رقم الفصل إلى نص عربي (الفصل الأول، الثاني، ...)
function getSemesterName($number) {
    switch ((int)$number) {
        case 1: return 'الأول';
        case 2: return 'الثاني';
        case 3: return 'الثالث';
        case 4: return 'الرابع';
        case 5: return 'الخامس';
        case 6: return 'السادس';
        case 7: return 'السابع';
        case 8: return 'الثامن';
        default: return (int)$number;
    }
}

$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// إذا كان طالب، يمكنه عرض سجله فقط
if ($auth->hasRole('student')) {
    $user = $auth->getCurrentUser();
    $student = $db->fetchOne(
        "SELECT * FROM students WHERE user_id = ?",
        [$user['id']]
    );
    if ($student) {
        $student_id = $student['id'];
    }
} else {
    // للمسؤولين: التحقق من الصلاحيات
    if (!$student_id || !$auth->canAccessStudent($student_id)) {
        header('Location: students.php');
        exit;
    }
}

if (!$student_id) {
    header('Location: students.php');
    exit;
}

// جلب معلومات الطالب
$student = $db->fetchOne(
    "SELECT s.*, m.name_ar as major_name, m.code as major_code, 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.id = ?",
    [$student_id]
);

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

// جلب جميع الفصول الدراسية والدرجات
$semesters_data = $db->fetchAll(
    "SELECT DISTINCT s.id as semester_id, s.semester_number, s.academic_year, s.start_date, s.end_date
     FROM semesters s
     INNER JOIN grades g ON s.id = g.semester_id
     WHERE g.student_id = ?
     ORDER BY s.academic_year, s.semester_number",
    [$student_id]
);

// جلب جميع الدرجات
$all_grades = $db->fetchAll(
    "SELECT g.*, c.code as course_code, c.name_ar as course_name, c.credit_hours,
     s.id as semester_id, s.semester_number, s.academic_year,
     COALESCE(g.calibrated_marks, g.marks) as display_marks,
     COALESCE(g.calibrated_letter_grade, g.letter_grade) as display_letter_grade,
     COALESCE(g.calibrated_points, g.points) as display_points
     FROM grades g
     JOIN courses c ON g.course_id = c.id
     JOIN semesters s ON g.semester_id = s.id
     WHERE g.student_id = ?
     ORDER BY s.academic_year, s.semester_number, c.code",
    [$student_id]
);

// تجميع الدرجات حسب الفصل
$grades_by_semester = [];
foreach ($all_grades as $grade) {
    $key = $grade['semester_id'];
    if (!isset($grades_by_semester[$key])) {
        $grades_by_semester[$key] = [
            'semester_id' => $grade['semester_id'],
            'semester_number' => $grade['semester_number'],
            'academic_year' => $grade['academic_year'],
            'grades' => []
        ];
    }
    $grades_by_semester[$key]['grades'][] = $grade;
}

// جلب المعدلات الفصلية
$semester_gpas = [];
$semester_gpas_db = $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]
);

foreach ($semester_gpas_db as $sgpa) {
    $key = $sgpa['semester_id'];
    $semester_gpas[$key] = $sgpa;
}

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

// حساب إجمالي الساعات المعتمدة
$total_credit_hours = 0;
$total_points = 0;
foreach ($all_grades as $grade) {
    // استثناء المواد المعفى منها
    if (strpos((string)$grade['display_letter_grade'], 'مع') !== false || 
        strpos((string)$grade['display_marks'], 'مع') !== false) {
        continue;
    }
    
    if ($grade['display_points'] !== null && is_numeric($grade['display_points']) && 
        $grade['credit_hours'] > 0) {
        $total_points += (float)$grade['credit_hours'] * (float)$grade['display_points'];
        $total_credit_hours += (float)$grade['credit_hours'];
    }
}

$calculated_cgpa = $total_credit_hours > 0 ? $total_points / $total_credit_hours : 0;
if ($cgpa) {
    $calculated_cgpa = (float)$cgpa['cgpa'];
    $total_credit_hours = (float)$cgpa['total_credit_hours'];
}

// تحديد التقدير النصي (المعدل الفصلي من 5)
// القواعد: >=4 ممتاز، >=3.5 جيد جداً، >=3 جيد، >=2.5 بدون رسوب مقبول، >=2.5 مع رسوب ملاحق، <2.5 إعادة السنة، <1.5 فصل بسبب المعدل
function getTextGrade($gpa, $failed_credits = 0) {
    if ($gpa < 1.5) return 'فصل';
    if ($gpa < 2.5) return 'إعادة السنة';
    if ($gpa >= 2.5 && $gpa < 3) {
        if ($failed_credits > 0) return 'ملاحق';
        return 'مقبول';
    }
    if ($gpa >= 3 && $gpa < 3.5) return 'جيد';
    if ($gpa >= 3.5 && $gpa < 4) return 'جيد جداً';
    if ($gpa >= 4 && $gpa <= 5) return 'ممتاز';
    return '-';
}

include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>السجل الأكاديمي - <?php echo htmlspecialchars($student['full_name_ar']); ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        @media print {
            body { background: white; }
            .no-print { display: none; }
            .page-break { page-break-after: always; }
        }
        .transcript-header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            border-bottom: 3px solid #667eea;
        }
        .transcript-header h1 {
            color: #667eea;
            margin-bottom: 10px;
        }
        .student-info-section {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        .student-info-section table {
            width: 100%;
            border-collapse: collapse;
        }
        .student-info-section td {
            padding: 8px;
            border-bottom: 1px solid #ddd;
        }
        .student-info-section td:first-child {
            font-weight: bold;
            width: 200px;
        }
        .semester-section {
            margin-bottom: 40px;
            page-break-inside: avoid;
        }
        .semester-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 8px 8px 0 0;
            margin-bottom: 0;
        }
        .semester-header h3 {
            margin: 0;
        }
        .transcript-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .transcript-table th {
            background: #667eea;
            color: white;
            padding: 12px;
            text-align: right;
            font-weight: bold;
        }
        .transcript-table td {
            padding: 10px;
            border-bottom: 1px solid #ddd;
            text-align: right;
        }
        .transcript-table tr:hover {
            background: #f9f9f9;
        }
        .semester-summary {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 0 0 8px 8px;
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
        }
        .summary-item {
            text-align: center;
        }
        .summary-item strong {
            display: block;
            font-size: 20px;
            color: #667eea;
            margin-bottom: 5px;
        }
        .summary-item span {
            color: #666;
            font-size: 14px;
        }
        .cgpa-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            margin-top: 30px;
        }
        .cgpa-section h2 {
            margin-bottom: 20px;
        }
        .cgpa-value {
            font-size: 48px;
            font-weight: bold;
            margin: 10px 0;
        }
        .cgpa-text {
            font-size: 24px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="no-print" style="margin-bottom: 20px;">
            <div class="page-header">
                <h2>السجل الأكاديمي</h2>
                <div>
                    <button onclick="window.print()" class="btn btn-primary">🖨️ طباعة</button>
                    <?php if (!$auth->hasRole('student')): ?>
                        <a href="students.php" class="btn btn-secondary">العودة</a>
                        <a href="student_details.php?id=<?php echo $student_id; ?>" class="btn btn-info">تفاصيل الطالب</a>
                    <?php else: ?>
                        <a href="dashboard.php" class="btn btn-secondary">العودة</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="transcript-header">
            <h1>السجل الأكاديمي</h1>
            <p style="font-size: 18px; color: #666;">نظام نتائج الجامعة</p>
        </div>
        
        <div class="student-info-section">
            <table>
                <tr>
                    <td>الاسم الكامل:</td>
                    <td><?php echo htmlspecialchars($student['full_name_ar']); ?></td>
                    <td>الرقم الجامعي:</td>
                    <td><?php echo htmlspecialchars($student['student_number']); ?></td>
                </tr>
                <tr>
                    <td>التخصص:</td>
                    <td><?php echo htmlspecialchars($student['major_name']); ?> (<?php echo htmlspecialchars($student['major_code']); ?>)</td>
                    <td>الكلية:</td>
                    <td><?php echo htmlspecialchars($student['college_name']); ?></td>
                </tr>
                <tr>
                    <td>تاريخ التسجيل:</td>
                    <td><?php echo date('Y-m-d', strtotime($student['enrollment_date'])); ?></td>
                    <td>الحالة:</td>
                    <td>
                        <?php
                        $status_text = [
                            'active' => 'نشط',
                            'suspended' => 'موقوف',
                            'graduated' => 'متخرج',
                            'withdrawn' => 'منسحب'
                        ];
                        echo $status_text[$student['status']] ?? $student['status'];
                        ?>
                    </td>
                </tr>
            </table>
        </div>
        
        <?php if (empty($semesters_data)): ?>
            <div class="alert alert-info">
                لا توجد درجات مسجلة للطالب.
            </div>
        <?php else: ?>
            <?php foreach ($semesters_data as $semester): ?>
                <?php
                $semester_id = $semester['semester_id'];
                $grades = isset($grades_by_semester[$semester_id]) ? $grades_by_semester[$semester_id]['grades'] : [];
                $semester_gpa = isset($semester_gpas[$semester_id]) ? $semester_gpas[$semester_id] : null;
                ?>
                
                <div class="semester-section">
                    <div class="semester-header">
                        <h3>الفصل الدراسي <?php echo htmlspecialchars(getSemesterName($semester['semester_number'])); ?> - العام الدراسي <?php echo htmlspecialchars($semester['academic_year']); ?></h3>
                    </div>
                    
                    <?php if (!empty($grades)): ?>
                        <table class="transcript-table">
                            <thead>
                                <tr>
                                    <th>رمز المادة</th>
                                    <th>اسم المادة</th>
                                    <th>الساعات المعتمدة</th>
                                    <th>الدرجة</th>
                                    <th>التقدير</th>
                                    <th>النقاط</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $semester_total_points = 0;
                                $semester_total_credits = 0;
                                ?>
                                <?php foreach ($grades as $grade): ?>
                                    <?php
                                    // استثناء المواد المعفى منها من الحساب
                                    $is_exempt = (strpos((string)$grade['display_letter_grade'], 'مع') !== false || 
                                                 strpos((string)$grade['display_marks'], 'مع') !== false);
                                    
                                    if (!$is_exempt && $grade['display_points'] !== null && 
                                        is_numeric($grade['display_points']) && $grade['credit_hours'] > 0) {
                                        $semester_total_points += (float)$grade['credit_hours'] * (float)$grade['display_points'];
                                        $semester_total_credits += (float)$grade['credit_hours'];
                                    }
                                    ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($grade['course_code']); ?></td>
                                        <td><?php echo htmlspecialchars($grade['course_name']); ?></td>
                                        <td><?php echo htmlspecialchars($grade['credit_hours']); ?></td>
                                        <td>
                                            <?php 
                                            if ($grade['display_marks'] !== null && is_numeric($grade['display_marks'])) {
                                                echo number_format((float)$grade['display_marks'], 2);
                                            } else {
                                                echo htmlspecialchars($grade['display_marks'] ?? '-');
                                            }
                                            ?>
                                        </td>
                                        <td><?php echo htmlspecialchars(cleanLetterGrade($grade['display_letter_grade'] ?? '-')); ?></td>
                                        <td>
                                            <?php 
                                            if ($grade['display_points'] !== null && is_numeric($grade['display_points'])) {
                                                echo number_format((float)$grade['display_points'], 2);
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        
                        <div class="semester-summary">
                            <div class="summary-item">
                                <strong><?php 
                                    $gpa = $semester_gpa ? (float)$semester_gpa['gpa'] : 
                                           ($semester_total_credits > 0 ? round($semester_total_points / $semester_total_credits, 2) : 0);
                                    echo number_format($gpa, 2);
                                ?></strong>
                                <span>المعدل الفصلي (GPA)</span>
                            </div>
                            <div class="summary-item">
                                <strong><?php echo getTextGrade($gpa); ?></strong>
                                <span>التقدير</span>
                            </div>
                            <div class="summary-item">
                                <strong><?php 
                                    $credits = $semester_gpa ? (float)$semester_gpa['total_credit_hours'] : $semester_total_credits;
                                    echo number_format($credits, 1);
                                ?></strong>
                                <span>إجمالي الساعات المعتمدة</span>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info" style="margin: 20px;">
                            لا توجد درجات مسجلة في هذا الفصل.
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
            
            <div class="cgpa-section">
                <h2>المعدل التراكمي</h2>
                <div class="cgpa-value"><?php echo number_format($calculated_cgpa, 2); ?></div>
                <div class="cgpa-text"><?php echo getTextGrade($calculated_cgpa); ?></div>
                <div style="margin-top: 20px; font-size: 16px;">
                    إجمالي الساعات المعتمدة: <strong><?php echo number_format($total_credit_hours, 1); ?></strong>
                </div>
            </div>
        <?php endif; ?>
        
        <div style="text-align: center; margin-top: 40px; padding: 20px; color: #666; font-size: 12px;">
            <p>تم إنشاء هذا السجل الأكاديمي تلقائياً من نظام نتائج الجامعة</p>
            <p>تاريخ الطباعة: <?php echo date('Y-m-d H:i:s'); ?></p>
        </div>
    </div>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>

