<?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();
$departments = [];
$search_term = $_GET['search'] ?? '';
$college_filter = $_GET['college_filter'] ?? '';

try {
    // جلب قائمة الكليات للفلتر
    $colleges_list = [];
    $col_sql = "SELECT College_ID, College FROM colleges ORDER BY College ASC";
    if (method_exists($db, 'select')) {
        $colleges_list = $db->select($col_sql);
    } else {
        $stmt = $db->prepare($col_sql);
        $stmt->execute();
        $colleges_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $params = [];
    $where_clauses = [];

    if (!empty($search_term)) {
        $where_clauses[] = "(d.Departement LIKE ? OR c.College LIKE ?)";
        $params[] = '%' . $search_term . '%';
        $params[] = '%' . $search_term . '%';
    }

    if (!empty($college_filter)) {
        $where_clauses[] = "d.College_ID = ?";
        $params[] = $college_filter;
    }

    $where_sql = !empty($where_clauses) ? " WHERE " . implode(" AND ", $where_clauses) : "";

    // استعلام يشمل عدد الطلاب والتدريسيين والدخل السنوي
    $sql = "SELECT 
                d.Departement_ID, 
                d.Departement, 
                c.College,
                (SELECT COUNT(*) FROM students s WHERE s.Departement_ID = d.Departement_ID) as student_count,
                (SELECT COUNT(*) FROM faculty f WHERE f.Department_ID = d.Departement_ID) as faculty_count,
                (SELECT SUM(Yearly_Cost) FROM students s WHERE s.Departement_ID = d.Departement_ID) as total_income
            FROM departemenets d
            JOIN colleges c ON d.College_ID = c.College_ID
            $where_sql
            ORDER BY c.College ASC, d.Departement ASC";

    if (method_exists($db, 'select')) {
        $departments = $db->select($sql, $params);
    } else {
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $departments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

} catch (Exception $e) {
    // محاولة احتياطية في حال اختلاف اسم عمود القسم في جدول الأساتذة
    try {
        $sql = str_replace("f.Department_ID", "f.Departement_ID", $sql);
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $departments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e2) {
        $_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_department') || hasPermission('edit_department')): ?>
            <a href="add_department.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">
                <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>
                <div class="col-md-3">
                    <select name="college_filter" class="form-select" onchange="this.form.submit()">
                        <option value="">-- كل الكليات --</option>
                        <?php foreach ($colleges_list as $col): ?>
                            <option value="<?php echo $col['College_ID']; ?>" <?php echo ($college_filter == $col['College_ID']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($col['College']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <a href="index.php" class="btn btn-light border w-100"><i class="fas fa-redo me-1"></i>إعادة تعيين</a>
                </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>الكلية التابع لها</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($departments)): ?>
                            <?php foreach ($departments as $index => $dept): ?>
                                <tr>
                                    <td><?php echo $index + 1; ?></td>
                                    <td>
                                        <div class="fw-bold text-dark">
                                            <i class="fas fa-building me-2 text-secondary"></i>
                                            <?php echo htmlspecialchars($dept['Departement']); ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <span class="text-muted">
                                            <i class="fas fa-university me-1 small"></i>
                                            <?php echo htmlspecialchars($dept['College']); ?>
                                        </span>
                                    </td>

                                    <td class="text-center">
                                        <span class="badge bg-primary">
                                            <i class="fas fa-chalkboard-teacher me-1"></i>
                                            <?php echo $dept['faculty_count'] ?? 0; ?>
                                        </span>
                                    </td>
                                    
                                    <td class="text-center">
                                        <span class="badge bg-success">
                                            <i class="fas fa-users me-1"></i>
                                            <?php echo $dept['student_count'] ?? 0; ?>
                                        </span>
                                    </td>

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

                                    <td class="text-center">
                                        <?php if (hasPermission('edit_college')): ?>
                                            <div class="btn-group">
                                                <a href="edit_department.php?id=<?php echo $dept['Departement_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 $dept['Departement_ID']; ?>, '<?php echo addslashes($dept['Departement']); ?>', <?php echo $dept['student_count']; ?>, <?php echo $dept['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="warnStd" class="alert alert-warning d-none">
                    <i class="fas fa-user-graduate me-2"></i>
                    يوجد (<strong id="countStd"></strong>) طالب في هذا القسم.
                </div>

                <div id="warnFac" class="alert alert-warning d-none">
                    <i class="fas fa-chalkboard-teacher me-2"></i>
                    يوجد (<strong id="countFac"></strong>) تدريسي في هذا القسم.
                </div>

                <p class="text-danger small mt-2 fw-bold">
                    سيتم حذف جميع الطلاب والأساتذة المرتبطين بهذا القسم نهائياً.
                </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, studentCount, facultyCount) {
        // تحديث النصوص والروابط
        document.getElementById('deleteName').textContent = name;
        document.getElementById('deleteLink').href = 'delete_department.php?id=' + id;

        // إظهار/إخفاء تحذير الطلاب
        const divStd = document.getElementById('warnStd');
        if (studentCount > 0) {
            document.getElementById('countStd').textContent = studentCount;
            divStd.classList.remove('d-none');
        } else {
            divStd.classList.add('d-none');
        }

        // إظهار/إخفاء تحذير الأساتذة
        const divFac = document.getElementById('warnFac');
        if (facultyCount > 0) {
            document.getElementById('countFac').textContent = facultyCount;
            divFac.classList.remove('d-none');
        } else {
            divFac.classList.add('d-none');
        }

        // فتح المودال
        var myModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        myModal.show();
    }
</script>

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