<?php
/**
 * صفحة للطلاب للبحث عن نتائجهم برقم الجلوس (الرقم الجامعي)
 * Student Results Search by Seat Number
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/ThorndikeCalibrator.php';

$db = Database::getInstance();
$message = '';
$student = null;
$student_grades = [];
$semester_gpas = [];
$cgpa = null;
$grades_by_semester = [];
$calibrated_grades_by_semester = [];
$view_type = isset($_GET['view_type']) ? $_GET['view_type'] : 'original'; // 'original' or 'calibrated'

// معالجة البحث (POST أو GET)
$seat_number = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['seat_number'])) {
    $seat_number = trim($_POST['seat_number']);
} elseif (isset($_GET['seat_number'])) {
    $seat_number = trim($_GET['seat_number']);
}

if (!empty($seat_number)) {
    // البحث عن الطالب بالرقم الجامعي (رقم الجلوس)
    $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.student_number = ?",
        [$seat_number]
    );
    
    if ($student) {
            // جلب جميع الدرجات
            $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, 
                 g.calibrated_marks, g.calibrated_letter_grade, g.calibrated_points,
                 s.academic_year, s.semester_number, s.id as semester_id
                 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']]
            );
            
            // تجميع الدرجات حسب الفصل
            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;
            }
            
            // تجميع الدرجات المعايرة حسب الفصل
            $calibrator = new ThorndikeCalibrator();
            foreach ($grades_by_semester as $sem_id => $sem_data) {
                $calibrated_grades_by_semester[$sem_id] = [
                    'semester' => $sem_data['semester'],
                    'grades' => []
                ];
                
                foreach ($sem_data['grades'] as $grade) {
                    if ($grade['calibrated_marks'] !== null) {
                        $calibrated_grades_by_semester[$sem_id]['grades'][] = $grade;
                    }
                }
            }
    } else {
        $message = '<div class="alert alert-error">❌ لم يتم العثور على طالب برقم الجلوس: ' . htmlspecialchars($seat_number) . '</div>';
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $message = '<div class="alert alert-warning">⚠️ يرجى إدخال رقم الجلوس</div>';
}
?>
<!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">
    <style>
        .search-container {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 40px;
            border-radius: 15px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            text-align: center;
            color: white;
        }
        .search-container h1 {
            color: white;
            margin-bottom: 20px;
            font-size: 2.5em;
        }
        .search-form {
            max-width: 500px;
            margin: 0 auto;
        }
        .search-input {
            width: 100%;
            padding: 20px;
            font-size: 1.3em;
            border: none;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .search-btn {
            width: 100%;
            padding: 15px;
            font-size: 1.2em;
            background: white;
            color: #667eea;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.2);
        }
        .student-info-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        .student-info-card h2 {
            color: #667eea;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 3px solid #667eea;
        }
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .info-item {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            border-right: 4px solid #667eea;
        }
        .info-item strong {
            color: #667eea;
            display: block;
            margin-bottom: 5px;
        }
        .semester-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            border-top: 5px solid #667eea;
        }
        .semester-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .semester-header h3 {
            margin: 0;
            color: white;
        }
        .gpa-badge {
            background: rgba(255,255,255,0.2);
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 1.3em;
            font-weight: bold;
        }
        .grades-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        .grades-table th {
            background: #667eea;
            color: white;
            padding: 15px;
            text-align: center;
            font-weight: bold;
        }
        .grades-table td {
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid #e0e0e0;
        }
        .grades-table tr:hover {
            background: #f8f9fa;
        }
        .grade-badge {
            display: inline-block;
            padding: 8px 15px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 1.1em;
        }
        .grade-A {
            background: #4caf50;
            color: white;
        }
        .grade-B {
            background: #2196F3;
            color: white;
        }
        .grade-C {
            background: #ff9800;
            color: white;
        }
        .grade-D {
            background: #ff5722;
            color: white;
        }
        .grade-F {
            background: #f44336;
            color: white;
        }
        .view-toggle {
            text-align: center;
            margin: 20px 0;
        }
        .view-toggle .btn {
            padding: 12px 30px;
            margin: 0 10px;
            border: 2px solid #667eea;
            background: white;
            color: #667eea;
            border-radius: 25px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s;
            font-weight: bold;
        }
        .view-toggle .btn.active {
            background: #667eea;
            color: white;
        }
        .view-toggle .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .calibration-info {
            background: #e8f5e9;
            border-right: 5px solid #4caf50;
            padding: 15px;
            border-radius: 10px;
            margin: 15px 0;
        }
        .comparison-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.9em;
            margin-right: 5px;
        }
        .comparison-up {
            background: #c8e6c9;
            color: #2e7d32;
        }
        .comparison-down {
            background: #ffcdd2;
            color: #c62828;
        }
        .comparison-same {
            background: #e0e0e0;
            color: #616161;
        }
        .cgpa-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .cgpa-card h2 {
            color: white;
            margin-bottom: 15px;
        }
        .cgpa-value {
            font-size: 4em;
            font-weight: bold;
            margin: 20px 0;
        }
        @media print {
            .search-container, .view-toggle {
                display: none;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="container">
        <div class="search-container">
            <h1>🔍 استعلام عن النتائج</h1>
            <p style="font-size: 1.2em; margin-bottom: 30px;">أدخل رقم الجلوس (الرقم الجامعي) للبحث عن النتائج</p>
            <form method="POST" class="search-form" autocomplete="off">
                <input type="text" 
                       name="seat_number" 
                       class="search-input" 
                       placeholder="أدخل رقم الجلوس (الرقم الجامعي)"
                       value="<?php echo isset($seat_number) && !empty($seat_number) ? htmlspecialchars($seat_number) : (isset($_POST['seat_number']) ? htmlspecialchars($_POST['seat_number']) : (isset($_GET['seat_number']) ? htmlspecialchars($_GET['seat_number']) : '')); ?>"
                       autocomplete="off"
                       inputmode="numeric"
                       required
                       autofocus>
                <button type="submit" class="search-btn">🔎 البحث عن النتائج</button>
            </form>
        </div>
        
        <?php echo $message; ?>
        
        <?php if ($student): ?>
            <div class="student-info-card">
                <h2>📋 معلومات الطالب</h2>
                <div class="info-grid">
                    <div class="info-item">
                        <strong>الرقم الجامعي (رقم الجلوس):</strong>
                        <?php echo htmlspecialchars($student['student_number']); ?>
                    </div>
                    <div class="info-item">
                        <strong>اسم الطالب:</strong>
                        <?php echo htmlspecialchars($student['full_name_ar']); ?>
                    </div>
                    <div class="info-item">
                        <strong>الكلية:</strong>
                        <?php echo htmlspecialchars($student['college_name']); ?>
                    </div>
                    <div class="info-item">
                        <strong>التخصص:</strong>
                        <?php echo htmlspecialchars($student['major_name']); ?>
                    </div>
                    <?php if ($student['national_id']): ?>
                    <div class="info-item">
                        <strong>الرقم الوطني:</strong>
                        <?php echo htmlspecialchars($student['national_id']); ?>
                    </div>
                    <?php endif; ?>
                    <div class="info-item">
                        <strong>الحالة:</strong>
                        <?php 
                        $status_labels = [
                            'active' => 'نشط',
                            'graduated' => 'متخرج',
                            'suspended' => 'موقوف',
                            'withdrawn' => 'منسحب'
                        ];
                        echo $status_labels[$student['status']] ?? $student['status'];
                        ?>
                    </div>
                </div>
            </div>
            
            <?php if ($cgpa): ?>
            <div class="cgpa-card">
                <h2>المعدل التراكمي</h2>
                <div class="cgpa-value"><?php echo number_format($cgpa['cgpa'], 2); ?></div>
                <p style="font-size: 1.2em;">من <?php echo number_format($cgpa['total_credit_hours'], 1); ?> ساعة معتمدة</p>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($grades_by_semester)): ?>
                <div class="view-toggle">
                    <a href="?seat_number=<?php echo urlencode($student['student_number']); ?>&view_type=original" 
                       class="btn <?php echo $view_type == 'original' ? 'active' : ''; ?>">
                        📊 النتائج الأصلية
                    </a>
                    <a href="?seat_number=<?php echo urlencode($student['student_number']); ?>&view_type=calibrated" 
                       class="btn <?php echo $view_type == 'calibrated' ? 'active' : ''; ?>">
                        📈 النتائج بعد المعايرة
                    </a>
                </div>
                
                <?php if ($view_type == 'original'): ?>
                    <?php foreach ($grades_by_semester as $sem_id => $sem_data): ?>
                        <div class="semester-card">
                            <div class="semester-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);
                                ?>
                                    <div class="gpa-badge">المعدل الفصلي: <?php echo number_format($gpa['gpa'], 2); ?></div>
                                <?php endif; ?>
                            </div>
                            
                            <table class="grades-table">
                                <thead>
                                    <tr>
                                        <th>رمز المادة</th>
                                        <th>اسم المادة</th>
                                        <th>الساعات</th>
                                        <th>التقدير</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($sem_data['grades'] as $grade): ?>
                                        <tr>
                                            <td><strong><?php echo htmlspecialchars($grade['course_code']); ?></strong></td>
                                            <td><?php echo htmlspecialchars($grade['course_name']); ?></td>
                                            <td><?php echo $grade['credit_hours']; ?></td>
                                            <td>
                                                <?php if ($grade['letter_grade']): ?>
                                                    <span class="grade-badge grade-<?php echo cleanLetterGrade($grade['letter_grade'])[0]; ?>">
                                                        <?php echo htmlspecialchars(cleanLetterGrade($grade['letter_grade'])); ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span style="color: #999;">-</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endforeach; ?>
                    
                <?php else: ?>
                    <?php 
                    // عرض النتائج المعايرة
                    $has_calibrated = false;
                    foreach ($grades_by_semester as $sem_id => $sem_data) {
                        foreach ($sem_data['grades'] as $grade) {
                            if ($grade['calibrated_marks'] !== null) {
                                $has_calibrated = true;
                                break 2;
                            }
                        }
                    }
                    ?>
                    
                    <?php if ($has_calibrated): ?>
                        <?php foreach ($grades_by_semester as $sem_id => $sem_data): ?>
                            <div class="semester-card">
                                <div class="semester-header">
                                    <h3><?php echo htmlspecialchars($sem_data['semester']); ?> - بعد المعايرة</h3>
                                    <?php 
                                    // حساب المعدل الفصلي المعاير
                                    $total_points_cal = 0;
                                    $total_hours_cal = 0;
                                    foreach ($sem_data['grades'] as $grade) {
                                        if ($grade['calibrated_marks'] !== null) {
                                            $total_points_cal += $grade['credit_hours'] * (float)$grade['calibrated_points'];
                                            $total_hours_cal += $grade['credit_hours'];
                                        }
                                    }
                                    $cal_gpa = $total_hours_cal > 0 ? round($total_points_cal / $total_hours_cal, 2) : 0;
                                    if ($cal_gpa > 0):
                                    ?>
                                        <div class="gpa-badge">المعدل الفصلي المعاير: <?php echo number_format($cal_gpa, 2); ?></div>
                                    <?php endif; ?>
                                </div>
                                
                                <?php 
                                $calibration_info = null;
                                $semester_info = $db->fetchOne("SELECT * FROM semesters WHERE id = ?", [$sem_id]);
                                if ($semester_info) {
                                    $calibrator = new ThorndikeCalibrator();
                                    $calibration_info = $calibrator->getCalibrationInfo($sem_id);
                                }
                                
                                if ($calibration_info):
                                ?>
                                    <div class="calibration-info">
                                        <strong>ℹ️ معلومات المعايرة:</strong>
                                        <ul style="margin-right: 20px; margin-top: 10px;">
                                            <li>المتوسط المستهدف: <?php echo $calibration_info['target_mean']; ?></li>
                                            <li>الانحراف المعياري المستهدف: <?php echo $calibration_info['target_std']; ?></li>
                                            <li>تمت المعايرة بواسطة: <?php echo htmlspecialchars($calibration_info['calibrated_by_name'] ?? 'غير معروف'); ?></li>
                                            <li>التاريخ: <?php echo date('Y-m-d H:i', strtotime($calibration_info['calibrated_at'])); ?></li>
                                        </ul>
                                    </div>
                                <?php endif; ?>
                                
                                <table class="grades-table">
                                    <thead>
                                        <tr>
                                            <th>رمز المادة</th>
                                            <th>اسم المادة</th>
                                            <th>الساعات</th>
                                            <th>التقدير</th>
                                            <th>المقارنة</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($sem_data['grades'] as $grade): ?>
                                            <?php if ($grade['calibrated_marks'] !== null): ?>
                                                <tr>
                                                    <td><strong><?php echo htmlspecialchars($grade['course_code']); ?></strong></td>
                                                    <td><?php echo htmlspecialchars($grade['course_name']); ?></td>
                                                    <td><?php echo $grade['credit_hours']; ?></td>
                                                    <td>
                                                        <span class="grade-badge grade-<?php echo cleanLetterGrade($grade['calibrated_letter_grade'])[0]; ?>">
                                                            <?php echo htmlspecialchars(cleanLetterGrade($grade['calibrated_letter_grade'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        $original = (float)$grade['marks'];
                                                        $calibrated = (float)$grade['calibrated_marks'];
                                                        $diff = $calibrated - $original;
                                                        $diff_sign = $diff > 0 ? '+' : '';
                                                        
                                                        if (abs($diff) < 0.01) {
                                                            $badge_class = 'comparison-same';
                                                            $badge_text = 'بدون تغيير';
                                                        } elseif ($diff > 0) {
                                                            $badge_class = 'comparison-up';
                                                            $badge_text = 'زيادة';
                                                        } else {
                                                            $badge_class = 'comparison-down';
                                                            $badge_text = 'نقص';
                                                        }
                                                        ?>
                                                        <span class="comparison-badge <?php echo $badge_class; ?>">
                                                            <?php echo $badge_text; ?>
                                                        </span>
                                                        <br>
                                                        <small style="color: #666;">
                                                            <?php echo number_format($original, 2); ?> 
                                                            → 
                                                            <?php echo number_format($calibrated, 2); ?>
                                                            <?php if (abs($diff) >= 0.01): ?>
                                                                (<?php echo $diff_sign . number_format($diff, 2); ?>)
                                                            <?php endif; ?>
                                                        </small>
                                                    </td>
                                                </tr>
                                            <?php elseif ($grade['marks']): ?>
                                                <tr style="opacity: 0.6;">
                                                    <td><strong><?php echo htmlspecialchars($grade['course_code']); ?></strong></td>
                                                    <td><?php echo htmlspecialchars($grade['course_name']); ?></td>
                                                    <td><?php echo $grade['credit_hours']; ?></td>
                                                    <td>
                                                        <span class="grade-badge grade-<?php echo $grade['letter_grade'][0]; ?>">
                                                            <?php echo htmlspecialchars($grade['letter_grade']); ?>
                                                        </span>
                                                    </td>
                                                    <td><span style="color: #999;">-</span></td>
                                                </tr>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endforeach; ?>
                        
                        <?php 
                        // حساب المعدل التراكمي المعاير
                        $total_points_cal_all = 0;
                        $total_hours_cal_all = 0;
                        foreach ($grades_by_semester as $sem_data) {
                            foreach ($sem_data['grades'] as $grade) {
                                if ($grade['calibrated_marks'] !== null) {
                                    $total_points_cal_all += $grade['credit_hours'] * (float)$grade['calibrated_points'];
                                    $total_hours_cal_all += $grade['credit_hours'];
                                }
                            }
                        }
                        $cal_cgpa = $total_hours_cal_all > 0 ? round($total_points_cal_all / $total_hours_cal_all, 2) : 0;
                        if ($cal_cgpa > 0):
                        ?>
                            <div class="cgpa-card" style="background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);">
                                <h2>المعدل التراكمي المعاير</h2>
                                <div class="cgpa-value"><?php echo number_format($cal_cgpa, 2); ?></div>
                                <p style="font-size: 1.2em;">من <?php echo number_format($total_hours_cal_all, 1); ?> ساعة معتمدة</p>
                                <?php if ($cgpa): ?>
                                    <p style="font-size: 1.1em; margin-top: 15px;">
                                        المعدل الأصلي: <?php echo number_format($cgpa['cgpa'], 2); ?> 
                                        → 
                                        المعدل المعاير: <?php echo number_format($cal_cgpa, 2); ?>
                                        <?php 
                                        $cgpa_diff = $cal_cgpa - $cgpa['cgpa'];
                                        if (abs($cgpa_diff) >= 0.01):
                                            $cgpa_sign = $cgpa_diff > 0 ? '+' : '';
                                        ?>
                                            (<?php echo $cgpa_sign . number_format($cgpa_diff, 2); ?>)
                                        <?php endif; ?>
                                    </p>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        
                    <?php else: ?>
                        <div class="alert alert-info" style="padding: 20px; border-radius: 10px; background: #e3f2fd; border-right: 5px solid #2196F3;">
                            <strong>ℹ️ ملاحظة:</strong> لا توجد درجات معايرة محفوظة لهذا الطالب.
                            <p style="margin-top: 10px;">يمكنك عرض النتائج الأصلية من الزر أعلاه.</p>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
                
                <div style="text-align: center; margin: 30px 0;">
                    <button onclick="window.print()" class="btn btn-primary" style="padding: 15px 40px; font-size: 1.2em;">
                        🖨️ طباعة النتائج
                    </button>
                </div>
                
            <?php else: ?>
                <div class="alert alert-info" style="padding: 20px; border-radius: 10px;">
                    <strong>ℹ️ لا توجد درجات مسجلة لهذا الطالب</strong>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>

