<?php
// index.php
// تفعيل عرض الأخطاء للتطوير
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'إدارة الكليات';
include '../../includes/header.php';

// التحقق من الجلسة
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

checkLogin();

// التحقق من الصلاحية
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../index.php');
    exit();
}

$db = getDB();
$colleges = [];
$search_term = $_GET['search'] ?? '';

try {
    $params = [];
    
    // ---------------------------------------------------------
    // تحديث الاستعلام: إضافة حساب عدد التدريسيين (faculty_count) والدخل السنوي (total_income)
    // ---------------------------------------------------------
    $sql = "SELECT 
                c.College_ID, 
                c.College,
                (SELECT COUNT(*) FROM departemenets d WHERE d.College_ID = c.College_ID) as dept_count,
                (SELECT COUNT(*) FROM students s WHERE s.College_ID = c.College_ID) as student_count,
                (SELECT COUNT(*) FROM faculty f WHERE f.College_ID = c.College_ID) as faculty_count,
                (SELECT SUM(Yearly_Cost) FROM students s WHERE s.College_ID = c.College_ID) as total_income
            FROM colleges c";

    // إضافة شرط البحث
    if (!empty($search_term)) {
        $sql .= " WHERE c.College LIKE ?";
        $params[] = '%' . $search_term . '%';
    }

    $sql .= " ORDER BY c.College ASC";

    if (method_exists($db, 'select')) {
        $colleges = $db->select($sql, $params);
    } else {
        // احتياط في حال كان الكلاس يدعم prepare
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $colleges = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

} catch (Exception $e) {
    $_SESSION['error_message'] = 'حدث خطأ في جلب البيانات: ' . $e->getMessage();
}
?>

<div class="content-area">
    <div class="page-header d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="page-title">الكليات</h2>
            <p class="page-subtitle">إدارة الكليات والأقسام التابعة لها.</p>
        </div>
        <?php if (hasPermission('add_college')): ?>
            <a href="add_college.php" class="btn btn-primary"><i class="fas fa-plus me-2"></i>إضافة كلية جديدة</a>
        <?php endif; ?>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">
            
            <form method="GET" class="row g-3 mb-4 justify-content-end">
                <div class="col-md-4">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="بحث عن اسم الكلية..." value="<?php echo htmlspecialchars($search_term); ?>">
                        <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button>
                    </div>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-hover align-middle table-striped">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 50px;">#</th>
                            <th>اسم الكلية</th>
                            <th class="text-center">عدد الأقسام</th>
                            <th class="text-center">عدد التدريسيين</th> 
                            <th class="text-center">إجمالي الطلاب</th>
                            <th class="text-center">الدخل السنوي</th>
                            <th class="text-center" style="width: 150px;">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($colleges)): ?>
                            <?php foreach ($colleges as $index => $college): ?>
                                <tr>
                                    <td><?php echo $index + 1; ?></td>
                                    <td>
                                        <div class="fw-bold text-primary">
                                            <i class="fas fa-university me-2"></i>
                                            <?php echo htmlspecialchars($college['College']); ?>
                                        </div>
                                    </td>
                                    
                                    <td class="text-center">
                                        <span class="badge bg-info text-dark">
                                            <?php echo $college['dept_count']; ?> قسم
                                        </span>
                                    </td>

                                    <td class="text-center">
                                        <span class="badge bg-secondary">
                                            <i class="fas fa-chalkboard-teacher me-1"></i>
                                            <?php echo $college['faculty_count']; ?>
                                        </span>
                                    </td>
                                    
                                    <td class="text-center">
                                        <span class="badge bg-success">
                                            <i class="fas fa-users me-1"></i>
                                            <?php echo $college['student_count']; ?> طالب
                                        </span>
                                    </td>

                                    <td class="text-center fw-bold text-primary">
                                        <?php echo $college['total_income'] ? number_format($college['total_income']) : '0'; ?>
                                    </td>

                                    <td class="text-center">
                                        <?php if (hasPermission('edit_college')): ?>
                                            <div class="btn-group">
                                                <a href="edit_college.php?id=<?php echo $college['College_ID']; ?>" class="btn btn-sm btn-outline-primary" title="تعديل">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                
                                                <button type="button" class="btn btn-sm btn-outline-danger" 
                                                        onclick="openDeleteModal(<?php echo $college['College_ID']; ?>, '<?php echo addslashes($college['College']); ?>', <?php echo $college['dept_count']; ?>, <?php echo $college['student_count']; ?>, <?php echo $college['faculty_count']; ?>)" 
                                                        title="حذف">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-muted small"><i class="fas fa-lock"></i> مقيد</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center py-5 text-muted">
                                    <i class="fas fa-folder-open fa-3x mb-3 d-block opacity-50"></i>
                                    لا توجد كليات مضافة حالياً.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">تأكيد حذف الكلية</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>هل أنت متأكد من رغبتك في حذف: <strong id="deleteName"></strong>؟</p>
                
                <div id="warnDept" class="alert alert-warning d-none">
                    <i class="fas fa-building me-2"></i>
                    تحتوي على (<strong id="cntDept"></strong>) قسم.
                </div>

                <div id="warnStd" class="alert alert-warning d-none">
                    <i class="fas fa-user-graduate me-2"></i>
                    تحتوي على (<strong id="cntStd"></strong>) طالب.
                </div>

                <div id="warnFac" class="alert alert-warning d-none">
                    <i class="fas fa-chalkboard-teacher me-2"></i>
                    تحتوي على (<strong id="cntFac"></strong>) تدريسي.
                </div>

                <p class="text-danger small mt-2 fw-bold">
                    <i class="fas fa-exclamation-triangle"></i>
                    تحذير: الحذف سيؤدي لإزالة جميع الأقسام، الطلاب، والأساتذة المرتبطين بهذه الكلية نهائياً.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <a href="#" id="deleteLink" class="btn btn-danger">نعم، احذف الكلية</a>
            </div>
        </div>
    </div>
</div>

<script>
    function openDeleteModal(id, name, deptCount, studentCount, facultyCount) {
        document.getElementById('deleteName').textContent = name;
        document.getElementById('deleteLink').href = 'delete_college.php?id=' + id;

        // تحذير الأقسام
        const dDept = document.getElementById('warnDept');
        if (deptCount > 0) {
            document.getElementById('cntDept').textContent = deptCount;
            dDept.classList.remove('d-none');
        } else {
            dDept.classList.add('d-none');
        }

        // تحذير الطلاب
        const dStd = document.getElementById('warnStd');
        if (studentCount > 0) {
            document.getElementById('cntStd').textContent = studentCount;
            dStd.classList.remove('d-none');
        } else {
            dStd.classList.add('d-none');
        }

        // تحذير الأساتذة
        const dFac = document.getElementById('warnFac');
        if (facultyCount > 0) {
            document.getElementById('cntFac').textContent = facultyCount;
            dFac.classList.remove('d-none');
        } else {
            dFac.classList.add('d-none');
        }

        var myModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        myModal.show();
    }
</script>

<?php include '../../includes/footer.php'; ?>