<?php
// generalsetting.php - MANAGE STUDENT FEES
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 = [];

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

// Get filter parameters - only use them if filters were applied
if ($filters_applied) {
    $filter_college_id = $_GET['filter_college'] ?? null;
    $filter_section_id = $_GET['filter_section'] ?? null;
    $filter_batch_id = $_GET['filter_batch'] ?? null;
    $filter_admission_type = $_GET['filter_admission_type'] ?? null;
    $filter_program_id = $_GET['filter_program'] ?? null;
    $filter_search = $_GET['filter_search'] ?? null;
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_batch_id = null;
    $filter_admission_type = null;
    $filter_program_id = null;
    $filter_search = null;
}

// Build WHERE clause for filtering students
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

// Apply scope restrictions
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 's'; 
    $params[] = $scopeCollege;
    // Auto-set the college filter if user has scope restriction
    if (!$filter_college_id) {
        $filter_college_id = $scopeCollege;
    }
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

// Apply filters ONLY if they were applied by user
if ($filters_applied) {
    if ($filter_college_id && !empty($filter_college_id)) {
        $where .= " AND s.college_id = ? ";
        $types .= 's'; 
        $params[] = $filter_college_id;
    }

    if ($filter_section_id && !empty($filter_section_id)) {
        $where .= " AND s.section_id = ? ";
        $types .= 's'; 
        $params[] = $filter_section_id;
    }

    if ($filter_batch_id && !empty($filter_batch_id)) {
        $where .= " AND s.batch_id = ? ";
        $types .= 's'; 
        $params[] = $filter_batch_id;
    }

    if ($filter_admission_type && !empty($filter_admission_type)) {
        $where .= " AND s.admission_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_admission_type;
    }

    if ($filter_program_id && !empty($filter_program_id)) {
        $where .= " AND s.program_id = ? ";
        $types .= 's'; 
        $params[] = $filter_program_id;
    }

    if ($filter_search && !empty($filter_search)) {
        $where .= " AND (s.student_id LIKE ? OR s.student_name LIKE ?) ";
        $types .= 'ss'; 
        $search_term = "%{$filter_search}%";
        $params[] = $search_term;
        $params[] = $search_term;
    }
}

// Handle bulk update form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_fees'])) {
    $update_type = $_POST['update_type'] ?? '';
    $fee_value = (float)($_POST['fee_value'] ?? 0);
    $student_ids = $_POST['student_ids'] ?? [];
    
    if (empty($student_ids)) {
        $error_message = 'لم يتم اختيار أي طلاب للتحديث';
    } elseif (empty($update_type)) {
        $error_message = 'يرجى اختيار نوع الرسوم للتحديث';
    } elseif ($fee_value < 0) {
        $error_message = 'قيمة الرسوم يجب أن تكون رقمًا موجبًا';
    } else {
        try {
            $mysqli1->begin_transaction();
            
            $updated_count = 0;
            
            foreach ($student_ids as $student_id) {
                // Prepare update query based on update type
                switch ($update_type) {
                    case 'program_fees':
                        $sql = "UPDATE students SET program_fees = ? WHERE id = ?";
                        break;
                    case 'registration_fees':
                        $sql = "UPDATE students SET registration_fees = ? WHERE id = ?";
                        break;
                    case 'insurance_fees':
                        $sql = "UPDATE students SET insurance_fees = ? WHERE id = ?";
                        break;
                    case 'all_fees':
                        $sql = "UPDATE students SET program_fees = ?, registration_fees = ?, insurance_fees = ? WHERE id = ?";
                        break;
                    default:
                        throw new Exception('نوع التحديث غير صحيح');
                }
                
                $stmt = $mysqli1->prepare($sql);
                
                if ($update_type === 'all_fees') {
                    $stmt->bind_param("dddi", $fee_value, $fee_value, $fee_value, $student_id);
                } else {
                    $stmt->bind_param("di", $fee_value, $student_id);
                }
                
                $stmt->execute();
                
                if ($stmt->affected_rows > 0) {
                    $updated_count++;
                }
                
                $stmt->close();
            }
            
            $mysqli1->commit();
            $success_message = "تم تحديث الرسوم لـ {$updated_count} طالب بنجاح";
            
            // Refresh the student list after update
            $_GET['filter_applied'] = '1';
            $filters_applied = true;
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            $error_message = "حدث خطأ أثناء تحديث الرسوم: " . $e->getMessage();
            error_log("Fee Update Error: " . $e->getMessage());
        }
    }
}

// Handle individual student update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_single_student'])) {
    $student_id = $_POST['student_id'] ?? '';
    $program_fees = (float)($_POST['program_fees'] ?? 0);
    $registration_fees = (float)($_POST['registration_fees'] ?? 0);
    $insurance_fees = (float)($_POST['insurance_fees'] ?? 0);
    
    if (empty($student_id)) {
        $error_message = 'رقم الطالب غير صحيح';
    } else {
        try {
            $sql = "UPDATE students SET 
                    program_fees = ?, 
                    registration_fees = ?, 
                    insurance_fees = ? 
                    WHERE student_id = ?";
            
            $stmt = $mysqli1->prepare($sql);
            $stmt->bind_param("dddi", $program_fees, $registration_fees, $insurance_fees, $student_id);
            $stmt->execute();
            
            if ($stmt->affected_rows > 0) {
                $success_message = "تم تحديث رسوم الطالب بنجاح";
            } else {
                $error_message = "لم يتم العثور على الطالب أو لم تحدث أي تغييرات";
            }
            
            $stmt->close();
            
        } catch (Exception $e) {
            $error_message = "حدث خطأ أثناء تحديث رسوم الطالب: " . $e->getMessage();
        }
    }
}

// Get filtered students ONLY if filters were applied
if ($filters_applied) {
    // استعلام معدل لإزالة التكرارات بناءً على رقم الطالب
    // أولاً: الحصول على جميع الطلاب بدون تكرارات
    $sqlStudents = "
        SELECT 
            s.id,
            s.student_id,
            s.student_name,
            s.student_number,
            s.program_fees,
            s.registration_fees,
            s.insurance_fees,
            s.admission_id,
            s.college_id,
            s.section_id,
            s.batch_id,
            s.program_id,
            c.name AS college_name,
            sec.name AS section_name,
            p.name AS program_name,
            b.value AS batch_name,
            adm.name AS admission_type_name
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id
        LEFT JOIN sections sec ON s.section_id = sec.id
        LEFT JOIN programs p ON s.program_id = p.id
        LEFT JOIN batches b ON s.batch_id = b.id
        LEFT JOIN admissions adm ON s.admission_id = adm.id
        WHERE s.id IN (
            SELECT MIN(id) 
            FROM students 
            WHERE 1=1 "
            . (isset($filter_college_id) && $filter_college_id ? " AND college_id = ?" : "")
            . (isset($filter_section_id) && $filter_section_id ? " AND section_id = ?" : "")
            . (isset($filter_batch_id) && $filter_batch_id ? " AND batch_id = ?" : "")
            . (isset($filter_admission_type) && $filter_admission_type ? " AND admission_id = ?" : "")
            . (isset($filter_program_id) && $filter_program_id ? " AND program_id = ?" : "")
            . (isset($filter_search) && $filter_search ? " AND (student_id LIKE ? OR student_name LIKE ?)" : "")
            . " GROUP BY student_id
        )
        ORDER BY s.student_id
        LIMIT 1000
    ";

    $students_stmt = $mysqli1->prepare($sqlStudents);
    
    // Bind parameters for subquery
    $all_params = [];
    $all_types = '';
    
    // Add subquery parameters
    if (isset($filter_college_id) && $filter_college_id) {
        $all_types .= 's';
        $all_params[] = $filter_college_id;
    }
    if (isset($filter_section_id) && $filter_section_id) {
        $all_types .= 's';
        $all_params[] = $filter_section_id;
    }
    if (isset($filter_batch_id) && $filter_batch_id) {
        $all_types .= 's';
        $all_params[] = $filter_batch_id;
    }
    if (isset($filter_admission_type) && $filter_admission_type) {
        $all_types .= 'i';
        $all_params[] = $filter_admission_type;
    }
    if (isset($filter_program_id) && $filter_program_id) {
        $all_types .= 's';
        $all_params[] = $filter_program_id;
    }
    if (isset($filter_search) && $filter_search) {
        $all_types .= 'ss';
        $search_term = "%{$filter_search}%";
        $all_params[] = $search_term;
        $all_params[] = $search_term;
    }
    
    if ($all_types) {
        $students_stmt->bind_param($all_types, ...$all_params);
    }
    
    $students_stmt->execute();
    $students = $students_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $students_stmt->close();
} else {
    // No students to show initially
    $students = [];
}

// Get filter options
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL 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 && !empty($filter_college_id)) {
    $sections_sql = "
        SELECT DISTINCT s.id, s.name, s.parent
        FROM sections s 
        WHERE s.parent = ? AND s.deleted_at IS NULL 
        ORDER BY s.name
    ";
    $sections_stmt = $mysqli1->prepare($sections_sql);
    $sections_stmt->bind_param("s", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_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 programs
$programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
$programs_stmt->execute();
$programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$programs_stmt->close();

// Get admission types from admissions table
// إزالة deleted_at من الاستعلام لأن الجدول قد لا يحتوي عليه
try {
    $admissions_stmt = $mysqli1->prepare("SELECT id, name FROM admissions ORDER BY name");
    $admissions_stmt->execute();
    $admissions_result = $admissions_stmt->get_result();
    $admissions = [];
    while ($row = $admissions_result->fetch_assoc()) {
        $admissions[] = $row;
    }
    $admissions_stmt->close();
} catch (Exception $e) {
    // إذا كان الجدول غير موجود، استخدم القيم القديمة من الطلاب
    $admissions_stmt = $mysqli1->prepare("SELECT DISTINCT addmission_type FROM students WHERE addmission_type IS NOT NULL AND addmission_type != '' ORDER BY addmission_type");
    $admissions_stmt->execute();
    $admissions_result = $admissions_stmt->get_result();
    $admissions = [];
    $counter = 1;
    while ($row = $admissions_result->fetch_assoc()) {
        $admissions[] = ['id' => $counter++, 'name' => $row['addmission_type']];
    }
    $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', system-ui, -apple-system, 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;
        }
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .checkbox-cell {
            width: 50px;
            text-align: center;
        }
        .batch-badge {
            font-size: 0.75rem;
        }
        .status-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .fees-input {
            max-width: 120px;
        }
        .total-fees {
            font-weight: bold;
            color: #059669;
        }
        .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;
        }
        .info-message {
            background-color: #f0f9ff;
            border: 1px solid #bae6fd;
            color: #0369a1;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .fee-type-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .bulk-update-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .summary-card {
            background-color: #f8f9fa;
            border-left: 4px solid #3b82f6;
        }
        .edit-btn {
            width: 32px;
            height: 32px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .search-input-group {
            position: relative;
        }
        .search-input-group .form-control {
            padding-right: 45px;
        }
        .search-input-group .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            z-index: 4;
        }
        .filter-row {
            margin-bottom: 10px;
        }
        .search-btn {
            margin-top: 8px;
        }
        .bulk-update-btn {
            margin-top: 5px;
        }
    </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-cog 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="row align-items-center">
                <div class="col-md-8">
                    <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 class="ms-3">
                            <span class="badge bg-light text-dark border">
                                <i class="fas fa-sliders-h me-1"></i>
                                <?= $filters_applied ? 'تصفية مطبقة' : 'في انتظار التطبيق' ?>
                            </span>
                        </div>
                    </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">
                        
                        <!-- Search Filter -->
                        <div class="col-lg-6 col-md-12 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-search me-1"></i>
                                    بحث سريع
                                </label>
                                <div class="search-input-group">
                                    <input type="text" 
                                           class="form-control form-control-sm" 
                                           name="filter_search" 
                                           id="filter_search" 
                                           placeholder="ابحث برقم الطالب أو الاسم..."
                                           value="<?= e($filter_search ?? '') ?>">
                                    <i class="fas fa-search search-icon"></i>
                                </div>
                                <small class="text-muted">يمكنك البحث بأي جزء من رقم الطالب أو الاسم</small>
                            </div>
                        </div>
                        
                        <!-- First Row of Filters -->
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-university me-1"></i>
                                    الكلية
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" 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>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-layer-group me-1"></i>
                                    القسم
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_section" id="filter_section" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !empty($sections)): ?>
                                            <?php foreach ($sections as $section): ?>
                                                <option value="<?= $section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                    <?= e($section['name']) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                                <?php if (!$filter_college_id): ?>
                                    <small class="text-muted">الرجاء اختيار كلية أولاً</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-book me-1"></i>
                                    البرنامج
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_program">
                                        <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>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book-open"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Second Row of Filters -->
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-users me-1"></i>
                                    الدفعة
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" 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>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-graduation-cap me-1"></i>
                                    نوع القبول
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_admission_type">
                                        <option value="">جميع الأنواع</option>
                                        <?php foreach ($admissions as $admission): ?>
                                            <option value="<?= $admission['id'] ?>" <?= ($filter_admission_type == $admission['id']) ? 'selected' : '' ?>>
                                                <?= e($admission['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-user-graduate"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-lg-3 col-md-6 filter-row">
                            <div class="d-flex gap-2 pt-2">
                                <button type="submit" class="btn btn-primary btn-sm px-3">
                                    <i class="fas fa-filter me-1"></i>
                                    تطبيق التصفية
                                </button>
                                <a href="generalsetting-per-student.php" class="btn btn-outline-secondary btn-sm px-3">
                                    <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>
                
                <!-- Filter Summary -->
                <div class="col-md-4">
                    <div class="bg-light rounded p-3 h-100">
                        <div class="d-flex align-items-center mb-2">
                            <i class="fas fa-info-circle me-2 <?= $filters_applied ? 'text-primary' : 'text-secondary' ?>"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        <div class="small">
                            <?php if ($filters_applied): ?>
                                <div class="mb-1">عدد الطلاب: <strong><?= count($students) ?></strong></div>
                                
                                <!-- Show selected filters -->
                                <?php if ($filter_search): ?>
                                    <div class="mb-1">
                                        <span class="fw-semibold">بحث:</span>
                                        <span class="badge bg-info bg-opacity-10 text-info ms-1">
                                            <?= e($filter_search) ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($filter_college_id): ?>
                                    <?php 
                                    $selected_college = null;
                                    foreach ($colleges as $college) {
                                        if ($college['id'] == $filter_college_id) {
                                            $selected_college = $college;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_college): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">الكلية:</span>
                                            <span class="badge bg-primary bg-opacity-10 text-primary ms-1">
                                                <?= e($selected_college['name']) ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($filter_section_id && $filter_college_id && !empty($sections)): ?>
                                    <?php 
                                    $selected_section = null;
                                    foreach ($sections as $section) {
                                        if ($section['id'] == $filter_section_id) {
                                            $selected_section = $section;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_section): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">القسم:</span>
                                            <span class="badge bg-success bg-opacity-10 text-success ms-1">
                                                <?= e($selected_section['name']) ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($filter_program_id): ?>
                                    <?php 
                                    $selected_program = null;
                                    foreach ($programs as $program) {
                                        if ($program['id'] == $filter_program_id) {
                                            $selected_program = $program;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_program): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">البرنامج:</span>
                                            <span class="badge bg-warning bg-opacity-10 text-warning ms-1">
                                                <?= e($selected_program['name']) ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php if ($filter_admission_type): ?>
                                    <?php 
                                    $selected_admission = null;
                                    foreach ($admissions as $adm) {
                                        if ($adm['id'] == $filter_admission_type) {
                                            $selected_admission = $adm;
                                            break;
                                        }
                                    }
                                    ?>
                                    <?php if ($selected_admission): ?>
                                        <div class="mb-1">
                                            <span class="fw-semibold">نوع القبول:</span>
                                            <span class="badge bg-info bg-opacity-10 text-info ms-1">
                                                <?= e($selected_admission['name']) ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <!-- Fees Summary -->
                                <?php if (!empty($students)): 
                                    $total_program_fees = 0;
                                    $total_registration_fees = 0;
                                    $total_insurance_fees = 0;
                                    $total_all_fees = 0;
                                    
                                    foreach ($students as $student) {
                                        $total_program_fees += (float)$student['program_fees'];
                                        $total_registration_fees += (float)$student['registration_fees'];
                                        $total_insurance_fees += (float)$student['insurance_fees'];
                                        $total_all_fees += (float)$student['program_fees'] + (float)$student['registration_fees'] + (float)$student['insurance_fees'];
                                    }
                                ?>
                                <div class="mt-3 pt-2 border-top">
                                    <div class="fw-semibold text-dark mb-1">إجمالي الرسوم:</div>
                                    <div class="row g-1">
                                        <div class="col-6">
                                            <small>دراسية:</small>
                                        </div>
                                        <div class="col-6 text-start">
                                            <small class="fw-bold"><?= number_format($total_program_fees, 2) ?></small>
                                        </div>
                                        <div class="col-6">
                                            <small>تسجيل:</small>
                                        </div>
                                        <div class="col-6 text-start">
                                            <small class="fw-bold"><?= number_format($total_registration_fees, 2) ?></small>
                                        </div>
                                        <div class="col-6">
                                            <small>تأمين:</small>
                                        </div>
                                        <div class="col-6 text-start">
                                            <small class="fw-bold"><?= number_format($total_insurance_fees, 2) ?></small>
                                        </div>
                                        <div class="col-6">
                                            <small class="fw-semibold">المجموع:</small>
                                        </div>
                                        <div class="col-6 text-start">
                                            <small class="fw-bold text-success"><?= number_format($total_all_fees, 2) ?></small>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                            <?php else: ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-filter fa-2x text-muted mb-3"></i>
                                    <p class="text-muted mb-0">لم يتم تطبيق أي تصفية بعد</p>
                                    <p class="text-muted small">الرجاء اختيار عوامل التصفية ثم النقر على "تطبيق التصفية"</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bulk Update Form -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4 mb-4 bulk-update-card">
            <div class="d-flex align-items-center mb-3">
                <h6 class="fw-bold mb-0 text-white">
                    <i class="fas fa-bolt me-2"></i>
                    تحديث جماعي للرسوم
                </h6>
                <span class="badge bg-white text-dark ms-2"><?= count($students) ?> طالب</span>
            </div>
            
            <form method="post" id="bulkUpdateForm" class="text-white">
                <div class="row g-3 align-items-end">
                    <div class="col-md-3">
                        <label class="form-label fw-semibold">نوع التحديث:</label>
                        <select class="form-control" name="update_type" required>
                            <option value="">-- اختر نوع التحديث --</option>
                            <option value="program_fees">رسوم الدراسة فقط</option>
                            <option value="registration_fees">رسوم التسجيل فقط</option>
                            <option value="insurance_fees">رسوم التأمين فقط</option>
                            <option value="all_fees">جميع الرسوم معاً</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-semibold">القيمة الجديدة:</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="fee_value" min="0" step="0.01" required placeholder="0.00">
                            <span class="input-group-text bg-white">SDG</span>
                        </div>
                        <small class="text-white-50">القيمة بالجنيه السوداني</small>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex gap-2 bulk-update-btn">
                            <button type="button" class="btn btn-light" onclick="selectAllStudents()">
                                <i class="fas fa-check-square me-1"></i>تحديد الكل
                            </button>
                            <button type="button" class="btn btn-outline-light" onclick="deselectAllStudents()">
                                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                            </button>
                            <button type="submit" name="update_fees" value="1" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i>تطبيق التحديث على المحددين
                            </button>
                        </div>
                        <div class="text-white-50 small mt-2">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم تطبيق القيمة المحددة على جميع الطلاب المختارين
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <!-- Students Table -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="fw-bold mb-0">قائمة الطلاب والرسوم</h6>
                <div class="d-flex gap-2">
                    <span class="badge bg-primary">
                        <i class="fas fa-users me-1"></i>
                        <?= count($students) ?> طالب
                    </span>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllStudents()">
                        <i class="fas fa-check me-1"></i>تحديد الكل
                    </button>
                </div>
            </div>
            
            <form method="post" id="studentsForm">
                <input type="hidden" name="update_fees" value="1">
                <div class="table-responsive">
                    <table class="table table-striped student-table">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">
                                    <input type="checkbox" id="selectAll" onchange="toggleAllStudents(this)">
                                </th>
                                <th>#</th>
                                <th>رقم الطالب</th>
                                <th>اسم الطالب</th>
                                <th>الكلية</th>
                                <th>القسم</th>
                                <th>البرنامج</th>
                                <th>الدفعة</th>
                                <th>نوع القبول</th>
                                <th>رسوم الدراسة</th>
                                <th>رسوم التسجيل</th>
                                <th>رسوم التأمين</th>
                                <th>المجموع</th>
                                <th>إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach ($students as $student): ?>
                                <?php
                                $program_fees = (float)$student['program_fees'];
                                $registration_fees = (float)$student['registration_fees'];
                                $insurance_fees = (float)$student['insurance_fees'];
                                $total_fees = $program_fees + $registration_fees + $insurance_fees;
                                ?>
                                <tr id="row-<?= e($student['id']) ?>">
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="student_ids[]" value="<?= e($student['id']) ?>" class="student-checkbox">
                                    </td>
                                    <td class="text-muted"><?= $counter++ ?></td>
                                    <td>
                                        <code><?= e($student['student_id']) ?></code>
                                    </td>
                                    <td><?= e($student['student_name']) ?></td>
                                    <td><?= e($student['college_name']) ?></td>
                                    <td><?= e($student['section_name']) ?></td>
                                    <td><?= e($student['program_name']) ?></td>
                                    <td>
                                        <span class="badge bg-secondary batch-badge"><?= e($student['batch_name']) ?></span>
                                    </td>
                                    <td>
                                        <?php if ($student['admission_type_name']): ?>
                                            <span class="badge bg-info fee-type-badge"><?= e($student['admission_type_name']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <input type="number" 
                                               class="form-control form-control-sm fees-input program-fees" 
                                               value="<?= number_format($program_fees, 2, '.', '') ?>" 
                                               step="0.01" 
                                               min="0"
                                               data-student-id="<?= e($student['id']) ?>"
                                               onchange="updateSingleFee(this, 'program_fees')">
                                    </td>
                                    <td>
                                        <input type="number" 
                                               class="form-control form-control-sm fees-input registration-fees" 
                                               value="<?= number_format($registration_fees, 2, '.', '') ?>" 
                                               step="0.01" 
                                               min="0"
                                               data-student-id="<?= e($student['id']) ?>"
                                               onchange="updateSingleFee(this, 'registration_fees')">
                                    </td>
                                    <td>
                                        <input type="number" 
                                               class="form-control form-control-sm fees-input insurance-fees" 
                                               value="<?= number_format($insurance_fees, 2, '.', '') ?>" 
                                               step="0.01" 
                                               min="0"
                                               data-student-id="<?= e($student['id']) ?>"
                                               onchange="updateSingleFee(this, 'insurance_fees')">
                                    </td>
                                    <td class="total-fees">
                                        <?= number_format($total_fees, 2) ?>
                                    </td>
                                    <td>
                                        <button type="button" 
                                                class="btn btn-sm btn-success edit-btn" 
                                                onclick="updateStudentFees('<?= e($student['id']) ?>')"
                                                title="حفظ التغييرات">
                                            <i class="fas fa-save"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <?php if (!empty($students)): 
                            $avg_program_fees = $total_program_fees / count($students);
                            $avg_registration_fees = $total_registration_fees / count($students);
                            $avg_insurance_fees = $total_insurance_fees / count($students);
                            $avg_total_fees = $total_all_fees / count($students);
                        ?>
                        <tfoot class="summary-card">
                            <tr>
                                <th colspan="9" class="text-end">المتوسط:</th>
                                <th class="text-start"><?= number_format($avg_program_fees, 2) ?></th>
                                <th class="text-start"><?= number_format($avg_registration_fees, 2) ?></th>
                                <th class="text-start"><?= number_format($avg_insurance_fees, 2) ?></th>
                                <th class="text-start total-fees"><?= number_format($avg_total_fees, 2) ?></th>
                                <th></th>
                            </tr>
                            <tr>
                                <th colspan="9" class="text-end">الإجمالي:</th>
                                <th class="text-start"><?= number_format($total_program_fees, 2) ?></th>
                                <th class="text-start"><?= number_format($total_registration_fees, 2) ?></th>
                                <th class="text-start"><?= number_format($total_insurance_fees, 2) ?></th>
                                <th class="text-start total-fees"><?= number_format($total_all_fees, 2) ?></th>
                                <th></th>
                            </tr>
                        </tfoot>
                        <?php endif; ?>
                    </table>
                </div>
                
                <!-- Quick Actions -->
                <div class="mt-4 pt-3 border-top">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-outline-primary" onclick="selectAllStudents()">
                                    <i class="fas fa-check-square me-1"></i>تحديد الكل
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="deselectAllStudents()">
                                    <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6 text-start">
                            <div class="text-muted small">
                                <i class="fas fa-info-circle me-1"></i>
                                يمكنك تعديل الرسوم فردياً أو استخدام التحديث الجماعي
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <?php elseif ($filters_applied && empty($students)): ?>
            <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-0">لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Modal for individual student update -->
    <div class="modal fade" id="updateModal" 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"></button>
                </div>
                <form method="post" id="updateSingleForm">
                    <input type="hidden" name="update_single_student" value="1">
                    <div class="modal-body">
                        <input type="hidden" name="student_id" id="modalStudentId">
                        <div class="mb-3">
                            <label class="form-label">رسوم الدراسة</label>
                            <input type="number" class="form-control" name="program_fees" id="modalProgramFees" step="0.01" min="0" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">رسوم التسجيل</label>
                            <input type="number" class="form-control" name="registration_fees" id="modalRegistrationFees" step="0.01" min="0" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">رسوم التأمين</label>
                            <input type="number" class="form-control" name="insurance_fees" id="modalInsuranceFees" step="0.01" min="0" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Student selection functions
        function toggleAllStudents(selectAll) {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
        }
        
        function selectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            document.getElementById('selectAll').checked = true;
        }
        
        function deselectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
        }
        
        // Update individual fee and recalculate total
        function updateSingleFee(input, feeType) {
            const studentId = input.dataset.studentId;
            const row = document.getElementById(`row-${studentId}`);
            const programFeesInput = row.querySelector('.program-fees');
            const registrationFeesInput = row.querySelector('.registration-fees');
            const insuranceFeesInput = row.querySelector('.insurance-fees');
            const totalCell = row.querySelector('.total-fees');
            
            const programFees = parseFloat(programFeesInput.value) || 0;
            const registrationFees = parseFloat(registrationFeesInput.value) || 0;
            const insuranceFees = parseFloat(insuranceFeesInput.value) || 0;
            const total = programFees + registrationFees + insuranceFees;
            
            totalCell.textContent = total.toFixed(2);
            
            // Highlight the row to show changes
            row.style.backgroundColor = '#fff9db';
            setTimeout(() => {
                row.style.backgroundColor = '';
            }, 1000);
        }
        
        // Update all fees for a single student
        function updateStudentFees(studentId) {
            const row = document.getElementById(`row-${studentId}`);
            const programFees = parseFloat(row.querySelector('.program-fees').value) || 0;
            const registrationFees = parseFloat(row.querySelector('.registration-fees').value) || 0;
            const insuranceFees = parseFloat(row.querySelector('.insurance-fees').value) || 0;
            
            // Create a form and submit via AJAX
            const formData = new FormData();
            formData.append('update_single_student', '1');
            formData.append('student_id', studentId);
            formData.append('program_fees', programFees);
            formData.append('registration_fees', registrationFees);
            formData.append('insurance_fees', insuranceFees);
            
            fetch('generalsetting-per-student.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(() => {
                // Show success message
                const btn = row.querySelector('.edit-btn');
                const originalHTML = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-check"></i>';
                btn.classList.remove('btn-success');
                btn.classList.add('btn-primary');
                
                // Reset after 2 seconds
                setTimeout(() => {
                    btn.innerHTML = originalHTML;
                    btn.classList.remove('btn-primary');
                    btn.classList.add('btn-success');
                }, 2000);
                
                // Refresh the page to show updated data
                setTimeout(() => {
                    location.reload();
                }, 500);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('حدث خطأ أثناء تحديث الرسوم');
            });
        }
        
        // Bulk update form validation
        document.getElementById('bulkUpdateForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.student-checkbox:checked').length;
            const updateType = document.querySelector('select[name="update_type"]').value;
            const feeValue = document.querySelector('input[name="fee_value"]').value;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار طالب واحد على الأقل للتحديث');
                return;
            }
            
            if (!updateType) {
                e.preventDefault();
                alert('يرجى اختيار نوع التحديث');
                return;
            }
            
            if (!feeValue || parseFloat(feeValue) < 0) {
                e.preventDefault();
                alert('يرجى إدخال قيمة صحيحة للرسوم');
                return;
            }
            
            const confirmationMessage = `هل أنت متأكد من تحديث الرسوم لـ ${selectedCount} طالب؟\n\nسيتم تعيين ${feeValue} لـ ${getUpdateTypeText(updateType)}`;
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        function getUpdateTypeText(type) {
            switch(type) {
                case 'program_fees': return 'رسوم الدراسة';
                case 'registration_fees': return 'رسوم التسجيل';
                case 'insurance_fees': return 'رسوم التأمين';
                case 'all_fees': return 'جميع الرسوم';
                default: return '';
            }
        }
        
        // Load sections when college changes
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                return;
            }
            
            // Submit form to reload with new college
            document.getElementById('filterForm').submit();
        }
        
        // Auto-calculate totals when page loads
        document.addEventListener('DOMContentLoaded', function() {
            // Update select all checkbox when individual checkboxes change
            document.querySelectorAll('.student-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    const allChecked = document.querySelectorAll('.student-checkbox:checked').length === document.querySelectorAll('.student-checkbox').length;
                    document.getElementById('selectAll').checked = allChecked;
                });
            });
            
            // Add input event listeners to all fee inputs
            document.querySelectorAll('.fees-input').forEach(input => {
                input.addEventListener('input', function() {
                    updateSingleFee(this, this.classList.contains('program-fees') ? 'program_fees' : 
                                             this.classList.contains('registration-fees') ? 'registration_fees' : 'insurance_fees');
                });
            });
            
            // Focus search field on page load if it's empty
            const searchField = document.getElementById('filter_search');
            if (searchField && !searchField.value) {
                searchField.focus();
            }
        });
        
        // Keyboard shortcut for search (Ctrl+F)
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
                e.preventDefault();
                const searchField = document.getElementById('filter_search');
                if (searchField) {
                    searchField.focus();
                }
            }
        });
        
        // Quick search on Enter key
        document.getElementById('filter_search')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
    </script>
</body>
</html>