<?php
/**
 * صفحة عرض نتائج الملاحق
 * Supplementary Exam Results Page
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';
require_once __DIR__ . '/classes/SupplementaryResults.php';
require_once __DIR__ . '/classes/ResultsArchive.php';

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

$db = Database::getInstance();
$supplementaryResults = new SupplementaryResults($db);
$resultsArchive = new ResultsArchive($db);

// جلب المعاملات
$semester_id = isset($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
$college_id = isset($_GET['college_id']) ? (int)$_GET['college_id'] : null;
$major_id = isset($_GET['major_id']) ? (int)$_GET['major_id'] : null;
$student_id = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;

// جلب بيانات الطالب إذا كان محدد
$student_result = null;
if ($student_id > 0 && $semester_id > 0) {
    $student_result = $supplementaryResults->calculateSupplementaryResult($student_id, $semester_id);
}

// جلب التقرير الشامل إذا كان الفصل محدد
$report = null;
if ($semester_id > 0) {
    $report = $supplementaryResults->getSupplementaryReport($semester_id, $college_id, $major_id);
}

// معالجة حفظ النتائج (بعد جلب $report)
$save_success = false;
$save_error = null;
if (isset($_POST['save_results']) && $semester_id > 0 && $report) {
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : null;
    try {
        $archive_id = $resultsArchive->saveSupplementaryResults(
            $semester_id,
            $_SESSION['user_id'],
            $report,
            $college_id,
            $major_id,
            $notes
        );
        $save_success = true;
        // إعادة تحميل الصفحة بعد الحفظ الناجح
        header("Location: supplementary_results_page.php?semester_id=" . $semester_id . 
               ($college_id ? "&college_id=" . $college_id : "") . 
               ($major_id ? "&major_id=" . $major_id : "") . 
               "&saved=1");
        exit;
    } catch (Exception $e) {
        $save_error = $e->getMessage();
    }
}

// التحقق من رسالة الحفظ الناجح
if (isset($_GET['saved']) && $_GET['saved'] == 1) {
    $save_success = true;
}

// جلب الكليات والفصول للقوائم المنسدلة
$colleges = [];
if ($auth->hasRole('admin')) {
    $colleges = $db->fetchAll("SELECT * FROM colleges ORDER BY name_ar");
} else {
    $user_college_id = $_SESSION['college_id'] ?? 0;
    if ($user_college_id) {
        $colleges = $db->fetchAll("SELECT * FROM colleges WHERE id = ?", [$user_college_id]);
        if (empty($college_id)) {
            $college_id = $user_college_id;
        }
    }
}

$majors = [];
if ($college_id) {
    $majors = $db->fetchAll("SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar", [$college_id]);
}

$semesters = [];
if ($major_id) {
    $semesters = $db->fetchAll(
        "SELECT * FROM semesters WHERE major_id = ? ORDER BY academic_year DESC, semester_number",
        [$major_id]
    );
}

require_once __DIR__ . '/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>نتائج امتحانات الملاحق</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .results-container {
            background: white;
            padding: 30px;
            margin: 20px auto;
            max-width: 1400px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .result-card {
            background: #f9f9f9;
            padding: 20px;
            margin: 15px 0;
            border-radius: 8px;
            border-right: 4px solid #667eea;
        }
        
        .status-repeat {
            border-right-color: #e74c3c;
            background: #fee;
        }
        
        .status-removal {
            border-right-color: #f39c12;
            background: #fff8e1;
        }
        
        .status-pass {
            border-right-color: #27ae60;
            background: #e8f5e9;
        }
        
        .result-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .result-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px;
            text-align: center;
            border: 1px solid #555;
        }
        
        .result-table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ddd;
        }
        
        .result-table tbody tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        .summary-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .summary-box h3 {
            margin-top: 0;
        }
        
        .summary-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        
        .stat-item {
            background: rgba(255, 255, 255, 0.2);
            padding: 15px;
            border-radius: 5px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <?php require_once __DIR__ . '/includes/header.php'; ?>
    
    <div class="container">
        <h1>نتائج امتحانات الملاحق</h1>
        
        <div class="form-section" style="background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 30px;">
            <form method="GET" action="supplementary_results_page.php">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end;">
                    <?php if ($auth->hasRole('admin')): ?>
                    <div class="form-group">
                        <label>الكلية:</label>
                        <select name="college_id" id="college_id" onchange="this.form.submit()">
                            <option value="">-- جميع الكليات --</option>
                            <?php foreach ($colleges as $col): ?>
                                <option value="<?php echo $col['id']; ?>" <?php echo ($college_id == $col['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($col['name_ar']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($college_id)): ?>
                    <div class="form-group">
                        <label>التخصص:</label>
                        <select name="major_id" id="major_id" onchange="this.form.submit()">
                            <option value="">-- جميع التخصصات --</option>
                            <?php foreach ($majors as $major): ?>
                                <option value="<?php echo $major['id']; ?>" <?php echo ($major_id == $major['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($major['name_ar']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($major_id)): ?>
                    <div class="form-group">
                        <label>الفصل الدراسي:</label>
                        <select name="semester_id" required>
                            <option value="">-- اختر الفصل --</option>
                            <?php foreach ($semesters as $sem): ?>
                                <option value="<?php echo $sem['id']; ?>" <?php echo ($semester_id == $sem['id']) ? 'selected' : ''; ?>>
                                    فصل <?php echo $sem['semester_number']; ?> - <?php echo htmlspecialchars($sem['academic_year']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">عرض النتائج</button>
                    </div>
                </div>
            </form>
        </div>
        
        <?php if ($report): ?>
            <div class="results-container">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h2 style="margin: 0;">تقرير نتائج الملاحق</h2>
                    <form method="POST" style="margin: 0;" onsubmit="return confirm('هل أنت متأكد من حفظ نسخة من هذه النتائج؟');">
                        <input type="hidden" name="save_results" value="1">
                        <input type="hidden" name="semester_id" value="<?php echo $semester_id; ?>">
                        <input type="hidden" name="college_id" value="<?php echo $college_id ?? ''; ?>">
                        <input type="hidden" name="major_id" value="<?php echo $major_id ?? ''; ?>">
                        <input type="text" name="notes" placeholder="ملاحظات (اختياري)" style="padding: 8px; margin-left: 10px; border: 1px solid #ddd; border-radius: 4px;">
                        <button type="submit" class="btn btn-success" style="margin-left: 10px;">💾 حفظ نسخة من النتائج</button>
                    </form>
                </div>
                
                <?php if ($save_success): ?>
                    <div style="background: #d4edda; color: #155724; padding: 12px; border-radius: 4px; margin-bottom: 20px; border: 1px solid #c3e6cb;">
                        ✓ تم حفظ نسخة من النتائج بنجاح
                    </div>
                <?php endif; ?>
                
                <?php if ($save_error): ?>
                    <div style="background: #f8d7da; color: #721c24; padding: 12px; border-radius: 4px; margin-bottom: 20px; border: 1px solid #f5c6cb;">
                        ✗ حدث خطأ: <?php echo htmlspecialchars($save_error); ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($report['summary']['total_students'] > 0): ?>
                    <div class="summary-box">
                        <h3>ملخص النتائج</h3>
                        <div class="summary-stats">
                            <div class="stat-item">
                                <div>إجمالي الطلاب</div>
                                <div class="stat-number"><?php echo $report['summary']['total_students']; ?></div>
                            </div>
                            <div class="stat-item">
                                <div>يعيد السنة</div>
                                <div class="stat-number"><?php echo $report['summary']['repeat_year_count']; ?></div>
                            </div>
                            <div class="stat-item">
                                <div>يسمح له بامتحان إزالة الرسوب</div>
                                <div class="stat-number"><?php echo $report['summary']['removal_exam_count']; ?></div>
                            </div>
                            <div class="stat-item">
                                <div>ناجح</div>
                                <div class="stat-number"><?php echo $report['summary']['pass_count']; ?></div>
                            </div>
                        </div>
                    </div>
                    
                    <table class="result-table">
                        <thead>
                            <tr>
                                <th>م</th>
                                <th>الرقم الجامعي</th>
                                <th>اسم الطالب</th>
                                <th>عدد المواد الراسبة</th>
                                <th>النتيجة</th>
                                <th>الدرجة</th>
                                <th>المواد الراسبة</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $serial = 1;
                            foreach ($report['students'] as $student_data): 
                                $result = $student_data['result'];
                                $status_class = '';
                                if ($result['status'] == 'repeat_year') {
                                    $status_class = 'status-repeat';
                                } elseif ($result['status'] == 'removal_exam') {
                                    $status_class = 'status-removal';
                                } else {
                                    $status_class = 'status-pass';
                                }
                                
                                // تجهيز نص الدرجات
                                $grades_text = '';
                                if (!empty($result['all_courses_grades'])) {
                                    $grade_items = [];
                                    foreach ($result['all_courses_grades'] as $course_grade) {
                                        $grade_display = '';
                                        if ($course_grade['marks'] !== null && is_numeric($course_grade['marks'])) {
                                            $grade_display = $course_grade['marks'];
                                        } elseif ($course_grade['letter_grade']) {
                                            $grade_display = $course_grade['letter_grade'];
                                        } else {
                                            $grade_display = '-';
                                        }
                                        $grade_items[] = $course_grade['course_code'] . ': ' . $grade_display;
                                    }
                                    $grades_text = implode('<br>', $grade_items);
                                } else {
                                    $grades_text = '<span style="color: #999;">-</span>';
                                }
                            ?>
                                <tr>
                                    <td><?php echo $serial++; ?></td>
                                    <td><?php echo htmlspecialchars($student_data['student_number']); ?></td>
                                    <td><?php echo htmlspecialchars($student_data['full_name_ar']); ?></td>
                                    <td><?php echo $result['failed_count']; ?> / <?php echo $result['total_supplementary_courses']; ?></td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($result['arabic_status']); ?></strong>
                                        <br>
                                        <small><?php echo htmlspecialchars($result['message']); ?></small>
                                    </td>
                                    <td style="text-align: right; font-size: 0.9em;"><?php echo $grades_text; ?></td>
                                    <td>
                                        <?php if (!empty($result['failed_courses'])): ?>
                                            <?php 
                                            $course_names = array_map(function($c) {
                                                return $c['course_name'];
                                            }, $result['failed_courses']);
                                            echo htmlspecialchars(implode('، ', $course_names));
                                            ?>
                                        <?php else: ?>
                                            <span style="color: green;">لا يوجد</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div style="text-align: center; padding: 40px; color: #666;">
                        لا توجد نتائج متاحة
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
        <?php if ($student_result && $student_id > 0): ?>
            <div class="results-container">
                <h2>نتيجة طالب محدد</h2>
                <?php
                $status_class = '';
                if ($student_result['status'] == 'repeat_year') {
                    $status_class = 'status-repeat';
                } elseif ($student_result['status'] == 'removal_exam') {
                    $status_class = 'status-removal';
                } else {
                    $status_class = 'status-pass';
                }
                ?>
                <div class="result-card <?php echo $status_class; ?>">
                    <h3><?php echo htmlspecialchars($student_result['arabic_status']); ?></h3>
                    <p><?php echo htmlspecialchars($student_result['message']); ?></p>
                    <p><strong>عدد المواد الراسبة:</strong> <?php echo $student_result['failed_count']; ?> / <?php echo $student_result['total_supplementary_courses']; ?></p>
                    
                    <?php if (!empty($student_result['failed_courses'])): ?>
                        <h4>المواد الراسبة:</h4>
                        <ul>
                            <?php foreach ($student_result['failed_courses'] as $course): ?>
                                <li>
                                    <?php echo htmlspecialchars($course['course_code']); ?> - 
                                    <?php echo htmlspecialchars($course['course_name']); ?>
                                    (<?php echo htmlspecialchars($course['marks'] ?? $course['letter_grade'] ?? 'N/A'); ?>)
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>

