<?php
// generalsetting.php - UPDATE STUDENT FEES BASED ON FILTERS
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

$committeeId   = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll        = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege  = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Initialize variables
$success_message = '';
$error_message = '';
$students_count = 0;

// CSRF Protection
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check if filters were submitted
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

// Validate and sanitize filter parameters
function validateInt($value) {
    return $value !== null && $value !== '' && ctype_digit($value) ? (int)$value : null;
}

// Get and validate filter parameters
if ($filters_applied) {
    $filter_college_id = validateInt($_GET['filter_college'] ?? null);
    $filter_section_id = validateInt($_GET['filter_section'] ?? null);
    $filter_program_id = validateInt($_GET['filter_program'] ?? null);
    $filter_specialization_id = validateInt($_GET['filter_specialization'] ?? null); // NEW
    $filter_batch_id = validateInt($_GET['filter_batch'] ?? null);
    $filter_admission_id = validateInt($_GET['filter_admission'] ?? null);
} else {
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_specialization_id = null; // NEW
    $filter_batch_id = null;
    $filter_admission_id = null;
}

// Handle form submission to update fees
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_fees'])) {
    
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $error_message = 'رمز الأمان غير صالح. الرجاء تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        $program_fees = (float)($_POST['program_fees'] ?? 0);
        $registration_fees = (float)($_POST['registration_fees'] ?? 0);
        $insurance_fees = (float)($_POST['insurance_fees'] ?? 0);
        
        if ($program_fees < 0 || $registration_fees < 0 || $insurance_fees < 0) {
            $error_message = 'قيمة الرسوم يجب أن تكون رقمًا موجبًا';
        } else {
            try {
                // Build WHERE clause for updating students
                $where = " WHERE 1=1 ";
                $types = ''; 
                $params = [];
                
                // Apply scope restrictions
                if (!$canAll && $scopeCollege !== null) {
                    $where .= " AND college_id = ? ";
                    $types .= 'i'; 
                    $params[] = $scopeCollege;
                }
                
                // Apply filters with validated integers
                if ($filter_college_id !== null) {
                    $where .= " AND college_id = ? ";
                    $types .= 'i'; 
                    $params[] = $filter_college_id;
                }
                
                if ($filter_section_id !== null) {
                    $where .= " AND section_id = ? ";
                    $types .= 'i'; 
                    $params[] = $filter_section_id;
                }
                
                if ($filter_program_id !== null) {
                    $where .= " AND program_id = ? ";
                    $types .= 'i'; 
                    $params[] = $filter_program_id;
                }
                
                // NEW: Apply specialization filter
                if ($filter_specialization_id !== null) {
                    $where .= " AND specialization_id = ? ";
                    $types .= 'i'; 
                    $params[] = $filter_specialization_id;
                }
                
                if ($filter_batch_id !== null) {
                    $where .= " AND batch_id = ? ";
                    $types .= 'i'; 
                    $params[] = $filter_batch_id;
                }
                
                if ($filter_admission_id !== null) {
                    $where .= " AND admission_id = ? ";
                    $types .= 'i'; 
                    $params[] = $filter_admission_id;
                }
                
                // Count matching students
                $count_sql = "SELECT COUNT(*) as total FROM students {$where}";
                $count_stmt = $mysqli1->prepare($count_sql);
                if ($types) {
                    $count_stmt->bind_param($types, ...$params);
                }
                $count_stmt->execute();
                $count_result = $count_stmt->get_result()->fetch_assoc();
                $total_students = $count_result['total'] ?? 0;
                $count_stmt->close();
                
                if ($total_students > 0) {
                    // Update matching students
                    $update_sql = "
                        UPDATE students 
                        SET program_fees = ?, 
                            registration_fees = ?, 
                            insurance_fees = ?,
                            updated_at = NOW()
                        {$where}
                    ";
                    
                    $update_stmt = $mysqli1->prepare($update_sql);
                    
                    // Bind parameters: fees first, then filter conditions
                    $bind_params = array_merge([$program_fees, $registration_fees, $insurance_fees], $params);
                    $param_types = "ddd" . $types;
                    
                    $update_stmt->bind_param($param_types, ...$bind_params);
                    $update_stmt->execute();
                    $affected_rows = $update_stmt->affected_rows;
                    $update_stmt->close();
                    
                    $success_message = "تم تحديث الرسوم لـ {$affected_rows} طالب (من إجمالي {$total_students} مطابق) بنجاح";
                    
                    // Log the action
                    error_log("User {$committeeId} updated fees for {$affected_rows} students");
                } else {
                    $error_message = "لا يوجد طلاب مطابقين لمعايير التصفية المحددة";
                }
                
            } catch (Exception $e) {
                $error_message = "حدث خطأ أثناء تحديث الرسوم";
                error_log("Update Fees Error: " . $e->getMessage());
            }
        }
    }
}

// Get count of matching students for current filters
if ($filters_applied) {
    $where = " WHERE 1=1 ";
    $types = ''; 
    $params = [];
    
    // Apply scope restrictions
    if (!$canAll && $scopeCollege !== null) {
        $where .= " AND college_id = ? ";
        $types .= 'i'; 
        $params[] = $scopeCollege;
    }
    
    // Apply filters with validated integers
    if ($filter_college_id !== null) {
        $where .= " AND college_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_college_id;
    }
    
    if ($filter_section_id !== null) {
        $where .= " AND section_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_section_id;
    }
    
    if ($filter_program_id !== null) {
        $where .= " AND program_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_program_id;
    }
    
    // NEW: Apply specialization filter
    if ($filter_specialization_id !== null) {
        $where .= " AND specialization_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_specialization_id;
    }
    
    if ($filter_batch_id !== null) {
        $where .= " AND batch_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_batch_id;
    }
    
    if ($filter_admission_id !== null) {
        $where .= " AND admission_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_admission_id;
    }
    
    $count_sql = "SELECT COUNT(*) as total FROM students {$where}";
    $count_stmt = $mysqli1->prepare($count_sql);
    if ($types) {
        $count_stmt->bind_param($types, ...$params);
    }
    $count_stmt->execute();
    $count_result = $count_stmt->get_result()->fetch_assoc();
    $students_count = $count_result['total'] ?? 0;
    $count_stmt->close();
}

// Get filter options
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges ORDER BY name");
$colleges_stmt->execute();
$colleges = $colleges_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$colleges_stmt->close();

// Get sections for the selected college
$sections = [];
if ($filter_college_id !== null) {
    $sections_sql = "
        SELECT DISTINCT s.id, s.name, s.parent
        FROM sections s 
        WHERE s.parent = ?  
        ORDER BY s.name
    ";
    $sections_stmt = $mysqli1->prepare($sections_sql);
    $sections_stmt->bind_param("i", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
}

// Get all sections (for initial load)
$all_sections_stmt = $mysqli1->prepare("SELECT id, name FROM sections ORDER BY name");
$all_sections_stmt->execute();
$all_sections = $all_sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$all_sections_stmt->close();

// Get programs based on selected college and section
$programs = [];
if ($filter_college_id !== null) {
    $programs_where = "p.deleted_at IS NULL";
    $programs_params = [];
    $programs_types = "";
    
    if ($filter_section_id !== null) {
        $programs_where .= " AND st.section_id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_section_id;
    }
    
    $programs_where .= " AND st.college_id = ?";
    $programs_types .= "i";
    $programs = [];
    
    $programs_sql = "
    SELECT DISTINCT p.id, p.name 
    FROM programs p 
    WHERE p.deleted_at IS NULL 
    ORDER BY p.name
";

$programs_stmt = $mysqli1->prepare($programs_sql);
$programs_stmt->execute();
$programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$programs_stmt->close();
}

// NEW: Get specializations based on selected section and program
$specializations = [];
if ($filter_section_id !== null && $filter_program_id !== null) {
    $specializations_sql = "
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("ii", $filter_section_id, $filter_program_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_section_id !== null) {
    // Get specializations by section only
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_section_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
} elseif ($filter_program_id !== null) {
    // Get specializations by program only
    $specializations_sql = "
        SELECT DISTINCT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ";
    $specializations_stmt = $mysqli1->prepare($specializations_sql);
    $specializations_stmt->bind_param("i", $filter_program_id);
    $specializations_stmt->execute();
    $specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $specializations_stmt->close();
}

// Get batches
$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id");
$batches_stmt->execute();
$batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$batches_stmt->close();

// Get admissions
$admissions_stmt = $mysqli1->prepare("SELECT id, name FROM admissions ORDER BY name");
$admissions_stmt->execute();
$admissions = $admissions_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$admissions_stmt->close();

include '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 href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', sans-serif !important; 
        }
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        .filter-icon {
            width: 40px;
            height: 40px;
            background: #3b82f6;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
        }
        .filter-status {
            font-size: 0.85rem;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
        }
        .filter-status.applied {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        .filter-status.not-applied {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .fees-input {
            max-width: 200px;
        }
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
        }
        .student-count-badge {
            font-size: 1.1rem;
            padding: 0.5rem 1rem;
        }
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25);
        }
        .info-message {
            background-color: #f0f9ff;
            border: 1px solid #bae6fd;
            color: #0369a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .filter-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
        }
        .filter-badge.specialization {
            background-color: #f3e8ff;
            color: #7e22ce;
        }
        .specialization-select {
            background-color: #faf5ff;
        }
    </style>
</head>
<body>
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold">
                <i class="fas fa-money-bill-wave me-2"></i>
                تحديث الرسوم حسب التصنيفات
            </h3>
            <div class="ms-auto">
                <span class="filter-status <?= $filters_applied ? 'applied' : 'not-applied' ?> me-2">
                    <i class="fas fa-<?= $filters_applied ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
                    <?= $filters_applied ? 'تم تطبيق التصفية' : 'لم يتم تطبيق أي تصفية' ?>
                </span>
                <a class="btn btn-outline-secondary" href="admin_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?php if (!$filters_applied): ?>
            <div class="info-message">
                <i class="fas fa-info-circle me-2"></i>
                <strong>تنبيه:</strong> لم يتم تطبيق أي تصفية. الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية" لتحديث الرسوم.
            </div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?= $success_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?= $error_message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="card card-arabic p-4 mb-4">
            <div class="d-flex align-items-center mb-3">
                <div class="filter-icon me-2">
                    <i class="fas fa-filter"></i>
                </div>
                <h6 class="fw-bold mb-0 text-dark">تصفية الطلاب لتحديث الرسوم</h6>
            </div>
            
            <form method="get" class="row g-3 align-items-end" id="filterForm">
                <!-- Hidden field to indicate filters were applied -->
                <input type="hidden" name="filter_applied" value="1">
                
                <!-- College Filter -->
                <div class="col-lg-2 col-md-6">
                    <div class="form-group">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-university me-1"></i>
                            الكلية
                        </label>
                        <select class="form-control" name="filter_college" id="filter_college" onchange="loadSections(this.value)">
                            <option value="">اختر الكلية</option>
                            <?php foreach ($colleges as $college): ?>
                                <?php 
                                // Don't show college filter if user has scope restriction
                                if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                    continue;
                                }
                                ?>
                                <option value="<?= $college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                    <?= e($college['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Section Filter (Dependent on College) -->
                <div class="col-lg-2 col-md-4">
                    <div class="form-group">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-layer-group me-1"></i>
                            القسم
                        </label>
                        <select class="form-control" name="filter_section" id="filter_section" onchange="loadSpecializations()">
                            <option value="">جميع الأقسام</option>
                            <?php if ($filter_college_id !== null && !empty($sections)): ?>
                                <?php foreach ($sections as $section): ?>
                                    <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                        <?= e($section['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <?php foreach ($all_sections as $section): ?>
                                    <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                        <?= e($section['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Program Filter -->
                <div class="col-lg-2 col-md-4">
                    <div class="form-group">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-graduation-cap me-1"></i>
                            البرنامج
                        </label>
                        <select class="form-control" name="filter_program" id="filter_program" onchange="loadSpecializations()">
                            <option value="">جميع البرامج</option>
                            <?php foreach ($programs as $program): ?>
                                <option value="<?= $program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                    <?= e($program['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- NEW: Specialization Filter -->
                <div class="col-lg-2 col-md-4">
                    <div class="form-group">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-microscope me-1"></i>
                            التخصص
                        </label>
                        <select class="form-control specialization-select" name="filter_specialization" id="filter_specialization" <?= (!$filter_section_id && !$filter_program_id) ? 'disabled' : '' ?>>
                            <option value="">جميع التخصصات</option>
                            <?php if (!empty($specializations)): ?>
                                <?php foreach ($specializations as $spec): ?>
                                    <option value="<?= $spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                        <?= e($spec['specialization_name_ar']) ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                        <small class="text-muted" id="specHint">
                            <?php if (!$filter_section_id && !$filter_program_id): ?>
                                اختر القسم أو البرنامج أولاً
                            <?php endif; ?>
                        </small>
                    </div>
                </div>
                
                <!-- Batch Filter -->
                <div class="col-lg-2 col-md-4">
                    <div class="form-group">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-users me-1"></i>
                            الدفعة
                        </label>
                        <select class="form-control" name="filter_batch">
                            <option value="">جميع الدفعات</option>
                            <?php foreach ($batches as $batch): ?>
                                <option value="<?= $batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                    <?= e($batch['value']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Admission Filter -->
                <div class="col-lg-2 col-md-6">
                    <div class="form-group">
                        <label class="form-label fw-semibold text-muted mb-2">
                            <i class="fas fa-user-graduate me-1"></i>
                            نوع القبول
                        </label>
                        <select class="form-control" name="filter_admission">
                            <option value="">جميع الأنواع</option>
                            <?php foreach ($admissions as $admission): ?>
                                <option value="<?= $admission['id'] ?>" <?= ($filter_admission_id == $admission['id']) ? 'selected' : '' ?>>
                                    <?= e($admission['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="col-12">
                    <div class="d-flex gap-2 pt-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-filter me-1"></i>
                            تطبيق التصفية
                        </button>
                        <a href="generalsetting.php" class="btn btn-outline-secondary">
                            <i class="fas fa-sync-alt me-1"></i>
                            إعادة تعيين
                        </a>
                        <?php if ($filters_applied): ?>
                            <span class="badge bg-success align-self-center px-3 py-2">
                                <i class="fas fa-check me-1"></i>
                                تم تطبيق التصفية
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>

        <!-- Fees Update Card -->
        <?php if ($filters_applied): ?>
        <div class="card card-arabic p-4 mb-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h6 class="fw-bold mb-1">تحديث الرسوم للطلاب المصفّين</h6>
                    <p class="text-muted mb-0">سيتم تحديث الرسوم لجميع الطلاب المطابقين للتصفية المحددة</p>
                </div>
                <span class="badge bg-primary student-count-badge">
                    <i class="fas fa-users me-1"></i>
                    <?= $students_count ?> طالب
                </span>
            </div>
            
            <!-- Current Filter Summary -->
            <div class="row g-3 mb-4">
                <div class="col-12">
                    <div class="p-3 bg-light rounded">
                        <div class="fw-semibold mb-2">التصفية المطبقة:</div>
                        <div class="d-flex flex-wrap gap-2">
                            <?php if ($filter_college_id !== null): ?>
                                <?php 
                                $selected_college = null;
                                foreach ($colleges as $college) {
                                    if ($college['id'] == $filter_college_id) {
                                        $selected_college = $college;
                                        break;
                                    }
                                }
                                ?>
                                <?php if ($selected_college): ?>
                                    <span class="badge bg-primary filter-badge">
                                        <i class="fas fa-university me-1"></i>
                                        <?= e($selected_college['name']) ?>
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                            
                            <?php if ($filter_section_id !== null): ?>
                                <?php 
                                $selected_section = null;
                                $search_sections = $filter_college_id ? $sections : $all_sections;
                                foreach ($search_sections as $section) {
                                    if ($section['id'] == $filter_section_id) {
                                        $selected_section = $section;
                                        break;
                                    }
                                }
                                ?>
                                <?php if ($selected_section): ?>
                                    <span class="badge bg-info filter-badge">
                                        <i class="fas fa-layer-group me-1"></i>
                                        <?= e($selected_section['name']) ?>
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                            
                            <?php if ($filter_program_id !== null): ?>
                                <?php 
                                $selected_program = null;
                                foreach ($programs as $program) {
                                    if ($program['id'] == $filter_program_id) {
                                        $selected_program = $program;
                                        break;
                                    }
                                }
                                ?>
                                <?php if ($selected_program): ?>
                                    <span class="badge bg-success filter-badge">
                                        <i class="fas fa-graduation-cap me-1"></i>
                                        <?= e($selected_program['name']) ?>
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                            
                            <!-- NEW: Specialization summary -->
                            <?php if ($filter_specialization_id !== null && !empty($specializations)): ?>
                                <?php 
                                $selected_spec = null;
                                foreach ($specializations as $spec) {
                                    if ($spec['specialization_id'] == $filter_specialization_id) {
                                        $selected_spec = $spec;
                                        break;
                                    }
                                }
                                ?>
                                <?php if ($selected_spec): ?>
                                    <span class="badge filter-badge specialization">
                                        <i class="fas fa-microscope me-1"></i>
                                        <?= e($selected_spec['specialization_name_ar']) ?>
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                            
                            <?php if ($filter_batch_id !== null): ?>
                                <?php 
                                $selected_batch = null;
                                foreach ($batches as $batch) {
                                    if ($batch['id'] == $filter_batch_id) {
                                        $selected_batch = $batch;
                                        break;
                                    }
                                }
                                ?>
                                <?php if ($selected_batch): ?>
                                    <span class="badge bg-warning filter-badge">
                                        <i class="fas fa-users me-1"></i>
                                        <?= e($selected_batch['value']) ?>
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                            
                            <?php if ($filter_admission_id !== null): ?>
                                <?php 
                                $selected_admission = null;
                                foreach ($admissions as $admission) {
                                    if ($admission['id'] == $filter_admission_id) {
                                        $selected_admission = $admission;
                                        break;
                                    }
                                }
                                ?>
                                <?php if ($selected_admission): ?>
                                    <span class="badge bg-secondary filter-badge">
                                        <i class="fas fa-user-graduate me-1"></i>
                                        <?= e($selected_admission['name']) ?>
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                            
                            <?php if ($filter_college_id === null && $filter_section_id === null && $filter_program_id === null && $filter_specialization_id === null && $filter_batch_id === null && $filter_admission_id === null): ?>
                                <span class="badge bg-light text-dark">جميع الطلاب</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Fees Update Form -->
            <form method="post" id="updateFeesForm">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                
                <div class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-book me-1 text-primary"></i>
                            رسوم الدراسة (SDG)
                        </label>
                        <div class="input-group">
                            <input type="number" 
                                   class="form-control fees-input" 
                                   name="program_fees" 
                                   value="0.00"
                                   step="0.01" 
                                   min="0" 
                                   required>
                            <span class="input-group-text">SDG</span>
                        </div>
                        <small class="text-muted">الرسوم الدراسية للطالب</small>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-edit me-1 text-success"></i>
                            رسوم التسجيل (SDG)
                        </label>
                        <div class="input-group">
                            <input type="number" 
                                   class="form-control fees-input" 
                                   name="registration_fees" 
                                   value="0.00"
                                   step="0.01" 
                                   min="0" 
                                   required>
                            <span class="input-group-text">SDG</span>
                        </div>
                        <small class="text-muted">رسوم التسجيل للطالب</small>
                    </div>
                    
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">
                            <i class="fas fa-shield-alt me-1 text-info"></i>
                            رسوم التأمين (SDG)
                        </label>
                        <div class="input-group">
                            <input type="number" 
                                   class="form-control fees-input" 
                                   name="insurance_fees" 
                                   value="0.00"
                                   step="0.01" 
                                   min="0" 
                                   required>
                            <span class="input-group-text">SDG</span>
                        </div>
                        <small class="text-muted">رسوم التأمين للطالب</small>
                    </div>
                    
                    <div class="col-12 mt-4">
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>تحذير:</strong> سيتم تحديث الرسوم لـ <strong><?= $students_count ?></strong> طالب مطابق للتصفية المحددة.
                            هذا الإجراء لا يمكن التراجع عنه.
                        </div>
                    </div>
                    
                    <div class="col-12">
                        <div class="d-flex justify-content-between">
                            <div>
                                <button type="submit" name="update_fees" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save me-2"></i>
                                    تحديث الرسوم
                                </button>
                            </div>
                            <div class="text-end">
                                <div class="text-muted small">
                                    <i class="fas fa-info-circle me-1"></i>
                                    سيتم تحديث الحقول التالية في جدول الطلاب:
                                </div>
                                <div class="d-flex gap-3 mt-1">
                                    <span class="badge bg-primary">program_fees</span>
                                    <span class="badge bg-success">registration_fees</span>
                                    <span class="badge bg-info">insurance_fees</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Summary Statistics -->
        <div class="card card-arabic p-4 summary-card">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h5 class="fw-bold text-white mb-3">
                        <i class="fas fa-chart-bar me-2"></i>
                        إحصائيات التصفية
                    </h5>
                    <div class="row text-white">
                        <div class="col-4">
                            <div class="d-flex align-items-center">
                                <div class="bg-white text-primary rounded-circle p-2 me-3">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div>
                                    <div class="fs-4 fw-bold"><?= $students_count ?></div>
                                    <div class="small opacity-75">عدد الطلاب</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="d-flex align-items-center">
                                <div class="bg-white text-success rounded-circle p-2 me-3">
                                    <i class="fas fa-filter"></i>
                                </div>
                                <div>
                                    <?php 
                                    $filter_count = 0;
                                    $filter_count += $filter_college_id !== null ? 1 : 0;
                                    $filter_count += $filter_section_id !== null ? 1 : 0;
                                    $filter_count += $filter_program_id !== null ? 1 : 0;
                                    $filter_count += $filter_specialization_id !== null ? 1 : 0; // NEW
                                    $filter_count += $filter_batch_id !== null ? 1 : 0;
                                    $filter_count += $filter_admission_id !== null ? 1 : 0;
                                    ?>
                                    <div class="fs-4 fw-bold"><?= $filter_count ?></div>
                                    <div class="small opacity-75">شروط التصفية</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="d-flex align-items-center">
                                <div class="bg-white text-warning rounded-circle p-2 me-3">
                                    <i class="fas fa-database"></i>
                                </div>
                                <div>
                                    <div class="fs-4 fw-bold"><?= date('Y-m-d') ?></div>
                                    <div class="small opacity-75">تاريخ التحديث</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-white rounded p-3">
                        <div class="text-dark fw-bold mb-2">ملاحظات هامة</div>
                        <div class="small text-muted">
                            <div class="mb-1">
                                <i class="fas fa-check-circle text-success me-1"></i>
                                التحديث شامل لجميع الطلاب المطابقين
                            </div>
                            <div class="mb-1">
                                <i class="fas fa-check-circle text-success me-1"></i>
                                يمكن تحديد بعض الشروط أو جميعها
                            </div>
                            <div class="mb-1">
                                <i class="fas fa-check-circle text-success me-1"></i>
                                الإجراء سريع ولا يتطلب وقت طويل
                            </div>
                            <div>
                                <i class="fas fa-exclamation-triangle text-warning me-1"></i>
                                لا يمكن التراجع عن التحديث
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php elseif ($filters_applied && $students_count == 0): ?>
            <div class="card card-arabic p-5 text-center">
                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">لا توجد طلاب</h5>
                <p class="text-muted mb-4">لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة</p>
                <a href="generalsetting.php" class="btn btn-primary">
                    <i class="fas fa-sync-alt me-2"></i>تغيير عوامل التصفية
                </a>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // تخزين جميع التخصصات للاستخدام في AJAX
        const allSpecializations = <?= json_encode($specializations) ?>;
        
        // Function to load sections based on selected college
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            if (!collegeId || collegeId === '') {
                // Reset to all sections
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                <?php foreach ($all_sections as $section): ?>
                    sectionSelect.innerHTML += `<option value="<?= $section['id'] ?>"><?= e($section['name']) ?></option>`;
                <?php endforeach; ?>
                return;
            }
            
            // Submit form to reload with new college
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            const collegeInput = document.createElement('input');
            collegeInput.type = 'hidden';
            collegeInput.name = 'filter_college';
            collegeInput.value = collegeId;
            form.appendChild(collegeInput);
            
            const appliedInput = document.createElement('input');
            appliedInput.type = 'hidden';
            appliedInput.name = 'filter_applied';
            appliedInput.value = '1';
            form.appendChild(appliedInput);
            
            // Preserve other filter values
            const currentSection = "<?= $filter_section_id ?: '' ?>";
            if (currentSection) {
                const sectionInput = document.createElement('input');
                sectionInput.type = 'hidden';
                sectionInput.name = 'filter_section';
                sectionInput.value = currentSection;
                form.appendChild(sectionInput);
            }
            
            const currentProgram = "<?= $filter_program_id ?: '' ?>";
            if (currentProgram) {
                const programInput = document.createElement('input');
                programInput.type = 'hidden';
                programInput.name = 'filter_program';
                programInput.value = currentProgram;
                form.appendChild(programInput);
            }
            
            const currentSpecialization = "<?= $filter_specialization_id ?: '' ?>";
            if (currentSpecialization) {
                const specInput = document.createElement('input');
                specInput.type = 'hidden';
                specInput.name = 'filter_specialization';
                specInput.value = currentSpecialization;
                form.appendChild(specInput);
            }
            
            const currentBatch = "<?= $filter_batch_id ?: '' ?>";
            if (currentBatch) {
                const batchInput = document.createElement('input');
                batchInput.type = 'hidden';
                batchInput.name = 'filter_batch';
                batchInput.value = currentBatch;
                form.appendChild(batchInput);
            }
            
            const currentAdmission = "<?= $filter_admission_id ?: '' ?>";
            if (currentAdmission) {
                const admissionInput = document.createElement('input');
                admissionInput.type = 'hidden';
                admissionInput.name = 'filter_admission';
                admissionInput.value = currentAdmission;
                form.appendChild(admissionInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        // NEW: Function to load specializations based on section and program
        function loadSpecializations() {
            const sectionId = document.getElementById('filter_section').value;
            const programId = document.getElementById('filter_program').value;
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            if (!sectionId && !programId) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                if (specHint) specHint.innerHTML = 'اختر القسم أو البرنامج أولاً';
                return;
            }
            
            // Build query string
            let url = 'ajax/get_specializations.php?';
            if (sectionId) url += `section_id=${encodeURIComponent(sectionId)}&`;
            if (programId) url += `program_id=${encodeURIComponent(programId)}`;
            
            // Show loading
            specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
            specSelect.disabled = false;
            if (specHint) specHint.innerHTML = 'جاري تحميل التخصصات...';
            
            // Fetch specializations via AJAX
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (data && data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            // Check if this specialization was previously selected
                            const urlParams = new URLSearchParams(window.location.search);
                            const selectedSpec = urlParams.get('filter_specialization');
                            if (selectedSpec && selectedSpec == spec.specialization_id) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                        if (specHint) specHint.innerHTML = `${data.length} تخصص متاح`;
                    } else {
                        if (specHint) specHint.innerHTML = 'لا توجد تخصصات متاحة';
                    }
                    
                    specSelect.disabled = false;
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    specSelect.disabled = false;
                    if (specHint) specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        // Form validation for updating fees
        document.getElementById('updateFeesForm')?.addEventListener('submit', function(e) {
            const programFees = document.querySelector('input[name="program_fees"]').value;
            const registrationFees = document.querySelector('input[name="registration_fees"]').value;
            const insuranceFees = document.querySelector('input[name="insurance_fees"]').value;
            const studentsCount = <?= $students_count ?>;
            
            if (parseFloat(programFees) < 0 || parseFloat(registrationFees) < 0 || parseFloat(insuranceFees) < 0) {
                e.preventDefault();
                alert('قيمة الرسوم يجب أن تكون رقمًا موجبًا');
                return;
            }
            
            const confirmationMessage = `هل أنت متأكد من تحديث الرسوم لـ ${studentsCount} طالب؟\n\n` +
                                      `• رسوم الدراسة: ${programFees} SDG\n` +
                                      `• رسوم التسجيل: ${registrationFees} SDG\n` +
                                      `• رسوم التأمين: ${insuranceFees} SDG\n\n` +
                                      `هذا الإجراء لا يمكن التراجع عنه.`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        // Auto-format fee inputs
        document.querySelectorAll('.fees-input').forEach(input => {
            input.addEventListener('blur', function() {
                if (this.value) {
                    this.value = parseFloat(this.value).toFixed(2);
                }
            });
            
            input.addEventListener('focus', function() {
                this.select();
            });
        });
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Load specializations if section or program is selected
            const sectionId = document.getElementById('filter_section')?.value;
            const programId = document.getElementById('filter_program')?.value;
            
            if ((sectionId || programId) && sectionId !== '' && programId !== '') {
                setTimeout(() => {
                    loadSpecializations();
                }, 100);
            }
        });
    </script>
</body>
</html>
