<?php
/**
 * صفحة عرض نسخة محفوظة من النتائج
 * View Archived Results Page
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.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();
$resultsArchive = new ResultsArchive($db);

// جلب معرف النسخة
$archive_id = isset($_GET['archive_id']) ? (int)$_GET['archive_id'] : 0;

if ($archive_id <= 0) {
    header('Location: results_archive_page.php');
    exit;
}

// جلب النسخة
$archive = $resultsArchive->getArchiveById($archive_id);

if (!$archive) {
    header('Location: results_archive_page.php');
    exit;
}

$report = $archive['result_data_decoded'];
$summary = $archive['summary_data_decoded'];

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>عرض نسخة محفوظة - <?php echo htmlspecialchars($resultsArchive->getResultTypeName($archive['result_type'])); ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .archive-view-container {
            background: white;
            padding: 30px;
            margin: 20px auto;
            max-width: 1400px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .archive-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        
        .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;
        }
        
        .export-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .export-buttons button {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s;
        }
        
        .export-buttons button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .btn-print {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-export {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .archive-view-container {
                box-shadow: none;
                padding: 0;
            }
            
            .result-table {
                font-size: 12px;
            }
            
            .result-table th,
            .result-table td {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
    <?php require_once __DIR__ . '/includes/header.php'; ?>
    
    <div class="container">
        <div class="archive-view-container">
            <div class="archive-header">
                <h2><?php echo htmlspecialchars($resultsArchive->getResultTypeName($archive['result_type'])); ?></h2>
                <p>
                    <strong>الفصل:</strong> فصل <?php echo $archive['semester_number']; ?> - <?php echo htmlspecialchars($archive['academic_year']); ?><br>
                    <?php if ($archive['college_name']): ?>
                        <strong>الكلية:</strong> <?php echo htmlspecialchars($archive['college_name']); ?><br>
                    <?php endif; ?>
                    <?php if ($archive['major_name']): ?>
                        <strong>التخصص:</strong> <?php echo htmlspecialchars($archive['major_name']); ?><br>
                    <?php endif; ?>
                    <strong>حفظ بواسطة:</strong> <?php echo htmlspecialchars($archive['saved_by_name']); ?><br>
                    <strong>تاريخ الحفظ:</strong> <?php echo date('Y-m-d H:i', strtotime($archive['saved_at'])); ?>
                    <?php if ($archive['notes']): ?>
                        <br><strong>ملاحظات:</strong> <?php echo htmlspecialchars($archive['notes']); ?>
                    <?php endif; ?>
                </p>
            </div>
            
            <?php if ($summary): ?>
                <div style="background: #f0f0f0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                    <h3>ملخص النتائج</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 15px;">
                        <?php if (isset($summary['total_students'])): ?>
                            <div><strong>إجمالي الطلاب:</strong> <?php echo $summary['total_students']; ?></div>
                        <?php endif; ?>
                        <?php if (isset($summary['repeat_year_count'])): ?>
                            <div><strong>يعيد السنة:</strong> <?php echo $summary['repeat_year_count']; ?></div>
                        <?php endif; ?>
                        <?php if (isset($summary['removal_exam_count'])): ?>
                            <div><strong>يسمح له بامتحان إزالة الرسوب:</strong> <?php echo $summary['removal_exam_count']; ?></div>
                        <?php endif; ?>
                        <?php if (isset($summary['pass_count'])): ?>
                            <div><strong>ناجح:</strong> <?php echo $summary['pass_count']; ?></div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($report['students'])): ?>
                <div class="no-print export-buttons">
                    <button onclick="window.print()" class="btn-print">🖨️ طباعة</button>
                    <button onclick="exportToExcel()" class="btn-export">📥 تصدير إلى Excel</button>
                </div>
                
                <table id="results-table" class="result-table">
                    <thead>
                        <tr>
                            <th>م</th>
                            <th>الرقم الجامعي</th>
                            <th>اسم الطالب</th>
                            <?php if ($archive['result_type'] == 'supplementary' || $archive['result_type'] == 'removal_exam'): ?>
                                <th>عدد المواد الراسبة</th>
                                <th>النتيجة</th>
                                <th>الدرجة</th>
                                <th>المواد الراسبة</th>
                            <?php else: ?>
                                <th>النتيجة</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $serial = 1;
                        foreach ($report['students'] as $student_data): 
                            $result = $student_data['result'] ?? [];
                        ?>
                            <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>
                                <?php if ($archive['result_type'] == 'supplementary' || $archive['result_type'] == 'removal_exam'): ?>
                                    <td>
                                        <?php 
                                        $failed_count = $result['failed_count'] ?? 0;
                                        $total_courses = $result['total_supplementary_courses'] ?? $result['total_removal_exam_courses'] ?? 0;
                                        echo $failed_count . ' / ' . $total_courses;
                                        ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($result['arabic_status'] ?? '-'); ?></td>
                                    <td>
                                        <?php if (!empty($result['all_courses_grades'])): ?>
                                            <?php 
                                            $grade_items = [];
                                            foreach ($result['all_courses_grades'] as $course_grade) {
                                                $grade_display = $course_grade['marks'] ?? $course_grade['letter_grade'] ?? '-';
                                                $grade_items[] = $grade_display;
                                            }
                                            echo implode('<br>', $grade_items);
                                            ?>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </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>
                                <?php else: ?>
                                    <td><?php echo htmlspecialchars($result['status'] ?? '-'); ?></td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div style="text-align: center; padding: 40px; color: #666;">
                    لا توجد بيانات متاحة
                </div>
            <?php endif; ?>
            
            <div class="no-print" style="margin-top: 30px; text-align: center;">
                <a href="results_archive_page.php" class="btn btn-primary">← العودة إلى الأرشيف</a>
            </div>
        </div>
    </div>
    
    <script>
        function exportToExcel() {
            const table = document.getElementById('results-table');
            
            if (!table) {
                alert('لا توجد بيانات للتصدير');
                return;
            }
            
            let csv = '';
            const rows = table.querySelectorAll('tr');
            
            rows.forEach(row => {
                const cols = row.querySelectorAll('th, td');
                const rowData = [];
                cols.forEach(col => {
                    // إزالة علامات HTML واستبدال الفواصل
                    let text = col.innerText || col.textContent || '';
                    text = text.replace(/"/g, '""'); // الهروب من علامات الاقتباس
                    text = text.replace(/\n/g, ' '); // استبدال الأسطر الجديدة بمسافات
                    rowData.push('"' + text + '"');
                });
                csv += rowData.join(',') + '\n';
            });
            
            // إنشاء ملف CSV وتنزيله
            const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            
            // اسم الملف
            const resultTypeName = '<?php echo htmlspecialchars($resultsArchive->getResultTypeName($archive['result_type']), ENT_QUOTES, 'UTF-8'); ?>';
            const semesterInfo = 'فصل_<?php echo $archive['semester_number']; ?>_<?php echo htmlspecialchars($archive['academic_year'], ENT_QUOTES, 'UTF-8'); ?>';
            // تنظيف اسم الملف من الأحرف الخاصة
            let fileName = resultTypeName + '_' + semesterInfo + '_' + new Date().getTime() + '.csv';
            fileName = fileName.replace(/[<>:"/\\|?*]/g, '_'); // استبدال الأحرف الخاصة
            fileName = fileName.replace(/\s+/g, '_'); // استبدال المسافات بشرطة سفلية
            
            link.setAttribute('download', fileName);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    </script>
    
    <?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>

