<?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 (!hasPermission('view_students')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لعرض قائمة الطلاب.';
    header('Location: ../../index.php');
    exit();
}

$db = getDB();

$students = [];
$total_students = 0;
$active_students = 0;
$inactive_students = 0;

// تصفية البحث والفلاتر
$search_term = $_GET['search'] ?? '';
$grade_filter = $_GET['grade_filter'] ?? ''; 
$college_filter = $_GET['college_filter'] ?? ''; 
$admission_filter = $_GET['admission_filter'] ?? '';
$status_filter = $_GET['status_filter'] ?? 'all';
$sort_by = $_GET['sort_by'] ?? 'full_name';
$sort_order = (isset($_GET['sort_order']) && $_GET['sort_order'] === 'desc') ? 'DESC' : 'ASC';

$limit = 10;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

try {
    // 1. جلب قائمة الكليات للفلتر
    $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);
    }

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

    // البحث
    if (!empty($search_term)) {
        $like = '%' . $search_term . '%';
        $where_clauses[] = "(s.full_name LIKE ? OR s.national_id_number LIKE ? OR s.guardian_phone LIKE ? OR s.College LIKE ? OR s.Departement LIKE ?)";
        $params = array_merge($params, [$like, $like, $like, $like, $like]);
    }
    
    // الفلاتر
    if ($grade_filter && $grade_filter !== 'all') {
        $where_clauses[] = "s.grade_level = ?";
        $params[] = $grade_filter;
    }
    if (!empty($college_filter)) {
        $where_clauses[] = "s.College_ID = ?";
        $params[] = $college_filter;
    }
    if (!empty($admission_filter)) {
        $where_clauses[] = "s.addmission = ?";
        $params[] = $admission_filter;
    }
    if ($status_filter !== 'all') {
        $where_clauses[] = "s.status = ?";
        $params[] = ($status_filter == '1') ? 1 : 0;
    }

    $search_where = $where_clauses ? "WHERE " . implode(" AND ", $where_clauses) : "";

    // جلب الإجمالي
    $total_res = $db->select("SELECT COUNT(*) AS total FROM students s {$search_where}", $params);
    $total_students = $total_res[0]['total'] ?? 0;
    $total_pages = ceil($total_students / $limit);

    // جلب البيانات
    $sql = "
        SELECT
            s.id, s.full_name, s.national_id_number, s.guardian_phone, 
            s.grade_level, s.enrollment_date, s.gender, s.address, s.status,
            s.College, s.Departement, s.addmission, s.Yearly_Cost
        FROM students s
        {$search_where}
        ORDER BY s.{$sort_by} {$sort_order}
        LIMIT ? OFFSET ?
    ";

    $params_query = array_merge($params, [$limit, $offset]);
    
    if (method_exists($db, 'select')) {
        $students = $db->select($sql, $params_query);
    } else {
        $stmt = $db->prepare($sql);
        $stmt->execute($params_query);
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // إحصائيات سريعة
    $stats = $db->select("SELECT 
                            COUNT(*) as total,
                            SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active,
                            SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as inactive,
                            SUM(Yearly_Cost) as total_income
                          FROM students");
    $stats_total = $stats[0]['total'] ?? 0;
    $stats_active = $stats[0]['active'] ?? 0;
    $stats_inactive = $stats[0]['inactive'] ?? 0;
    $total_income = $stats[0]['total_income'] ?? 0;

    $unique_grades = ['المرحلة الأولى', 'المرحلة الثانية', 'المرحلة الثالثة', 'المرحلة الرابعة', 'المرحلة الخامسة'];
    $admission_types = ["صباحي", "مسائي", "صباحي\شهداء", "مسائي\شهداء"];

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

<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_student')): ?>
            <a href="add_student.php" class="btn btn-primary"><i class="fas fa-user-graduate me-2"></i>إضافة طالب</a>
        <?php endif; ?>
    </div>

    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card shadow-sm border-0 bg-primary text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>إجمالي الطلاب</h5><h3><?php echo $stats_total; ?></h3></div>
                    <i class="fas fa-users fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm border-0 bg-success text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>نشط</h5><h3><?php echo $stats_active; ?></h3></div>
                    <i class="fas fa-user-check fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm border-0 bg-secondary text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>منقطع/مؤجل</h5><h3><?php echo $stats_inactive; ?></h3></div>
                    <i class="fas fa-user-clock fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm border-0 bg-info text-white">
                <div class="card-body d-flex justify-content-between align-items-center">
                    <div><h5>الدخل السنوي</h5><h3><?php echo number_format($total_income); ?></h3></div>
                    <i class="fas fa-money-bill-wave fa-2x opacity-50"></i>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">
            <form method="GET" class="row g-2 mb-4">
                <div class="col-md-2">
                    <input type="text" name="search" class="form-control" placeholder="بحث..." value="<?php echo htmlspecialchars($search_term); ?>">
                </div>
                <div class="col-md-2">
                    <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">
                    <select name="grade_filter" class="form-select" onchange="this.form.submit()">
                        <option value="all">كل المراحل</option>
                        <?php foreach($unique_grades as $grade): ?>
                            <option value="<?php echo htmlspecialchars($grade); ?>" <?php echo ($grade_filter === $grade) ? 'selected' : ''; ?>><?php echo htmlspecialchars($grade); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="admission_filter" class="form-select" onchange="this.form.submit()">
                        <option value="">كل أنواع القبول</option>
                        <?php foreach($admission_types as $type): ?>
                            <option value="<?php echo htmlspecialchars($type); ?>" <?php echo ($admission_filter === $type) ? 'selected' : ''; ?>><?php echo htmlspecialchars($type); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 d-flex gap-2">
                    <button class="btn btn-primary flex-grow-1"><i class="fas fa-filter"></i> تصفية</button>
                    <a href="index.php" class="btn btn-light border"><i class="fas fa-redo"></i></a>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-hover align-middle table-striped">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>الاسم & الرقم الوطني</th>
                            <th>الكلية & القسم</th>
                            <th>المرحلة</th>
                            <th>نوع القبول</th>
                            <th>التكلفة</th>
                            <th>الحالة</th>
                            <th class="text-center">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($students as $i => $std): ?>
                            <tr>
                                <td><?php echo (($page-1)*$limit)+$i+1; ?></td>
                                
                                <td>
                                    <div class="fw-bold"><i class="fas fa-user-graduate me-1 text-primary"></i> <?php echo htmlspecialchars($std['full_name']); ?></div>
                                    <div class="text-muted small"><i class="fas fa-id-card me-1"></i> <?php echo htmlspecialchars($std['national_id_number'] ?: '---'); ?></div>
                                </td>

                                <td>
                                    <div class="text-dark fw-bold"><?php echo htmlspecialchars($std['College'] ?: '---'); ?></div>
                                    <div class="text-muted small"><?php echo htmlspecialchars($std['Departement'] ?: '---'); ?></div>
                                </td>

                                <td><span class="badge bg-info text-dark"><?php echo htmlspecialchars($std['grade_level']); ?></span></td>
                                <td><?php echo htmlspecialchars($std['addmission'] ?: '---'); ?></td>
                                <td><?php echo $std['Yearly_Cost'] ? number_format($std['Yearly_Cost']) : '---'; ?></td>

                                <td>
                                    <span class="badge <?php echo $std['status']==1?'bg-success':'bg-secondary'; ?>">
                                        <?php echo $std['status']==1?'نشط':'منقطع'; ?>
                                    </span>
                                </td>

                                <td class="text-center">
                                    <div class="btn-group">
                                        <?php if(hasPermission('edit_student')): ?>
                                            <a href="edit_student.php?id=<?php echo $std['id']; ?>" class="btn btn-sm btn-outline-primary" title="تعديل"><i class="fas fa-edit"></i></a>
                                        <?php endif; ?>

                                        <a href="students_docs.php?id=<?php echo $std['id']; ?>" class="btn btn-sm btn-outline-dark" title="عرض الوثائق"><i class="fas fa-eye"></i></a>

                                        <?php if(hasPermission('delete_student')): ?>
                                            <button class="btn btn-sm btn-outline-danger" onclick="showDeleteModal(<?php echo $std['id']; ?>,'<?php echo addslashes($std['full_name']); ?>')" title="حذف"><i class="fas fa-trash"></i></button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if(empty($students)): ?>
                            <tr><td colspan="8" class="text-center py-4 text-muted">لا يوجد طلاب مطابقين للبحث</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if($total_pages > 1): ?>
                <nav class="mt-4"><ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page<=1?'disabled':''; ?>"><a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo $search_term; ?>&college_filter=<?php echo $college_filter; ?>&grade_filter=<?php echo $grade_filter; ?>&admission_filter=<?php echo $admission_filter; ?>">السابق</a></li>
                    <?php for($i=1;$i<=$total_pages;$i++): ?>
                        <li class="page-item <?php echo $page==$i?'active':''; ?>"><a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search_term; ?>&college_filter=<?php echo $college_filter; ?>&grade_filter=<?php echo $grade_filter; ?>&admission_filter=<?php echo $admission_filter; ?>"><?php echo $i; ?></a></li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page>=$total_pages?'disabled':''; ?>"><a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo $search_term; ?>&college_filter=<?php echo $college_filter; ?>&grade_filter=<?php echo $grade_filter; ?>&admission_filter=<?php echo $admission_filter; ?>">التالي</a></li>
                </ul></nav>
            <?php endif; ?>
        </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">
                <h5 class="modal-title">تأكيد الحذف</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                هل أنت متأكد من حذف الطالب <strong id="studentName"></strong>؟ لا يمكن التراجع عن هذا الإجراء.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <a id="confirmDeleteBtn" href="#" class="btn btn-danger">حذف</a>
            </div>
        </div>
    </div>
</div>

<script>
function showDeleteModal(id, name) {
    document.getElementById('studentName').textContent = name;
    document.getElementById('confirmDeleteBtn').href = 'delete_student.php?id=' + id;
    var myModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    myModal.show();
}
</script>

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