<?php
/**
 * صفحة أرشيف النتائج
 * Results Archive 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);

// معالجة الحذف
if (isset($_POST['delete_archive']) && isset($_POST['archive_id'])) {
    $archive_id = (int)$_POST['archive_id'];
    if ($resultsArchive->deleteArchive($archive_id)) {
        $delete_success = true;
    } else {
        $delete_error = true;
    }
}

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

// جلب النسخ المحفوظة
$archives = [];
if ($semester_id > 0) {
    if ($result_type) {
        $archives = $resultsArchive->getArchivedResults($result_type, $semester_id, $college_id);
    } else {
        // جلب جميع الأنواع
        $all_types = ['first_term', 'supplementary', 'removal_exam'];
        foreach ($all_types as $type) {
            $type_archives = $resultsArchive->getArchivedResults($type, $semester_id, $college_id);
            $archives = array_merge($archives, $type_archives);
        }
        // ترتيب حسب التاريخ
        usort($archives, function($a, $b) {
            return strtotime($b['saved_at']) - strtotime($a['saved_at']);
        });
    }
} else {
    // جلب جميع النسخ
    $archives = $resultsArchive->getAllArchives($college_id, $result_type);
}

// جلب الفصول والكليات
$semesters = $db->fetchAll(
    "SELECT * FROM semesters ORDER BY academic_year DESC, semester_number"
);

$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;
        }
    }
}

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>
        .archive-container {
            background: white;
            padding: 30px;
            margin: 20px auto;
            max-width: 1400px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .archive-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .archive-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px;
            text-align: center;
            border: 1px solid #555;
        }
        
        .archive-table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ddd;
        }
        
        .archive-table tbody tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        .archive-table tbody tr:hover {
            background-color: #f0f0f0;
        }
        
        .type-badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 12px;
            font-size: 0.9em;
            font-weight: bold;
        }
        
        .type-first_term {
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .type-supplementary {
            background: #fff3e0;
            color: #f57c00;
        }
        
        .type-removal_exam {
            background: #f3e5f5;
            color: #7b1fa2;
        }
    </style>
</head>
<body>
    <?php require_once __DIR__ . '/includes/header.php'; ?>
    
    <div class="container">
        <h1>أرشيف النتائج</h1>
        
        <?php if (isset($delete_success)): ?>
            <div style="background: #d4edda; color: #155724; padding: 12px; border-radius: 4px; margin-bottom: 20px;">
                ✓ تم حذف النسخة بنجاح
            </div>
        <?php endif; ?>
        
        <?php if (isset($delete_error)): ?>
            <div style="background: #f8d7da; color: #721c24; padding: 12px; border-radius: 4px; margin-bottom: 20px;">
                ✗ حدث خطأ عند حذف النسخة
            </div>
        <?php endif; ?>
        
        <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="results_archive_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">
                            <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; ?>
                    
                    <div class="form-group">
                        <label>الفصل الدراسي:</label>
                        <select name="semester_id">
                            <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>
                    
                    <div class="form-group">
                        <label>نوع النتيجة:</label>
                        <select name="result_type">
                            <option value="">-- جميع الأنواع --</option>
                            <option value="first_term" <?php echo ($result_type == 'first_term') ? 'selected' : ''; ?>>نتيجة الدور الأول</option>
                            <option value="supplementary" <?php echo ($result_type == 'supplementary') ? 'selected' : ''; ?>>نتيجة الملاحق</option>
                            <option value="removal_exam" <?php echo ($result_type == 'removal_exam') ? 'selected' : ''; ?>>نتيجة إزالة الرسوب</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">🔍 بحث</button>
                    </div>
                </div>
            </form>
        </div>
        
        <?php if (!empty($archives)): ?>
            <div class="archive-container">
                <h2>النسخ المحفوظة</h2>
                <table class="archive-table">
                    <thead>
                        <tr>
                            <th>م</th>
                            <th>نوع النتيجة</th>
                            <th>الفصل الدراسي</th>
                            <th>الكلية</th>
                            <th>التخصص</th>
                            <th>عدد الطلاب</th>
                            <th>حفظ بواسطة</th>
                            <th>تاريخ الحفظ</th>
                            <th>ملاحظات</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $serial = 1;
                        foreach ($archives as $archive): 
                            $summary = $archive['summary_data_decoded'];
                            $total_students = $summary && isset($summary['total_students']) ? $summary['total_students'] : 0;
                            
                            $type_class = 'type-' . $archive['result_type'];
                            $type_name = $resultsArchive->getResultTypeName($archive['result_type']);
                        ?>
                            <tr>
                                <td><?php echo $serial++; ?></td>
                                <td>
                                    <span class="type-badge <?php echo $type_class; ?>">
                                        <?php echo htmlspecialchars($type_name); ?>
                                    </span>
                                </td>
                                <td>
                                    فصل <?php echo $archive['semester_number']; ?><br>
                                    <small><?php echo htmlspecialchars($archive['academic_year']); ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($archive['college_name'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($archive['major_name'] ?? '-'); ?></td>
                                <td><?php echo $total_students; ?></td>
                                <td><?php echo htmlspecialchars($archive['saved_by_name']); ?></td>
                                <td><?php echo date('Y-m-d H:i', strtotime($archive['saved_at'])); ?></td>
                                <td><?php echo htmlspecialchars($archive['notes'] ?? '-'); ?></td>
                                <td>
                                    <a href="view_archived_results.php?archive_id=<?php echo $archive['id']; ?>" class="btn btn-info" style="padding: 5px 10px; font-size: 0.9em;">عرض</a>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('هل أنت متأكد من حذف هذه النسخة؟');">
                                        <input type="hidden" name="delete_archive" value="1">
                                        <input type="hidden" name="archive_id" value="<?php echo $archive['id']; ?>">
                                        <button type="submit" class="btn btn-danger" style="padding: 5px 10px; font-size: 0.9em;">حذف</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="archive-container">
                <div style="text-align: center; padding: 40px; color: #666;">
                    لا توجد نسخ محفوظة
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <?php require_once __DIR__ . '/includes/footer.php'; ?>
</body>
</html>

