<?php
// fees_management.php - STUDENT FEES MANAGEMENT SYSTEM (ADMIN ONLY)
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';



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

// Initialize variables
$success_message = '';
$error_message = '';
$selected_students = [];
$bulk_update_mode = false;

// 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_program_id = $_GET['filter_program'] ?? null;
    $filter_batch_id = $_GET['filter_batch'] ?? null;
    $search_query = trim($_GET['search_query'] ?? '');
} else {
    // Don't apply filters by default
    $filter_college_id = null;
    $filter_section_id = null;
    $filter_program_id = null;
    $filter_batch_id = null;
    $search_query = '';
}

// Handle form submission for fees update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_fees'])) {
        $student_ids = $_POST['student_ids'] ?? [];
        $update_type = $_POST['update_type'] ?? 'individual';
        
        if (empty($student_ids)) {
            $error_message = 'لم يتم اختيار أي طلاب للتعديل';
        } else {
            try {
                $mysqli1->begin_transaction();
                
                $updated_count = 0;
                $errors = [];
                
                if ($update_type === 'bulk') {
                    // Bulk update for all selected students
                    $new_study_fees = isset($_POST['bulk_study_fees']) && $_POST['bulk_study_fees'] !== '' ? floatval($_POST['bulk_study_fees']) : null;
                    $new_registration_fees = isset($_POST['bulk_registration_fees']) && $_POST['bulk_registration_fees'] !== '' ? floatval($_POST['bulk_registration_fees']) : null;
                    $new_insurance_fees = isset($_POST['bulk_insurance_fees']) && $_POST['bulk_insurance_fees'] !== '' ? floatval($_POST['bulk_insurance_fees']) : null;
                    
                    foreach ($student_ids as $student_id) {
                        // Get current fees
                        $current_stmt = $mysqli1->prepare("
                            SELECT program_fees, registration_fees, insurance_fees, student_name 
                            FROM students 
                            WHERE student_id = ?
                        ");
                        $current_stmt->bind_param("s", $student_id);
                        $current_stmt->execute();
                        $current_fees = $current_stmt->get_result()->fetch_assoc();
                        $current_stmt->close();
                        
                        if (!$current_fees) {
                            $errors[] = "الطالب $student_id غير موجود";
                            continue;
                        }
                        
                        // Prepare update values (keep current if new is null)
                        $update_fields = [];
                        $update_values = [];
                        $update_types = "";
                        
                        if ($new_study_fees !== null) {
                            $update_fields[] = "program_fees = ?";
                            $update_values[] = $new_study_fees;
                            $update_types .= "d";
                        }
                        
                        if ($new_registration_fees !== null) {
                            $update_fields[] = "registration_fees = ?";
                            $update_values[] = $new_registration_fees;
                            $update_types .= "d";
                        }
                        
                        if ($new_insurance_fees !== null) {
                            $update_fields[] = "insurance_fees = ?";
                            $update_values[] = $new_insurance_fees;
                            $update_types .= "d";
                        }
                        
                        if (!empty($update_fields)) {
                            $update_fields[] = "updated_at = NOW()";
                            
                            // Update student fees
                            $update_sql = "UPDATE students SET " . implode(", ", $update_fields) . " WHERE student_id = ?";
                            $update_stmt = $mysqli1->prepare($update_sql);
                            
                            // Add student_id to parameters
                            $update_values[] = $student_id;
                            $update_types .= "s";
                            
                            $update_stmt->bind_param($update_types, ...$update_values);
                            $update_stmt->execute();
                            $update_stmt->close();
                            
                            $updated_count++;
                        }
                    }
                    
                    if ($updated_count > 0) {
                        $success_message = "تم تحديث الرسوم لـ {$updated_count} طالب بنجاح";
                        if (!empty($errors)) {
                            $success_message .= " (حدثت أخطاء في " . count($errors) . " طالب)";
                        }
                    }
                    
                } else {
                    // Individual update for each student
                    foreach ($student_ids as $student_id) {
                        // Check if fees were provided for this student
                        if (!isset($_POST['study_fees'][$student_id]) || 
                            !isset($_POST['registration_fees'][$student_id]) || 
                            !isset($_POST['insurance_fees'][$student_id])) {
                            continue;
                        }
                        
                        $new_study_fees = floatval($_POST['study_fees'][$student_id]);
                        $new_registration_fees = floatval($_POST['registration_fees'][$student_id]);
                        $new_insurance_fees = floatval($_POST['insurance_fees'][$student_id]);
                        
                        // Update student fees
                        $update_stmt = $mysqli1->prepare("
                            UPDATE students 
                            SET program_fees = ?, registration_fees = ?, insurance_fees = ?, updated_at = NOW()
                            WHERE student_id = ?
                        ");
                        $update_stmt->bind_param(
                            "ddds",
                            $new_study_fees,
                            $new_registration_fees,
                            $new_insurance_fees,
                            $student_id
                        );
                        
                        if ($update_stmt->execute()) {
                            $updated_count++;
                        } else {
                            $errors[] = "خطأ في تحديث رسوم الطالب $student_id: " . $update_stmt->error;
                        }
                        
                        $update_stmt->close();
                    }
                    
                    if ($updated_count > 0) {
                        $success_message = "تم تحديث الرسوم لـ {$updated_count} طالب بنجاح";
                        if (!empty($errors)) {
                            $success_message .= " (حدثت أخطاء في " . count($errors) . " طالب)";
                        }
                    }
                }
                
                // Commit transaction
                $mysqli1->commit();
                
            } catch (Exception $e) {
                // Rollback transaction on error
                $mysqli1->rollback();
                $error_message = "حدث خطأ أثناء تحديث الرسوم: " . $e->getMessage();
                error_log("Fees Update Error: " . $e->getMessage());
            }
        }
    }
}

// Get filtered students ONLY if filters were applied
$students = [];
if ($filters_applied) {
    // Build WHERE clause
    $where = " WHERE 1=1 ";
    $types = ''; 
    $params = [];
    
    // Apply filters
    if ($filter_college_id && !empty($filter_college_id)) {
        $where .= " AND s.college_id = ? ";
        $types .= 'i'; 
        $params[] = $filter_college_id;
    }

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

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

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

    // Apply search query if provided
    if (!empty($search_query)) {
        $where .= " AND (s.student_id LIKE ? OR s.student_name LIKE ? OR s.student_name_eng LIKE ?) ";
        $types .= 'sss';
        $search_param = "%" . $search_query . "%";
        $params[] = $search_param;
        $params[] = $search_param;
        $params[] = $search_param;
    }
    
    $sqlStudents = "
        SELECT 
            s.student_id, s.student_name, s.student_name_eng,
            s.college_id, s.section_id, s.program_id, s.batch_id,
            s.program_fees, s.registration_fees, s.insurance_fees,
            s.created_at, s.updated_at,
            c.name AS college_name,
            sec.name AS section_name,
            p.name AS program_name,
            b.value AS batch_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
        {$where}
        ORDER BY s.student_id DESC
        LIMIT 500
    ";

    $students_stmt = $mysqli1->prepare($sqlStudents);
    if ($types) {
        $students_stmt->bind_param($types, ...$params);
    }
    $students_stmt->execute();
    $students = $students_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $students_stmt->close();
}

// 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("i", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
}

// Get programs
$programs = [];
if ($filter_college_id && !empty($filter_college_id)) {
    $programs_where = "p.deleted_at IS NULL";
    $programs_params = [];
    $programs_types = "";
    
    if ($filter_section_id && !empty($filter_section_id)) {
        $programs_where .= " AND st.section_id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_section_id;
    }
    
    $programs_where .= " AND st.college_id = ?";
    $programs_types .= "i";
    $programs_params[] = $filter_college_id;
    
    $programs_sql = "
        SELECT DISTINCT p.id, p.name 
        FROM programs p 
        INNER JOIN students st ON p.id = st.program_id 
        WHERE {$programs_where} 
        ORDER BY p.name
    ";
    
    $programs_stmt = $mysqli1->prepare($programs_sql);
    if ($programs_types) {
        $programs_stmt->bind_param($programs_types, ...$programs_params);
    }
    $programs_stmt->execute();
    $programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $programs_stmt->close();
} else {
    $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();
}

$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();

// إضافة header بعد معالجة جميع العمليات وقبل أي إخراج HTML
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;
        }
        .fees-input {
            min-width: 100px;
            max-width: 150px;
            width: 180px;
        }
        /* Make all fees input boxes consistent */
        input[name^="study_fees"],
        input[name^="registration_fees"], 
        input[name^="insurance_fees"] {
            min-width: 150px;
            width: 180px;
        }
        .fees-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .admin-badge {
            background-color: #8b5cf6;
            color: white;
        }
        .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;
        }
        .warning-message {
            background-color: #fef3c7;
            border: 1px solid #fde68a;
            color: #92400e;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .update-type-selector {
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .update-type-selector.active {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }
        .form-check-input:checked {
            background-color: #3b82f6;
            border-color: #3b82f6;
        }
        .total-fees-display {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
        }
        .fees-summary-card {
            border-left: 4px solid #10b981;
        }
        .date-display {
            font-size: 0.75rem;
            color: #6c757d;
        }
        /* Style for unselected rows */
        tr.unselected {
            background-color: #f8f9fa;
            opacity: 0.7;
        }
        /* Style for selected rows */
        tr.selected {
            background-color: #e8f5e9;
        }
        /* Highlight when checkbox is checked */
        .student-checkbox:checked {
            accent-color: #3b82f6;
        }
        .selected-count-badge {
            font-size: 0.8rem;
            padding: 0.3rem 0.6rem;
        }
    </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="badge admin-badge me-2">
                    <i class="fas fa-user-shield me-1"></i>مدير النظام
                </span>
                <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">
                        
                        <!-- College Filter -->
                        <div class="col-lg-3 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>
                                <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): ?>
                                            <option value="<?= $college['id'] ?>" <?= (isset($_GET['filter_college']) && $_GET['filter_college'] == $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>
                        
                        <!-- Section Filter -->
                        <div class="col-lg-3 col-md-6">
                            <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'] ?>" <?= (isset($_GET['filter_section']) && $_GET['filter_section'] == $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>
                        
                        <!-- Program Filter -->
                        <div class="col-lg-3 col-md-6">
                            <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_program" id="filter_program">
                                        <option value="">جميع البرامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= $program['id'] ?>" <?= (isset($_GET['filter_program']) && $_GET['filter_program'] == $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"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-3 col-md-6">
                            <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'] ?>" <?= (isset($_GET['filter_batch']) && $_GET['filter_batch'] == $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>
                        
                        <!-- Search Field -->
                        <div class="col-12 mt-2">
                            <div class="input-group input-group-sm">
                                <input type="text" 
                                       class="form-control" 
                                       name="search_query" 
                                       id="search_query"
                                       placeholder="بحث برقم الطالب أو اسم الطالب..."
                                       value="<?= e($search_query) ?>"
                                       autocomplete="off">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-search"></i>
                                </span>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="col-12">
                            <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="fees_management.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>
                                        تم تطبيق التصفية
                                        <?php if (!empty($search_query)): ?>
                                            <i class="fas fa-search ms-1"></i>
                                        <?php endif; ?>
                                    </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>
                                
                                <?php if (!empty($search_query)): ?>
                                    <div class="mb-2 p-2 bg-warning bg-opacity-10 rounded">
                                        <div class="fw-semibold text-warning mb-1">
                                            <i class="fas fa-search me-1"></i>
                                            نتيجة البحث
                                        </div>
                                        <div class="text-truncate">
                                            "<?= e($search_query) ?>"
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mb-2 p-2 bg-primary bg-opacity-10 rounded">
                                    <div class="fw-semibold text-primary mb-1">
                                        <i class="fas fa-shield-alt me-1"></i>
                                        صلاحيات النظام
                                    </div>
                                    <div>مدير النظام - كامل الصلاحيات</div>
                                </div>
                            <?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>

        <!-- Update Type Selector -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4 mb-4">
            <h6 class="fw-bold mb-3">طريقة التعديل</h6>
            <div class="row">
                <div class="col-md-6">
                    <div class="update-type-selector <?= !$bulk_update_mode ? 'active' : '' ?>" onclick="setUpdateType('individual')">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="update_type" id="updateTypeIndividual" 
                                   value="individual" <?= !$bulk_update_mode ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="updateTypeIndividual">
                                <i class="fas fa-user-edit me-2"></i>
                                تعديل فردي لكل طالب
                            </label>
                            <p class="text-muted small mt-2 mb-0">
                                يمكنك تعديل رسوم كل طالب على حدة في الجدول أدناه
                            </p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="update-type-selector <?= $bulk_update_mode ? 'active' : '' ?>" onclick="setUpdateType('bulk')">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="update_type" id="updateTypeBulk" 
                                   value="bulk" <?= $bulk_update_mode ? 'checked' : '' ?>>
                            <label class="form-check-label fw-bold" for="updateTypeBulk">
                                <i class="fas fa-users-cog me-2"></i>
                                تعديل جماعي لجميع الطلاب المحددين
                            </label>
                            <p class="text-muted small mt-2 mb-0">
                                تطبيق نفس القيم على جميع الطلاب المحددين
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Bulk Update Form (Hidden by default) -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4 mb-4" id="bulkUpdateForm" style="<?= !$bulk_update_mode ? 'display: none;' : '' ?>">
            <h6 class="fw-bold mb-3">
                <i class="fas fa-users-cog me-2"></i>
                تعديل جماعي
            </h6>
            
            <div class="warning-message mb-3">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>تنبيه:</strong> سيتم تطبيق القيم التالية على جميع الطلاب المحددين. اترك الحقل فارغاً للحفاظ على القيمة الحالية.
            </div>
            
            <form method="post" id="bulkUpdateFormContent">
                <div class="row g-3 mb-4">
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">رسوم الدراسة:</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="bulk_study_fees" 
                                   step="0.01" min="0" placeholder="اترك فارغاً للحفاظ على القيمة">
                            <span class="input-group-text">SDG</span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">رسوم التسجيل:</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="bulk_registration_fees" 
                                   step="0.01" min="0" placeholder="اترك فارغاً للحفاظ على القيمة">
                            <span class="input-group-text">SDG</span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">رسوم التأمين:</label>
                        <div class="input-group">
                            <input type="number" class="form-control" name="bulk_insurance_fees" 
                                   step="0.01" min="0" placeholder="اترك فارغاً للحفاظ على القيمة">
                            <span class="input-group-text">SDG</span>
                        </div>
                    </div>
                </div>
                
                <!-- Hidden student IDs -->
                <div id="bulkStudentIds"></div>
                
                <!-- Action Buttons -->
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <span class="badge bg-info">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم تطبيق القيم على جميع الطلاب المحددين
                        </span>
                    </div>
                    <div>
                        <button type="button" class="btn btn-secondary me-2" onclick="showUpdateForm()">
                            <i class="fas fa-arrow-right me-1"></i>
                            العودة للتعديل الفردي
                        </button>
                        <button type="button" class="btn btn-success" onclick="submitBulkUpdate()">
                            <i class="fas fa-check-circle me-1"></i>
                            تطبيق التعديل الجماعي
                        </button>
                    </div>
                </div>
            </form>
        </div>
        <?php endif; ?>

        <!-- Fees Update Form -->
        <?php if ($filters_applied && !empty($students)): ?>
        <div class="card card-arabic p-4 mb-4" id="updateForm" style="<?= $bulk_update_mode ? 'display: none;' : '' ?>">
            <form method="post" id="feesUpdateForm">
                
                <!-- Action Buttons with Selected Count -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-6">
                        <div class="d-flex gap-2 align-items-center">
                            <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>
                            <button type="button" class="btn btn-info" onclick="showBulkUpdate()">
                                <i class="fas fa-users-cog me-1"></i>التعديل الجماعي
                            </button>
                            <span id="selectedCountBadge" class="badge bg-primary selected-count-badge">
                                0 مختار
                            </span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex justify-content-end">
                            <button type="submit" name="update_fees" class="btn btn-success">
                                <i class="fas fa-save me-1"></i>حفظ التعديلات للطلاب المحددين
                            </button>
                        </div>
                        <div class="text-muted small text-end mt-1">
                            <i class="fas fa-shield-alt me-1"></i>
                            <strong>مدير النظام:</strong> <?= e($_SESSION['user_name'] ?? '') ?>
                        </div>
                    </div>
                </div>
                
                <!-- Students Table -->
                <div class="table-responsive mt-4">
                    <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>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $counter = 1; ?>
                            <?php foreach ($students as $student): ?>
                                <?php
                                // Calculate total fees
                                $study_fees = !empty($student['program_fees']) ? floatval($student['program_fees']) : 0.00;
                                $registration_fees = !empty($student['registration_fees']) ? floatval($student['registration_fees']) : 0.00;
                                $insurance_fees = !empty($student['insurance_fees']) ? floatval($student['insurance_fees']) : 0.00;
                                $total_fees = $study_fees + $registration_fees + $insurance_fees;
                                
                                // Handle null dates safely
                                $created_at = !empty($student['created_at']) ? date('Y-m-d', strtotime($student['created_at'])) : '';
                                $updated_at = !empty($student['updated_at']) ? date('Y-m-d', strtotime($student['updated_at'])) : '';
                                ?>
                                <tr class="unselected">
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="student_ids[]" value="<?= e($student['student_id']) ?>" class="student-checkbox">
                                    </td>
                                    <td class="text-muted"><?= $counter++ ?></td>
                                    <td>
                                        <code><?= e($student['student_id']) ?></code>
                                        <?php if ($created_at): ?>
                                            <br><small class="date-display"><?= $created_at ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?= e($student['student_name']) ?>
                                        <?php if ($student['student_name_eng']): ?>
                                            <br><small class="text-muted"><?= e($student['student_name_eng']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= e($student['college_name']) ?></td>
                                    <td><?= e($student['program_name']) ?></td>
                                    <td>
                                        <span class="badge bg-secondary batch-badge"><?= e($student['batch_name']) ?></span>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm fees-input" 
                                               name="study_fees[<?= e($student['student_id']) ?>]" 
                                               value="<?= number_format($study_fees, 2, '.', '') ?>" 
                                               step="0.01" min="0" required>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm fees-input" 
                                               name="registration_fees[<?= e($student['student_id']) ?>]" 
                                               value="<?= number_format($registration_fees, 2, '.', '') ?>" 
                                               step="0.01" min="0" required>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm fees-input" 
                                               name="insurance_fees[<?= e($student['student_id']) ?>]" 
                                               value="<?= number_format($insurance_fees, 2, '.', '') ?>" 
                                               step="0.01" min="0" required>
                                    </td>
                                    <td>
                                        <span class="badge bg-primary fees-badge">
                                            <?= number_format($total_fees, 2) ?> SDG
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($updated_at): ?>
                                            <small class="date-display"><?= $updated_at ?></small>
                                        <?php else: ?>
                                            <small class="text-muted">-</small>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Hidden field for update type -->
                <input type="hidden" name="update_type" value="individual">
            </form>
        </div>
        
        <!-- Fees Summary -->
        <div class="card card-arabic p-4 fees-summary-card">
            <div class="row">
                <div class="col-md-3">
                    <div class="total-fees-display text-center">
                        <div class="small">إجمالي الرسوم الحالية</div>
                        <h4 class="fw-bold mb-0" id="totalFeesDisplay">0.00 SDG</h4>
                        <small>لجميع الطلاب المحددين</small>
                    </div>
                </div>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="text-center p-3">
                                <div class="text-muted small mb-1">رسوم الدراسة</div>
                                <div class="h5 fw-bold text-info" id="totalStudyFees">0.00</div>
                                <small class="text-muted">SDG</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3">
                                <div class="text-muted small mb-1">رسوم التسجيل</div>
                                <div class="h5 fw-bold text-warning" id="totalRegistrationFees">0.00</div>
                                <small class="text-muted">SDG</small>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3">
                                <div class="text-muted small mb-1">رسوم التأمين</div>
                                <div class="h5 fw-bold text-success" id="totalInsuranceFees">0.00</div>
                                <small class="text-muted">SDG</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </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">
                    <?php if (!empty($search_query)): ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة والبحث: "<?= e($search_query) ?>"
                    <?php else: ?>
                        لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function toggleAllStudents(selectAll) {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
                const row = checkbox.closest('tr');
                if (row) {
                    if (selectAll.checked) {
                        row.classList.remove('unselected');
                        row.classList.add('selected');
                    } else {
                        row.classList.remove('selected');
                        row.classList.add('unselected');
                    }
                }
            });
            calculateTotals();
        }
        
        function selectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
                const row = checkbox.closest('tr');
                if (row) {
                    row.classList.remove('unselected');
                    row.classList.add('selected');
                }
            });
            document.getElementById('selectAll').checked = true;
            calculateTotals();
        }
        
        function deselectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
                const row = checkbox.closest('tr');
                if (row) {
                    row.classList.remove('selected');
                    row.classList.add('unselected');
                }
            });
            document.getElementById('selectAll').checked = false;
            calculateTotals();
        }
        
        // Update select all checkbox when individual checkboxes change
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const row = this.closest('tr');
                if (row) {
                    if (this.checked) {
                        row.classList.remove('unselected');
                        row.classList.add('selected');
                    } else {
                        row.classList.remove('selected');
                        row.classList.add('unselected');
                    }
                }
                
                const allChecked = document.querySelectorAll('.student-checkbox:checked').length === document.querySelectorAll('.student-checkbox').length;
                document.getElementById('selectAll').checked = allChecked;
                calculateTotals();
            });
        });
        
        // Calculate and update totals
        function calculateTotals() {
            let totalStudyFees = 0;
            let totalRegistrationFees = 0;
            let totalInsuranceFees = 0;
            let selectedCount = 0;
            
            document.querySelectorAll('.student-checkbox').forEach(checkbox => {
                const row = checkbox.closest('tr');
                if (row && checkbox.checked) {
                    selectedCount++;
                    const studyInput = row.querySelector('input[name^="study_fees"]');
                    const regInput = row.querySelector('input[name^="registration_fees"]');
                    const insuranceInput = row.querySelector('input[name^="insurance_fees"]');
                    
                    if (studyInput) totalStudyFees += parseFloat(studyInput.value) || 0;
                    if (regInput) totalRegistrationFees += parseFloat(regInput.value) || 0;
                    if (insuranceInput) totalInsuranceFees += parseFloat(insuranceInput.value) || 0;
                }
            });
            
            const totalFees = totalStudyFees + totalRegistrationFees + totalInsuranceFees;
            
            document.getElementById('totalStudyFees').textContent = totalStudyFees.toFixed(2);
            document.getElementById('totalRegistrationFees').textContent = totalRegistrationFees.toFixed(2);
            document.getElementById('totalInsuranceFees').textContent = totalInsuranceFees.toFixed(2);
            document.getElementById('totalFeesDisplay').textContent = totalFees.toFixed(2) + ' SDG';
            
            // Update selected count badge
            const selectedBadge = document.getElementById('selectedCountBadge');
            if (selectedBadge) {
                selectedBadge.textContent = selectedCount + ' مختار';
            }
        }
        
        // Listen to input changes in fees fields
        document.querySelectorAll('.fees-input').forEach(input => {
            input.addEventListener('input', calculateTotals);
        });
        
        // Form submission confirmation
        document.getElementById('feesUpdateForm')?.addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.student-checkbox:checked').length;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار طالب واحد على الأقل للتعديل');
                return;
            }
            
            if (!confirm(`هل أنت متأكد من تحديث الرسوم لـ ${selectedCount} طالب؟`)) {
                e.preventDefault();
            }
        });
        
        function setUpdateType(type) {
            document.querySelectorAll('input[name="update_type"]').forEach(radio => {
                if (radio.value === type) {
                    radio.checked = true;
                    radio.closest('.update-type-selector').classList.add('active');
                } else {
                    radio.closest('.update-type-selector').classList.remove('active');
                }
            });
            
            if (type === 'bulk') {
                showBulkUpdate();
            } else {
                showUpdateForm();
            }
        }
        
        function showBulkUpdate() {
            document.getElementById('updateForm').style.display = 'none';
            document.getElementById('bulkUpdateForm').style.display = 'block';
            
            // Collect all checked student IDs
            const studentIds = [];
            document.querySelectorAll('.student-checkbox:checked').forEach(checkbox => {
                studentIds.push(checkbox.value);
            });
            
            // Create hidden inputs for student IDs
            const container = document.getElementById('bulkStudentIds');
            container.innerHTML = '';
            studentIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'student_ids[]';
                input.value = id;
                container.appendChild(input);
            });
            
            // Show warning if no students selected
            if (studentIds.length === 0) {
                alert('الرجاء اختيار طلاب أولاً قبل استخدام التعديل الجماعي');
                showUpdateForm();
                return;
            }
        }
        
        function showUpdateForm() {
            document.getElementById('updateForm').style.display = 'block';
            document.getElementById('bulkUpdateForm').style.display = 'none';
        }
        
        function submitBulkUpdate() {
            const form = document.getElementById('bulkUpdateFormContent');
            const studentIds = document.querySelectorAll('#bulkStudentIds input');
            
            if (studentIds.length === 0) {
                alert('الرجاء اختيار طلاب أولاً');
                return;
            }
            
            if (!confirm('هل أنت متأكد من تطبيق التعديل الجماعي على جميع الطلاب المحددين؟')) {
                return;
            }
            
            // Create a new form for submission
            const submitForm = document.createElement('form');
            submitForm.method = 'post';
            submitForm.style.display = 'none';
            document.body.appendChild(submitForm);
            
            // Add all student IDs
            studentIds.forEach(input => {
                const newInput = document.createElement('input');
                newInput.type = 'hidden';
                newInput.name = input.name;
                newInput.value = input.value;
                submitForm.appendChild(newInput);
            });
            
            // Add bulk update values
            const bulkStudyFees = document.querySelector('input[name="bulk_study_fees"]');
            const bulkRegFees = document.querySelector('input[name="bulk_registration_fees"]');
            const bulkInsuranceFees = document.querySelector('input[name="bulk_insurance_fees"]');
            
            if (bulkStudyFees.value !== '') {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'bulk_study_fees';
                input.value = bulkStudyFees.value;
                submitForm.appendChild(input);
            }
            
            if (bulkRegFees.value !== '') {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'bulk_registration_fees';
                input.value = bulkRegFees.value;
                submitForm.appendChild(input);
            }
            
            if (bulkInsuranceFees.value !== '') {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'bulk_insurance_fees';
                input.value = bulkInsuranceFees.value;
                submitForm.appendChild(input);
            }
            
            // Add update type
            const updateTypeInput = document.createElement('input');
            updateTypeInput.type = 'hidden';
            updateTypeInput.name = 'update_type';
            updateTypeInput.value = 'bulk';
            submitForm.appendChild(updateTypeInput);
            
            // Add submit button
            const submitInput = document.createElement('input');
            submitInput.type = 'hidden';
            submitInput.name = 'update_fees';
            submitInput.value = '1';
            submitForm.appendChild(submitInput);
            
            submitForm.submit();
        }
        
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            
            if (!collegeId || collegeId === '') {
                sectionSelect.disabled = true;
                sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
                return;
            }
            
            // Submit the form to reload with new college
            const form = document.getElementById('filterForm');
            form.submit();
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Initially all rows are unselected
            document.querySelectorAll('.student-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
            calculateTotals();
        });
    </script>
</body>
</html>