<?php
// reports/partially_registered.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../helpers.php';

// Set charset for mysqli connection to prevent SQL injection
$mysqli1->set_charset("utf8mb4");

// Check committee access
if (!isset($_SESSION['committee_id'])) {
    header('Location: ../login.php');
    exit;
}

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;

// Initialize variables
$students = [];
$error_message = '';
$success_message = '';

// Validate and sanitize input parameters
$filters_applied = isset($_GET['filter_applied']) && $_GET['filter_applied'] === '1';

// Get and validate filter parameters - with proper sanitization
$filter_college_id = isset($_GET['filter_college']) && ctype_digit($_GET['filter_college']) ? (int)$_GET['filter_college'] : null;
$filter_section_id = isset($_GET['filter_section']) && ctype_digit($_GET['filter_section']) ? (int)$_GET['filter_section'] : null;
$filter_program_id = isset($_GET['filter_program']) && ctype_digit($_GET['filter_program']) ? (int)$_GET['filter_program'] : null;
$filter_specialization_id = isset($_GET['filter_specialization']) && ctype_digit($_GET['filter_specialization']) ? (int)$_GET['filter_specialization'] : null;
$filter_batch_id = isset($_GET['filter_batch']) && ctype_digit($_GET['filter_batch']) ? (int)$_GET['filter_batch'] : null;
$filter_semester_id = isset($_GET['filter_semester']) && ctype_digit($_GET['filter_semester']) ? (int)$_GET['filter_semester'] : null;

// Validate that semester is required when filters are applied
if ($filters_applied && empty($filter_semester_id)) {
    $error_message = "الرجاء اختيار فصل دراسي لعرض الطلاب القائمة الطلاب الذين لم يكملوا سداد الرسوم";
    $filters_applied = false;
}

// Apply scope restrictions
if (!$canAll && $scopeCollege !== null) {
    // Force college filter to user's scope
    $filter_college_id = $scopeCollege;
} elseif (!$canAll && $scopeCollege === null) {
    // No access
    $filter_college_id = -1; // This will return no results
}

// Get filter data with prepared statements
$colleges = [];
$sections = [];
$programs = [];
$specializations = [];
$batches = [];
$semesters = [];
$semester_name = '';
$semester_code = '';
$college_name = '';
$section_name = '';
$program_name = '';
$specialization_name = '';
$batch_name = '';

try {
    // Get colleges with prepared statement
    $colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
    if ($colleges_stmt) {
        $colleges_stmt->execute();
        $colleges_result = $colleges_stmt->get_result();
        while ($row = $colleges_result->fetch_assoc()) {
            $colleges[] = $row;
        }
        $colleges_stmt->close();
    }

    // Get college name if selected
    if ($filter_college_id && $filter_college_id > 0) {
        $college_stmt = $mysqli1->prepare("SELECT name FROM colleges WHERE id = ? AND deleted_at IS NULL");
        if ($college_stmt) {
            $college_stmt->bind_param("i", $filter_college_id);
            $college_stmt->execute();
            $college_result = $college_stmt->get_result();
            if ($college_row = $college_result->fetch_assoc()) {
                $college_name = $college_row['name'];
            }
            $college_stmt->close();
        }
    }

    // Get sections based on selected college with prepared statement
    if ($filter_college_id && $filter_college_id > 0) {
        $sections_stmt = $mysqli1->prepare("
            SELECT DISTINCT s.id, s.name, s.parent
            FROM sections s 
            WHERE s.parent = ? AND s.deleted_at IS NULL 
            ORDER BY s.name
        ");
        if ($sections_stmt) {
            $sections_stmt->bind_param("i", $filter_college_id);
            $sections_stmt->execute();
            $sections_result = $sections_stmt->get_result();
            while ($row = $sections_result->fetch_assoc()) {
                $sections[] = $row;
            }
            $sections_stmt->close();
        }

        // Get section name if selected
        if ($filter_section_id && $filter_section_id > 0) {
            $section_stmt = $mysqli1->prepare("SELECT name FROM sections WHERE id = ? AND deleted_at IS NULL");
            if ($section_stmt) {
                $section_stmt->bind_param("i", $filter_section_id);
                $section_stmt->execute();
                $section_result = $section_stmt->get_result();
                if ($section_row = $section_result->fetch_assoc()) {
                    $section_name = $section_row['name'];
                }
                $section_stmt->close();
            }
        }
    }

    // Get programs with prepared statement
    $programs_query = "
        SELECT DISTINCT p.id, p.name 
        FROM programs p 
        WHERE p.deleted_at IS NULL
    ";
    $programs_params = [];
    $programs_types = "";

    if ($filter_program_id && $filter_program_id > 0) {
        $programs_query .= " AND p.id = ?";
        $programs_types .= "i";
        $programs_params[] = $filter_program_id;
    }

    $programs_query .= " ORDER BY p.name";

    $programs_stmt = $mysqli1->prepare($programs_query);
    if ($programs_stmt) {
        if (!empty($programs_params)) {
            $programs_stmt->bind_param($programs_types, ...$programs_params);
        }
        $programs_stmt->execute();
        $programs_result = $programs_stmt->get_result();
        while ($row = $programs_result->fetch_assoc()) {
            $programs[] = $row;
            
            // Get program name if selected
            if ($filter_program_id && $row['id'] == $filter_program_id) {
                $program_name = $row['name'];
            }
        }
        $programs_stmt->close();
    }

    // Get specializations based on selected section and program
    if ($filter_section_id && $filter_section_id > 0 && $filter_program_id && $filter_program_id > 0) {
        $specializations_stmt = $mysqli1->prepare("
            SELECT specialization_id, specialization_name_ar 
            FROM specializations 
            WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
            ORDER BY specialization_name_ar
        ");
        if ($specializations_stmt) {
            $specializations_stmt->bind_param("ii", $filter_section_id, $filter_program_id);
            $specializations_stmt->execute();
            $specializations_result = $specializations_stmt->get_result();
            while ($row = $specializations_result->fetch_assoc()) {
                $specializations[] = $row;
                
                // Get specialization name if selected
                if ($filter_specialization_id && $row['specialization_id'] == $filter_specialization_id) {
                    $specialization_name = $row['specialization_name_ar'];
                }
            }
            $specializations_stmt->close();
        }
    } elseif ($filter_section_id && $filter_section_id > 0) {
        // Get specializations by section only
        $specializations_stmt = $mysqli1->prepare("
            SELECT DISTINCT specialization_id, specialization_name_ar 
            FROM specializations 
            WHERE section_id = ? AND deleted_at IS NULL 
            ORDER BY specialization_name_ar
        ");
        if ($specializations_stmt) {
            $specializations_stmt->bind_param("i", $filter_section_id);
            $specializations_stmt->execute();
            $specializations_result = $specializations_stmt->get_result();
            while ($row = $specializations_result->fetch_assoc()) {
                $specializations[] = $row;
                
                // Get specialization name if selected
                if ($filter_specialization_id && $row['specialization_id'] == $filter_specialization_id) {
                    $specialization_name = $row['specialization_name_ar'];
                }
            }
            $specializations_stmt->close();
        }
    } elseif ($filter_program_id && $filter_program_id > 0) {
        // Get specializations by program only
        $specializations_stmt = $mysqli1->prepare("
            SELECT DISTINCT specialization_id, specialization_name_ar 
            FROM specializations 
            WHERE program_id = ? AND deleted_at IS NULL 
            ORDER BY specialization_name_ar
        ");
        if ($specializations_stmt) {
            $specializations_stmt->bind_param("i", $filter_program_id);
            $specializations_stmt->execute();
            $specializations_result = $specializations_stmt->get_result();
            while ($row = $specializations_result->fetch_assoc()) {
                $specializations[] = $row;
                
                // Get specialization name if selected
                if ($filter_specialization_id && $row['specialization_id'] == $filter_specialization_id) {
                    $specialization_name = $row['specialization_name_ar'];
                }
            }
            $specializations_stmt->close();
        }
    }

    // Get batches with prepared statement
    $batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY id DESC");
    if ($batches_stmt) {
        $batches_stmt->execute();
        $batches_result = $batches_stmt->get_result();
        while ($row = $batches_result->fetch_assoc()) {
            $batches[] = $row;
            
            // Get batch name if selected
            if ($filter_batch_id && $row['id'] == $filter_batch_id) {
                $batch_name = $row['value'];
            }
        }
        $batches_stmt->close();
    }

    // Get semesters with prepared statement
    $semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
    if ($semesters_stmt) {
        $semesters_stmt->execute();
        $semesters_result = $semesters_stmt->get_result();
        while ($row = $semesters_result->fetch_assoc()) {
            $semesters[] = $row;
        }
        $semesters_stmt->close();
    }

    // Get semester info if selected
    if ($filter_semester_id && $filter_semester_id > 0) {
        $semester_stmt = $mysqli1->prepare("SELECT name, code FROM semesters WHERE id = ? AND deleted_at IS NULL");
        if ($semester_stmt) {
            $semester_stmt->bind_param("i", $filter_semester_id);
            $semester_stmt->execute();
            $semester_result = $semester_stmt->get_result();
            if ($semester_row = $semester_result->fetch_assoc()) {
                $semester_name = $semester_row['name'] . ' (' . $semester_row['code'] . ')';
                $semester_code = $semester_row['code'];
            }
            $semester_stmt->close();
        }
    }

    // Get partially registered students ONLY if filters are applied and semester is selected
    if ($filters_applied && !empty($filter_semester_id) && $filter_semester_id > 0) {
        
        // Build the students query with proper prepared statements
        $students_query = "
            SELECT 
                s.student_id,
                s.student_name,
                s.student_name_eng,
                s.college_id,
                s.section_id,
                s.program_id,
                s.specialization_id,
                s.batch_id,
                c.name AS college_name,
                sec.name AS section_name,
                p.name AS program_name,
                sp.specialization_name_ar AS specialization_name,
                b.value AS batch_name,
                reg_summary.total_paid_amount,
                reg_summary.total_unpaid_amount,
                reg_summary.total_fees,
                reg_summary.paid_count,
                reg_summary.unpaid_count,
                reg_summary.total_registrations,
                reg_summary.payment_percentage,
                reg_summary.last_registration_date
            FROM students s
            LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
            LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
            LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
            LEFT JOIN specializations sp ON s.specialization_id = sp.specialization_id AND sp.deleted_at IS NULL
            LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
            INNER JOIN (
                -- Internal query to get payment statistics
                SELECT 
                    r.student_id,
                    SUM(CASE WHEN r.is_paid = 1 THEN r.payment_amount ELSE 0 END) as total_paid_amount,
                    SUM(CASE WHEN r.is_paid = 0 THEN r.payment_amount ELSE 0 END) as total_unpaid_amount,
                    SUM(r.payment_amount) as total_fees,
                    SUM(CASE WHEN r.is_paid = 1 THEN 1 ELSE 0 END) as paid_count,
                    SUM(CASE WHEN r.is_paid = 0 THEN 1 ELSE 0 END) as unpaid_count,
                    COUNT(r.id) as total_registrations,
                    ROUND((SUM(CASE WHEN r.is_paid = 1 THEN r.payment_amount ELSE 0 END) / SUM(r.payment_amount)) * 100, 1) as payment_percentage,
                    MAX(r.created_at) as last_registration_date
                FROM registrations r
                WHERE r.semester_id = ? 
                  AND r.deleted_at IS NULL
                GROUP BY r.student_id
                HAVING paid_count > 0 
                   AND unpaid_count > 0
                   AND total_registrations > 0
            ) reg_summary ON reg_summary.student_id = s.student_id
            WHERE s.deleted_at IS NULL
        ";

        $students_params = [$filter_semester_id];
        $students_types = "i";

        // Apply college filter
        if ($filter_college_id && $filter_college_id > 0) {
            $students_query .= " AND s.college_id = ?";
            $students_types .= "i";
            $students_params[] = $filter_college_id;
        }

        // Apply section filter
        if ($filter_section_id && $filter_section_id > 0) {
            $students_query .= " AND s.section_id = ?";
            $students_types .= "i";
            $students_params[] = $filter_section_id;
        }

        // Apply program filter
        if ($filter_program_id && $filter_program_id > 0) {
            $students_query .= " AND s.program_id = ?";
            $students_types .= "i";
            $students_params[] = $filter_program_id;
        }

        // Apply specialization filter
        if ($filter_specialization_id && $filter_specialization_id > 0) {
            $students_query .= " AND s.specialization_id = ?";
            $students_types .= "i";
            $students_params[] = $filter_specialization_id;
        }

        // Apply batch filter
        if ($filter_batch_id && $filter_batch_id > 0) {
            $students_query .= " AND s.batch_id = ?";
            $students_types .= "i";
            $students_params[] = $filter_batch_id;
        }

        $students_query .= " ORDER BY reg_summary.payment_percentage DESC, reg_summary.last_registration_date DESC, s.student_name LIMIT 1000";

        // Execute the query with prepared statement
        $students_stmt = $mysqli1->prepare($students_query);
        if ($students_stmt) {
            $students_stmt->bind_param($students_types, ...$students_params);
            $students_stmt->execute();
            $students_result = $students_stmt->get_result();
            while ($row = $students_result->fetch_assoc()) {
                $students[] = $row;
            }
            $students_stmt->close();
        } else {
            $error_message = "حدث خطأ في جلب بيانات الطلاب";
        }
    }

} catch (Exception $e) {
    error_log("Database error in partially_registered.php: " . $e->getMessage());
    $error_message = "حدث خطأ في قاعدة البيانات. الرجاء المحاولة مرة أخرى.";
}

// Calculate totals for partially registered students
$totalStudents = count($students);
$totalPaidAmount = 0;
$totalUnpaidAmount = 0;
$totalFees = 0;
$avgPaymentPercentage = 0;

if ($totalStudents > 0) {
    $totalPaidAmount = array_sum(array_column($students, 'total_paid_amount'));
    $totalUnpaidAmount = array_sum(array_column($students, 'total_unpaid_amount'));
    $totalFees = array_sum(array_column($students, 'total_fees'));
    $avgPaymentPercentage = array_sum(array_column($students, 'payment_percentage')) / $totalStudents;
}

// Include header with correct path
include __DIR__ . '/../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>
        /* Base RTL Styles */
        body, h1, h2, h3, h4, h5, h6, p, a, button, label, .container, .card, .table, .form-control, .form-select { 
            font-family: 'Cairo', sans-serif !important; 
            direction: rtl;
            text-align: right;
        }
        
        .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: linear-gradient(135deg, #f59e0b, #d97706);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.1rem;
            margin-left: 1rem !important;
            margin-right: 0 !important;
        }
        
        .filter-status {
            font-size: 0.85rem;
            padding: 0.3rem 0.6rem;
            border-radius: 6px;
        }
        
        .filter-status.applied {
            background-color: #fef3c7;
            color: #92400e;
            border: 1px solid #fde68a;
        }
        
        .filter-status.not-applied {
            background-color: #fef3c7;
            color: #92400e;
            border: 1px solid #fde68a;
        }
        
        .info-message {
            background-color: #fef3c7;
            border: 1px solid #fbbf24;
            color: #92400e;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .warning-message {
            background-color: #fee2e2;
            border: 1px solid #f87171;
            color: #991b1b;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        
        .student-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            text-align: right !important;
        }
        
        .student-table td {
            text-align: right !important;
        }
        
        .badge-custom {
            padding: 5px 10px;
            border-radius: 20px;
            font-weight: 500;
        }
        
        .form-select, .form-control {
            border-radius: 8px;
            border: 1px solid #ced4da;
        }
        
        .form-select:focus, .form-control:focus {
            border-color: #f59e0b;
            box-shadow: 0 0 0 0.2rem rgba(245, 158, 11, 0.25);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            border: none;
            border-radius: 8px;
            padding: 8px 20px;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #d97706, #b45309);
        }
        
        .table-responsive {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
        }
        
        .total-row {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        .total-row td {
            border-top: 2px solid #dee2e6;
        }
        
        .chip {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        
        .chip.warning { background: #fef3c7; color: #92400e; }
        .chip.danger { background: #fee2e2; color: #991b1b; }
        .chip.success { background: #d1fae5; color: #065f46; }
        .chip.info { background: #dbeafe; color: #1e40af; }
        .chip.secondary { background: #e9ecef; color: #495057; }
        .chip.specialization { background: #f3e8ff; color: #6b21a8; }
        
        .payment-progress {
            height: 10px;
            background-color: #e5e7eb;
            border-radius: 5px;
            overflow: hidden;
            margin-top: 5px;
        }
        
        .payment-progress-bar {
            height: 100%;
            border-radius: 5px;
        }
        
        .progress-high { background: linear-gradient(90deg, #10b981, #34d399); }
        .progress-medium { background: linear-gradient(90deg, #f59e0b, #fbbf24); }
        .progress-low { background: linear-gradient(90deg, #ef4444, #f87171); }
        
        @media print {
            .no-print { display: none !important; }
            body { font-size: 12px; }
            table { font-size: 10px; }
        }
        
        .semester-warning {
            background-color: #fffbeb;
            border-right: 4px solid #f59e0b;
            border-left: none;
            padding: 10px 15px;
            margin-bottom: 15px;
            border-radius: 6px;
        }
        
        .print-container {
            display: none;
        }
        
        .banner-img {
            max-width: 100%;
            height: auto;
            margin-bottom: 15px;
        }
        
        /* RTL Margin and Padding Fixes */
        .ms-auto {
            margin-right: auto !important;
            margin-left: 0 !important;
        }
        
        .me-auto {
            margin-left: auto !important;
            margin-right: 0 !important;
        }
        
        .me-1, .me-2, .me-3 {
            margin-left: 0.25rem !important;
            margin-right: 0 !important;
        }
        
        .ms-1, .ms-2, .ms-3 {
            margin-right: 0.25rem !important;
            margin-left: 0 !important;
        }
        
        .pe-1, .pe-2, .pe-3 {
            padding-left: 0.25rem !important;
            padding-right: 0 !important;
        }
        
        .ps-1, .ps-2, .ps-3 {
            padding-right: 0.25rem !important;
            padding-left: 0 !important;
        }
        
        .border-end-0 {
            border-left: 0 !important;
            border-right: 1px solid #ced4da !important;
        }
        
        .border-start-0 {
            border-right: 0 !important;
            border-left: 1px solid #ced4da !important;
        }
        
        .input-group-text {
            border-radius: 0 8px 8px 0 !important;
        }
        
        .form-control {
            border-radius: 8px 0 0 8px !important;
        }
        
        .input-group {
            flex-direction: row-reverse;
        }
        
        .btn-group {
            flex-direction: row-reverse;
        }
        
        .d-flex {
            flex-direction: row;
        }
        
        .d-flex.align-items-center i {
            margin-left: 0.5rem !important;
            margin-right: 0 !important;
        }
        
        .fa-arrow-right {
            transform: scaleX(-1);
        }
        
        /* Filter Summary Card */
        .filter-summary-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 1px solid #dee2e6;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .filter-summary-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f59e0b;
            flex-direction: row-reverse;
        }
        
        .filter-summary-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #f59e0b, #d97706);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.3rem;
            margin-left: 15px !important;
            margin-right: 0 !important;
        }
        
        .filter-summary-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: #1f2937;
            margin: 0;
        }
        
        .filter-summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .filter-item {
            background: white;
            padding: 12px;
            border-radius: 10px;
            border: 1px solid #e5e7eb;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .filter-item-label {
            font-size: 0.85rem;
            color: #6b7280;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .filter-item-label i {
            margin-left: 0.5rem !important;
            margin-right: 0 !important;
        }
        
        .filter-item-value {
            font-size: 1rem;
            font-weight: 600;
            color: #1f2937;
            word-break: break-word;
        }
        
        /* Stats Cards */
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #e5e7eb;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px -1px rgba(0, 0, 0, 0.15);
        }
        
        .stats-card .number {
            font-size: 2.2rem;
            font-weight: 800;
            margin-bottom: 8px;
            line-height: 1;
        }
        
        .stats-card .label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 0;
        }
        
        .stats-card-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 1.5rem;
        }
        
        .stats-card-icon.orange {
            background: linear-gradient(135deg, #fed7aa, #fdba74);
            color: #f97316;
        }
        
        .stats-card-icon.yellow {
            background: linear-gradient(135deg, #fde68a, #fcd34d);
            color: #f59e0b;
        }
        
        .stats-card-icon.green {
            background: linear-gradient(135deg, #a7f3d0, #6ee7b7);
            color: #10b981;
        }
        
        .stats-card-icon.red {
            background: linear-gradient(135deg, #fecaca, #fca5a5);
            color: #ef4444;
        }
        
        /* Export Options */
        .export-options {
            background: white;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #e5e7eb;
            margin-bottom: 20px;
        }
        
        .export-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            flex-direction: row-reverse;
        }
        
        .export-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            margin-left: 15px !important;
            margin-right: 0 !important;
            font-size: 1.1rem;
        }
        
        .export-title {
            font-size: 1rem;
            font-weight: 600;
            color: #1f2937;
            margin: 0;
        }
        
        .export-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: flex-start;
        }
        
        .btn-export {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            border: none;
        }
        
        .btn-export i {
            margin-left: 0.5rem !important;
            margin-right: 0 !important;
        }
        
        .btn-export-excel {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
        }
        
        .btn-export-excel:hover {
            background: linear-gradient(135deg, #059669, #047857);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        }
        
        .btn-export-pdf {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }
        
        .btn-export-pdf:hover {
            background: linear-gradient(135deg, #dc2626, #b91c1c);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }
        
        @media (max-width: 768px) {
            .filter-summary-grid {
                grid-template-columns: 1fr;
            }
            
            .export-buttons {
                flex-direction: column;
            }
            
            .btn-export {
                width: 100%;
            }
        }
        
        /* Print styles */
        @media print {
            body { 
                font-size: 12px !important; 
                direction: rtl;
                padding: 0;
                margin: 0;
            }
            
            .no-print { 
                display: none !important; 
            }
            
            .print-only { 
                display: block !important; 
            }
            
            .print-header {
                text-align: center;
                margin-bottom: 20px;
                padding-bottom: 15px;
            }
            
            .print-header h2 {
                font-size: 18px;
                margin: 10px 0;
                font-weight: bold;
            }
            
            .print-info {
                font-size: 11px;
                color: #666;
                margin-bottom: 10px;
            }
            
            .print-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 10px;
                direction: rtl;
            }
            
            .print-table th {
                background-color: #f0f0f0 !important;
                border: 1px solid #000 !important;
                padding: 6px 4px !important;
                font-weight: bold !important;
                text-align: right !important;
            }
            
            .print-table td {
                border: 1px solid #000 !important;
                padding: 5px 4px !important;
                text-align: right !important;
            }
            
            .print-total {
                font-weight: bold !important;
                background-color: #f8f9fa !important;
                border-top: 2px solid #000 !important;
            }
            
            .print-footer {
                margin-top: 20px;
                padding-top: 10px;
                border-top: 1px solid #000;
                font-size: 10px;
                text-align: center;
                color: #666;
            }
            
            body > *:not(.print-container) {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <!-- Hidden Print Container -->
    <div class="print-container" id="printContainer">
        <div class="print-header">
            <img src="../img/banar3.jpg" alt="Banner" class="banner-img" onerror="this.style.display='none'">
            <h2>تقرير الطلاب القائمة الطلاب الذين لم يكملوا سداد الرسوم</h2>
            <div class="print-info">
                تاريخ التقرير: <?= date('Y-m-d H:i:s') ?><br>
                <?php if ($college_name): ?>الكلية: <?= htmlspecialchars($college_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                <?php if ($program_name): ?>البرنامج: <?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                <?php if ($specialization_name): ?>التخصص: <?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
                <?php if ($semester_name): ?>الفصل الدراسي: <?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?><br><?php endif; ?>
            </div>
        </div>
        
        <table class="print-table">
            <thead>
                <tr>
                    <th width="5%">#</th>
                    <th width="15%">رقم الطالب</th>
                    <th width="40%">اسم الطالب</th>
                    <th width="15%">الدفعة</th>
                    <th width="15%">المدفوع</th>
                    <th width="10%">نسبة الدفع</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($students)): ?>
                    <tr>
                        <td colspan="6" class="text-center">
                            لا توجد بيانات للعرض
                        </td>
                    </tr>
                <?php else: ?>
                    <?php 
                    $printTotalPaid = 0;
                    $printTotalUnpaid = 0;
                    $printTotalStudents = 0;
                    ?>
                    <?php foreach ($students as $index => $student): ?>
                        <?php
                        $printTotalPaid += $student['total_paid_amount'];
                        $printTotalUnpaid += $student['total_unpaid_amount'];
                        $printTotalStudents++;
                        ?>
                        <tr>
                            <td><?= $index + 1 ?></td>
                            <td><?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($student['student_name'] ?: $student['student_name_eng'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($student['batch_name'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= number_format($student['total_paid_amount'] ?? 0, 0) ?> / <?= number_format($student['total_fees'] ?? 0, 0) ?></td>
                            <td><?= number_format($student['payment_percentage'] ?? 0, 1) ?>%</td>
                        </tr>
                    <?php endforeach; ?>
                    
                    <tr class="print-total">
                        <td colspan="3" class="text-end">
                            إجمالي الطلاب: <?= number_format($printTotalStudents) ?>
                        </td>
                        <td class="text-end">المدفوع:</td>
                        <td><?= number_format($printTotalPaid, 0) ?></td>
                        <td>المتبقي: <?= number_format($printTotalUnpaid, 0) ?></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
        
        <div class="print-footer">
            تم إنشاء التقرير تلقائياً من نظام إدارة القبول والتسجيل<br>
            الصفحة 1 من 1
        </div>
    </div>
    
    <div class="container py-4">
        <!-- Header - Removed dir="ltr" -->
        <div class="d-flex align-items-center mb-4 no-print">
            <h3 class="mb-0 fw-bold">تقرير الطلاب القائمة الطلاب الذين لم يكملوا سداد الرسوم</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="../committee_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?php if ($error_message): ?>
            <div class="warning-message no-print">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?= htmlspecialchars($error_message, ENT_QUOTES, 'UTF-8') ?>
            </div>
        <?php endif; ?>

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

        <!-- Filter Card -->
        <div class="card card-arabic p-4 mb-4 no-print">
            <div class="row align-items-center">
                <div class="col-md-12">
                    <div class="d-flex align-items-center mb-4">
                        <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">
                        <input type="hidden" name="filter_applied" value="1">
                        
                        <!-- College Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-university me-1"></i>
                                    الكلية
                                </label>
                                <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 
                                            if (!$canAll && $scopeCollege !== null && $college['id'] != $scopeCollege) {
                                                continue;
                                            }
                                            ?>
                                            <option value="<?= (int)$college['id'] ?>" <?= ($filter_college_id == $college['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </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-2 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 position-relative">
                                    <select class="form-control border-end-0" name="filter_section" id="filter_section" onchange="loadSpecializations()" <?= !$filter_college_id ? 'disabled' : '' ?>>
                                        <option value="">جميع الأقسام</option>
                                        <?php if ($filter_college_id && !empty($sections)): ?>
                                            <?php foreach ($sections as $section): ?>
                                                <option value="<?= (int)$section['id'] ?>" <?= ($filter_section_id == $section['id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($section['name'], ENT_QUOTES, 'UTF-8') ?>
                                                </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-2 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" onchange="loadSpecializations()">
                                        <option value="">جميع البرامج</option>
                                        <?php foreach ($programs as $program): ?>
                                            <option value="<?= (int)$program['id'] ?>" <?= ($filter_program_id == $program['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($program['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-book"></i>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Specialization Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-microscope me-1"></i>
                                    التخصص
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_specialization" id="filter_specialization" <?= (!$filter_section_id && !$filter_program_id) ? 'disabled' : '' ?>>
                                        <option value="">جميع التخصصات</option>
                                        <?php foreach ($specializations as $spec): ?>
                                            <option value="<?= (int)$spec['specialization_id'] ?>" <?= ($filter_specialization_id == $spec['specialization_id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($spec['specialization_name_ar'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-microscope"></i>
                                    </span>
                                </div>
                                <small class="text-muted spec-hint" id="specHint">
                                    <?php if (!$filter_section_id && !$filter_program_id): ?>
                                        الرجاء اختيار القسم أو البرنامج أولاً
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                        
                        <!-- Batch Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-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="<?= (int)$batch['id'] ?>" <?= ($filter_batch_id == $batch['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                            </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>
                        
                        <!-- Semester Filter -->
                        <div class="col-lg-2 col-md-6">
                            <div class="form-group">
                                <label class="form-label fw-semibold text-muted mb-2">
                                    <i class="fas fa-calendar-alt me-1"></i>
                                    الفصل الدراسي <span class="text-danger">*</span>
                                </label>
                                <div class="input-group input-group-sm">
                                    <select class="form-control border-end-0" name="filter_semester" required>
                                        <option value="">اختر الفصل الدراسي</option>
                                        <?php foreach ($semesters as $semester): ?>
                                            <option value="<?= (int)$semester['id'] ?>" <?= ($filter_semester_id == $semester['id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($semester['name'] . ' (' . $semester['code'] . ')', ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-calendar"></i>
                                    </span> 
                                </div>
                            </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="partially_registered.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-warning align-self-center px-3 py-2">
                                        <i class="fas fa-check me-1"></i>
                                        تم تطبيق التصفية
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Report Content -->
        <?php if ($filters_applied && !empty($filter_semester_id) && $filter_semester_id > 0): ?>
            <!-- Semester Warning -->
            <div class="semester-warning no-print">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>ملاحظة:</strong> يتم عرض الطلاب القائمة الطلاب الذين لم يكملوا سداد الرسوم في الفصل الدراسي: 
                <span class="fw-bold"><?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?></span>
                <span class="text-muted ms-2">(لديهم دفعيات مدفوعة وغير مدفوعة)</span>
            </div>
            
            <!-- Filter Summary Card -->
            <div class="filter-summary-card mb-4 no-print">
                <div class="filter-summary-header">
                    <div class="filter-summary-icon">
                        <i class="fas fa-chart-pie"></i>
                    </div>
                    <h5 class="filter-summary-title">ملخص التصفية المطبقة</h5>
                </div>
                
                <div class="filter-summary-grid">
                    <?php if ($filter_college_id && $filter_college_id > 0 && $college_name): ?>
                        <div class="filter-item">
                            <div class="filter-item-label">
                                <i class="fas fa-university text-primary"></i>
                                الكلية
                            </div>
                            <div class="filter-item-value"><?= htmlspecialchars($college_name, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($filter_section_id && $filter_section_id > 0 && $section_name): ?>
                        <div class="filter-item">
                            <div class="filter-item-label">
                                <i class="fas fa-layer-group text-success"></i>
                                القسم
                            </div>
                            <div class="filter-item-value"><?= htmlspecialchars($section_name, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($filter_program_id && $filter_program_id > 0 && $program_name): ?>
                        <div class="filter-item">
                            <div class="filter-item-label">
                                <i class="fas fa-graduation-cap text-warning"></i>
                                البرنامج
                            </div>
                            <div class="filter-item-value"><?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($filter_specialization_id && $filter_specialization_id > 0 && $specialization_name): ?>
                        <div class="filter-item">
                            <div class="filter-item-label">
                                <i class="fas fa-microscope text-info"></i>
                                التخصص
                            </div>
                            <div class="filter-item-value"><?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($filter_batch_id && $filter_batch_id > 0 && $batch_name): ?>
                        <div class="filter-item">
                            <div class="filter-item-label">
                                <i class="fas fa-users text-info"></i>
                                الدفعة
                            </div>
                            <div class="filter-item-value"><?= htmlspecialchars($batch_name, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($filter_semester_id && $filter_semester_id > 0 && $semester_name): ?>
                        <div class="filter-item">
                            <div class="filter-item-label">
                                <i class="fas fa-calendar-alt text-danger"></i>
                                الفصل الدراسي
                            </div>
                            <div class="filter-item-value"><?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <div class="filter-item">
                        <div class="filter-item-label">
                            <i class="fas fa-users text-warning"></i>
                            عدد الطلاب الجزئيين
                        </div>
                        <div class="filter-item-value">
                            <span class="badge bg-warning fs-6"><?= number_format($totalStudents) ?></span>
                        </div>
                    </div>
                    
                    <div class="filter-item">
                        <div class="filter-item-label">
                            <i class="fas fa-percentage text-warning"></i>
                            متوسط نسبة الدفع
                        </div>
                        <div class="filter-item-value">
                            <span class="fw-bold text-warning"><?= number_format($avgPaymentPercentage, 1) ?>%</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Export Options -->
            <div class="export-options mb-4 no-print">
                <div class="export-header">
                    <div class="export-icon">
                        <i class="fas fa-download"></i>
                    </div>
                    <h5 class="export-title">خيارات التصدير والطباعة</h5>
                </div>
                
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <div class="text-muted mb-3 mb-md-0">
                            <i class="fas fa-info-circle me-2"></i>
                            <span>تاريخ التقرير: <?= date('Y-m-d H:i:s') ?></span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="export-buttons justify-content-md-end">
                            <button class="btn btn-export btn-export-excel" onclick="exportToExcel()">
                                <i class="fas fa-file-excel"></i>
                                تصدير لإكسل
                            </button>
                            <button class="btn btn-export btn-export-pdf" onclick="printReportPDF()">
                                <i class="fas fa-print"></i>
                                طباعة PDF
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Students Table -->
            <div class="card card-arabic p-4">
                <div class="d-flex align-items-center mb-3">
                    <div class="filter-icon me-2">
                        <i class="fas fa-users"></i>
                    </div>
                    <h6 class="fw-bold mb-0">
                        قائمة الطلاب القائمة الطلاب الذين لم يكملوا سداد الرسوم
                        <?php if ($program_name): ?>
                            <span class="chip warning ms-2">
                                <i class="fas fa-graduation-cap me-1"></i>
                                <?= htmlspecialchars($program_name, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <?php if ($specialization_name): ?>
                            <span class="chip specialization ms-2">
                                <i class="fas fa-microscope me-1"></i>
                                <?= htmlspecialchars($specialization_name, ENT_QUOTES, 'UTF-8') ?>
                            </span>
                        <?php endif; ?>
                        <span class="chip warning ms-2">
                            <i class="fas fa-calendar-alt me-1"></i>
                            <?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?>
                        </span>
                    </h6>
                    <div class="ms-auto">
                        <span class="badge bg-warning fs-6">
                            <i class="fas fa-users me-1"></i>
                            <?= number_format($totalStudents) ?> طالب
                        </span>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped student-table" id="studentsTable">
                        <thead>
                            <tr>
                                <th width="5%">#</th>
                                <th width="12%">رقم الطالب</th>
                                <th width="20%">اسم الطالب</th>
                                <th width="10%">الكلية</th>
                                <th width="8%">البرنامج</th>
                                <th width="10%">التخصص</th>
                                <th width="8%">الدفعة</th>
                                <th width="12%">حالة الدفع</th>
                                <th width="15%">نسبة الدفع</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($students)): ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted py-4">
                                        <div class="py-5">
                                            <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                                            <h5 class="text-success">لا توجد بيانات</h5>
                                            <p class="text-muted">لا يوجد طلاب قائمة الطلاب الذين لم يكملوا سداد الرسوم في الفصل الدراسي: <?= htmlspecialchars($semester_name, ENT_QUOTES, 'UTF-8') ?></p>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php 
                                $tablePaidAmount = 0;
                                $tableUnpaidAmount = 0;
                                ?>
                                <?php foreach ($students as $index => $student): ?>
                                    <?php
                                    $tablePaidAmount += $student['total_paid_amount'];
                                    $tableUnpaidAmount += $student['total_unpaid_amount'];
                                    
                                    $paymentPercentage = $student['payment_percentage'] ?? 0;
                                    $progressClass = '';
                                    if ($paymentPercentage >= 70) {
                                        $progressClass = 'progress-high';
                                    } elseif ($paymentPercentage >= 40) {
                                        $progressClass = 'progress-medium';
                                    } else {
                                        $progressClass = 'progress-low';
                                    }
                                    ?>
                                    <tr>
                                        <td class="fw-bold"><?= $index + 1 ?></td>
                                        <td><code><?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                        <td><?= htmlspecialchars($student['student_name'] ?: $student['student_name_eng'], ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= htmlspecialchars($student['college_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                        <td>
                                            <span class="chip info">
                                                <i class="fas fa-graduation-cap me-1"></i>
                                                <?= htmlspecialchars($student['program_name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if (!empty($student['specialization_name'])): ?>
                                                <span class="chip specialization">
                                                    <i class="fas fa-microscope me-1"></i>
                                                    <?= htmlspecialchars($student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary">
                                                <?= htmlspecialchars($student['batch_name'], ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="small">
                                                <div class="d-flex justify-content-between">
                                                    <span class="text-success fw-bold">
                                                        <i class="fas fa-check-circle me-1"></i>
                                                        <?= number_format($student['paid_count']) ?>
                                                    </span>
                                                    <span class="text-danger fw-bold">
                                                        <i class="fas fa-times-circle me-1"></i>
                                                        <?= number_format($student['unpaid_count']) ?>
                                                    </span>
                                                </div>
                                                <div class="mt-1">
                                                    <span class="text-success">
                                                        <?= number_format($student['total_paid_amount'] ?? 0, 0) ?> 
                                                    </span>
                                                    <span class="text-muted">/</span>
                                                    <span class="text-danger">
                                                        <?= number_format($student['total_unpaid_amount'] ?? 0, 0) ?> 
                                                    </span>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="me-2 fw-bold <?= $paymentPercentage >= 70 ? 'text-success' : ($paymentPercentage >= 40 ? 'text-warning' : 'text-danger') ?>">
                                                    <?= number_format($paymentPercentage, 1) ?>%
                                                </div>
                                                <div class="payment-progress flex-grow-1">
                                                    <div class="payment-progress-bar <?= $progressClass ?>" 
                                                         style="width: <?= min($paymentPercentage, 100) ?>%"></div>
                                                </div>
                                            </div>
                                            <div class="small text-muted mt-1">
                                                <i class="fas fa-money-bill-wave me-1"></i>
                                                <?= number_format($student['total_paid_amount'] ?? 0, 0) ?>  من <?= number_format($student['total_fees'] ?? 0, 0) ?> 
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                
                                <tr class="total-row">
                                    <td colspan="7" class="fw-bold">
                                        <i class="fas fa-calculator me-2"></i>الإجمالي:
                                    </td>
                                    <td>
                                        <div class="d-flex justify-content-between">
                                            <span class="text-success fw-bold">
                                                <?= number_format($tablePaidAmount, 0) ?> 
                                            </span>
                                            <span class="text-danger fw-bold">
                                                <?= number_format($tableUnpaidAmount, 0) ?> 
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-warning">
                                            <?= $tablePaidAmount + $tableUnpaidAmount > 0 ? number_format(($tablePaidAmount / ($tablePaidAmount + $tableUnpaidAmount)) * 100, 1) : 0 ?>%
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function loadSections(collegeId) {
            const sectionSelect = document.getElementById('filter_section');
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            sectionSelect.innerHTML = '<option value="">جميع الأقسام</option>';
            sectionSelect.disabled = true;
            
            specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
            specSelect.disabled = true;
            if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم أو البرنامج أولاً';
            
            if (!collegeId || collegeId === '') {
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'get';
            form.style.display = 'none';
            
            const collegeInput = document.createElement('input');
            collegeInput.type = 'hidden';
            collegeInput.name = 'filter_college';
            collegeInput.value = collegeId;
            form.appendChild(collegeInput);
            
            const appliedInput = document.createElement('input');
            appliedInput.type = 'hidden';
            appliedInput.name = 'filter_applied';
            appliedInput.value = '1';
            form.appendChild(appliedInput);
            
            const currentSection = "<?= $filter_section_id ?>";
            if (currentSection) {
                const sectionInput = document.createElement('input');
                sectionInput.type = 'hidden';
                sectionInput.name = 'filter_section';
                sectionInput.value = currentSection;
                form.appendChild(sectionInput);
            }
            
            const currentProgram = "<?= $filter_program_id ?>";
            if (currentProgram) {
                const programInput = document.createElement('input');
                programInput.type = 'hidden';
                programInput.name = 'filter_program';
                programInput.value = currentProgram;
                form.appendChild(programInput);
            }
            
            const currentSpecialization = "<?= $filter_specialization_id ?>";
            if (currentSpecialization) {
                const specInput = document.createElement('input');
                specInput.type = 'hidden';
                specInput.name = 'filter_specialization';
                specInput.value = currentSpecialization;
                form.appendChild(specInput);
            }
            
            const currentBatch = "<?= $filter_batch_id ?>";
            if (currentBatch) {
                const batchInput = document.createElement('input');
                batchInput.type = 'hidden';
                batchInput.name = 'filter_batch';
                batchInput.value = currentBatch;
                form.appendChild(batchInput);
            }
            
            const currentSemester = "<?= $filter_semester_id ?>";
            if (currentSemester) {
                const semesterInput = document.createElement('input');
                semesterInput.type = 'hidden';
                semesterInput.name = 'filter_semester';
                semesterInput.value = currentSemester;
                form.appendChild(semesterInput);
            }
            
            document.body.appendChild(form);
            form.submit();
        }
        
        function loadSpecializations() {
            const sectionId = document.getElementById('filter_section').value;
            const programId = document.getElementById('filter_program').value;
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            if (!sectionId && !programId) {
                specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                specSelect.disabled = true;
                if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم أو البرنامج أولاً';
                return;
            }
            
            specSelect.innerHTML = '<option value="">جاري التحميل...</option>';
            specSelect.disabled = false;
            if (specHint) specHint.innerHTML = 'جاري تحميل التخصصات...';
            
            let url = '../ajax/get_specializations.php?';
            if (sectionId) url += `section_id=${encodeURIComponent(sectionId)}&`;
            if (programId) url += `program_id=${encodeURIComponent(programId)}&`;
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    
                    if (data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            const urlParams = new URLSearchParams(window.location.search);
                            const selectedSpec = urlParams.get('filter_specialization');
                            if (selectedSpec && selectedSpec == spec.specialization_id) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                        if (specHint) specHint.innerHTML = `${data.length} تخصص متاح`;
                    } else {
                        if (specHint) specHint.innerHTML = 'لا توجد تخصصات متاحة';
                    }
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">جميع التخصصات</option>';
                    if (specHint) specHint.innerHTML = 'حدث خطأ في تحميل التخصصات';
                });
        }
        
        function exportToExcel() {
            if (!<?= $filters_applied ? 'true' : 'false' ?> || !<?= !empty($filter_semester_id) ? 'true' : 'false' ?>) {
                alert('الرجاء تطبيق التصفية أولاً مع اختيار فصل دراسي لعرض الطلاب');
                return;
            }
            
            if (<?= count($students) ?> === 0) {
                alert('لا توجد بيانات للتصدير');
                return;
            }
            
            const table = document.getElementById('studentsTable');
            
            if (!table) {
                alert('لا توجد بيانات للتصدير');
                return;
            }
            
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.table_to_sheet(table);
            
            const wscols = [
                {wch: 5},
                {wch: 15},
                {wch: 30},
                {wch: 20},
                {wch: 15},
                {wch: 15},
                {wch: 10},
                {wch: 25},
                {wch: 15},
            ];
            ws['!cols'] = wscols;
            
            XLSX.utils.book_append_sheet(wb, ws, "الطلاب الجزئيين");
            
            let filename = "الطلاب_المسجلين_جزئياً";
            
            <?php if ($college_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $college_name) ?>";
            <?php endif; ?>
            
            <?php if ($program_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $program_name) ?>";
            <?php endif; ?>
            
            <?php if ($specialization_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $specialization_name) ?>";
            <?php endif; ?>
            
            <?php if ($semester_name): ?>
                filename += "_<?= preg_replace('/[^\p{L}\p{N}\s]/u', '', $semester_name) ?>";
            <?php endif; ?>
            
            filename += "_<?= date('Y-m-d') ?>.xlsx";
            
            filename = filename.replace(/[/\\?%*:|"<>]/g, '_');
            
            XLSX.writeFile(wb, filename);
        }
        
        function printReportPDF() {
            if (!<?= $filters_applied ? 'true' : 'false' ?> || !<?= !empty($filter_semester_id) ? 'true' : 'false' ?>) {
                alert('الرجاء تطبيق التصفية أولاً مع اختيار فصل دراسي لعرض الطلاب');
                return;
            }
            
            if (<?= count($students) ?> === 0) {
                alert('لا توجد بيانات للطباعة');
                return;
            }
            
            const printContainer = document.getElementById('printContainer').outerHTML;
            
            const printWindow = window.open('', '_blank', 'width=800,height=600');
            
            const printContent = `
                <!DOCTYPE html>
                <html dir="rtl">
                <head>
                    <meta charset="UTF-8">
                    <title>تقرير الطلاب القائمة الطلاب الذين لم يكملوا سداد الرسوم</title>
                    <style>
                        @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap');
                        
                        * {
                            font-family: 'Cairo', sans-serif !important;
                            box-sizing: border-box;
                        }
                        
                        body {
                            margin: 0;
                            padding: 15mm;
                            direction: rtl;
                            background: white;
                            font-size: 12px;
                        }
                        
                        .print-header {
                            text-align: center;
                            margin-bottom: 20px;
                            padding-bottom: 10px;
                        }
                        
                        .banner-img {
                            max-width: 100%;
                            height: auto;
                            margin-bottom: 15px;
                        }
                        
                        .print-header h2 {
                            font-size: 20px;
                            margin: 5px 0;
                            font-weight: bold;
                            color: #000;
                        }
                        
                        .print-info {
                            font-size: 11px;
                            color: #666;
                            margin-top: 10px;
                            line-height: 1.6;
                        }
                        
                        .print-table {
                            width: 100%;
                            border-collapse: collapse;
                            font-size: 10px;
                            margin-top: 15px;
                        }
                        
                        .print-table th {
                            background-color: #f0f0f0;
                            border: 1px solid #000;
                            padding: 8px 5px;
                            font-weight: bold;
                            text-align: right;
                            font-size: 11px;
                        }
                        
                        .print-table td {
                            border: 1px solid #000;
                            padding: 6px 5px;
                            text-align: right;
                        }
                        
                        .print-total {
                            font-weight: bold;
                            background-color: #f8f9fa;
                            border-top: 2px solid #000;
                        }
                        
                        .print-total td {
                            padding: 8px 5px;
                        }
                        
                        .print-footer {
                            margin-top: 20px;
                            padding-top: 10px;
                            border-top: 1px solid #666;
                            font-size: 10px;
                            text-align: center;
                            color: #666;
                            line-height: 1.6;
                        }
                        
                        @media print {
                            @page {
                                size: A4 portrait;
                                margin: 15mm;
                            }
                            
                            body { 
                                margin: 0;
                                padding: 0;
                            }
                            
                            .print-table {
                                font-size: 9px;
                            }
                            
                            .print-table th, 
                            .print-table td {
                                padding: 5px 3px;
                            }
                        }
                    </style>
                </head>
                <body>
                    ${printContainer}
                </body>
                </html>
            `;
            
            printWindow.document.write(printContent);
            printWindow.document.close();
            
            printWindow.onload = function() {
                printWindow.focus();
                setTimeout(function() {
                    printWindow.print();
                }, 500);
            };
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            const collegeSelect = document.getElementById('filter_college');
            const sectionSelect = document.getElementById('filter_section');
            const specSelect = document.getElementById('filter_specialization');
            const specHint = document.getElementById('specHint');
            
            if (collegeSelect && sectionSelect) {
                if (!collegeSelect.value) {
                    sectionSelect.disabled = true;
                    if (specSelect) specSelect.disabled = true;
                    if (specHint) specHint.innerHTML = 'الرجاء اختيار القسم أو البرنامج أولاً';
                } else {
                    sectionSelect.disabled = false;
                }
            }
            
            const sectionId = document.getElementById('filter_section')?.value;
            const programId = document.getElementById('filter_program')?.value;
            
            if ((sectionId || programId) && specSelect && specHint) {
                specSelect.disabled = false;
                
                const specCount = <?= count($specializations) ?>;
                if (specCount > 0) {
                    specHint.innerHTML = `${specCount} تخصص متاح`;
                } else if (sectionId || programId) {
                    specHint.innerHTML = 'لا توجد تخصصات متاحة';
                }
            }
            
            // Fix arrow icons
            document.querySelectorAll('.fa-arrow-right').forEach(function(icon) {
                icon.style.transform = 'scaleX(-1)';
            });
            
            // Fix icon margins
            document.querySelectorAll('.btn i, .chip i, .filter-item-label i, .fa-check-circle, .fa-times-circle').forEach(function(icon) {
                if (!icon.classList.contains('fa-arrow-right')) {
                    icon.style.marginLeft = '0.5rem';
                    icon.style.marginRight = '0';
                }
            });
        });
    </script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</body>
</html>
