<?php
// registration.php - UPDATED WITH DUPLICATE PREVENTION AND LAST REGISTRATION CARDS
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

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

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

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

// Get filter parameters
$filter_section_id = $_GET['filter_section'] ?? null;
$filter_program_id = $_GET['filter_program'] ?? null;
$filter_batch_id = $_GET['filter_batch'] ?? null;
$filter_college_id = $_GET['filter_college'] ?? null;

// Build WHERE clause for filtering students - NO CONSTRAINTS, ONLY FILTERS
$where = " WHERE 1=1 ";
$types = ''; 
$params = [];

// Apply scope restrictions only (no profile or interview constraints)
if (!$canAll && $scopeCollege !== null) {
    $where .= " AND s.college_id = ? ";
    $types .= 'i'; 
    $params[] = $scopeCollege;
} elseif (!$canAll && $scopeCollege === null) {
    $where .= " AND 1=0 ";
}

// Apply filters
if ($filter_college_id && !empty($filter_college_id) && $canAll) {
    $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;
}

// Function to generate unique payment reference - UPDATED WITH YEAR PREFIX
function generateUniquePaymentReference($mysqli) {
    $unique = false;
    $max_attempts = 10;
    $attempts = 0;
    
    while (!$unique && $attempts < $max_attempts) {
        // Generate random 12-digit number (year prefix + random part)
        $year_prefix = date('y'); // Gets last 2 digits of current year (25 for 2025, 26 for 2026, etc.)
        $random_part = str_pad(mt_rand(1, 9999999999), 10, '0', STR_PAD_LEFT);
        $reference = $year_prefix . $random_part;
        
        // Check if reference already exists
        $check_stmt = $mysqli->prepare("SELECT id FROM registrations WHERE payment_reference = ?");
        $check_stmt->bind_param("s", $reference);
        $check_stmt->execute();
        $existing = $check_stmt->get_result()->fetch_assoc();
        $check_stmt->close();
        
        if (!$existing) {
            $unique = true;
            return $reference;
        }
        
        $attempts++;
    }
    
    // If we can't generate a unique reference after max attempts, use timestamp-based
    return date('ymd') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
}

// Function to check for existing registrations with same filters
function checkExistingRegistrations($mysqli, $filters) {
    $where_conditions = [];
    $types = '';
    $params = [];
    
    if (!empty($filters['college_id'])) {
        $where_conditions[] = "rc.college_id = ?";
        $types .= 'i';
        $params[] = $filters['college_id'];
    }
    
    if (!empty($filters['section_id'])) {
        $where_conditions[] = "rc.section_id = ?";
        $types .= 'i';
        $params[] = $filters['section_id'];
    }
    
    if (!empty($filters['program_id'])) {
        $where_conditions[] = "rc.program_id = ?";
        $types .= 'i';
        $params[] = $filters['program_id'];
    }
    
    if (!empty($filters['batch_id'])) {
        $where_conditions[] = "rc.batch_id = ?";
        $types .= 'i';
        $params[] = $filters['batch_id'];
    }
    
    if (empty($where_conditions)) {
        return []; // No filters provided
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    
    $sql = "
        SELECT 
            r.id, r.student_id, r.student_name, r.payment_reference,
            r.semester_id, r.study_fees, r.registration_fees, r.insurance_fees,
            r.payment_amount, r.due_amount, r.is_paid, r.start, r.end,
            r.created_at, r.updated_at,
            s.name as semester_name,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            b.value as batch_name
        FROM registrations r
        INNER JOIN registration_constraints rc ON r.id = rc.registration_id
        INNER JOIN semesters s ON r.semester_id = s.id
        LEFT JOIN colleges c ON rc.college_id = c.id
        LEFT JOIN sections sec ON rc.section_id = sec.id
        LEFT JOIN programs p ON rc.program_id = p.id
        LEFT JOIN batches b ON rc.batch_id = b.id
        WHERE {$where_clause}
        AND r.deleted_at IS NULL
        ORDER BY r.created_at DESC
        LIMIT 3000
    ";
    
    $stmt = $mysqli->prepare($sql);
    if ($types) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    
    return $result;
}

// Get last registrations based on current filters
$current_filters = [
    'college_id' => $filter_college_id,
    'section_id' => $filter_section_id,
    'program_id' => $filter_program_id,
    'batch_id' => $filter_batch_id
];

$last_registrations = checkExistingRegistrations($mysqli1, $current_filters);

// Handle form submission for registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_students'])) {
    $semester_id = (int)($_POST['semester_id'] ?? 0);
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $student_ids = $_POST['student_ids'] ?? [];
    
    // Validate dates
    if (empty($semester_id)) {
        $error_message = 'يرجى اختيار فصل دراسي';
    } elseif (empty($start_date)) {
        $error_message = 'يرجى تحديد تاريخ بداية التسجيل';
    } elseif (empty($end_date)) {
        $error_message = 'يرجى تحديد تاريخ نهاية التسجيل';
    } elseif (empty($student_ids)) {
        $error_message = 'لم يتم اختيار أي طلاب للتسجيل';
    } else {
        // Convert dates to MySQL format
        $start_timestamp = date('Y-m-d H:i:s', strtotime($start_date));
        $end_timestamp = date('Y-m-d H:i:s', strtotime($end_date));
        
        // Validate that end date is after start date
        if (strtotime($end_date) <= strtotime($start_date)) {
            $error_message = 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية';
        } else {
            try {
                // Begin transaction
                $mysqli1->begin_transaction();
                
                // Get semester details
                $semester_stmt = $mysqli1->prepare("SELECT * FROM semesters WHERE id = ?");
                $semester_stmt->bind_param("i", $semester_id);
                $semester_stmt->execute();
                $semester = $semester_stmt->get_result()->fetch_assoc();
                $semester_stmt->close();
                
                if (!$semester) {
                    throw new Exception('الفصل الدراسي المحدد غير موجود');
                }
                
                $registration_count = 0;
                $duplicate_count = 0;
                
                foreach ($student_ids as $student_id) {
                    // Check if student already registered for this semester
                    $check_stmt = $mysqli1->prepare("
                        SELECT id FROM registrations 
                        WHERE student_id = ? AND semester_id = ? AND deleted_at IS NULL
                    ");
                    $check_stmt->bind_param("si", $student_id, $semester_id);
                    $check_stmt->execute();
                    $existing_registration = $check_stmt->get_result()->fetch_assoc();
                    $check_stmt->close();
                    
                    if ($existing_registration) {
                        $duplicate_count++;
                        continue; // Skip if already registered
                    }
                    
                    // Get student details with fees
                    $student_stmt = $mysqli1->prepare("
                        SELECT student_id, student_name, college_id, section_id, program_id, 
                               program_fees, registration_fees, insurance_fees 
                        FROM students 
                        WHERE student_id = ?
                    ");
                    $student_stmt->bind_param("s", $student_id);
                    $student_stmt->execute();
                    $student = $student_stmt->get_result()->fetch_assoc();
                    $student_stmt->close();

                    if (!$student) {
                        continue; // Skip if student not found
                    }

                    // Generate unique payment reference
                    $payment_reference = generateUniquePaymentReference($mysqli1);

                    // Get fees from student record, ensure they are not empty and set to 0 if null/empty
                    // program_fees from students table becomes study_fees in registrations table
                    $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;

                    // Insert into registrations table with dates and payment reference
                    $insert_stmt = $mysqli1->prepare("
                        INSERT INTO registrations (
                            student_id, student_name, payment_reference, semester_id, 
                            study_fees, registration_fees, insurance_fees, payment_amount, 
                            due_amount, is_paid, fee_type_id, user_id, start, end, created_at, updated_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                    ");
                    
                    $is_paid = 0; // Not paid initially
                    $fee_type_id = 1; // Default fee type
                    $due_amount = $total_fees;
                    
                    $insert_stmt->bind_param(
                        "sssiddddiiiiss", 
                        $student['student_id'],
                        $student['student_name'],
                        $payment_reference,
                        $semester_id,
                        $study_fees,
                        $registration_fees,
                        $insurance_fees,
                        $total_fees,
                        $due_amount,
                        $is_paid,
                        $fee_type_id,
                        $committeeId,
                        $start_timestamp,
                        $end_timestamp
                    );
                    
                    $insert_stmt->execute();
                    $registration_id = $insert_stmt->insert_id;
                    $insert_stmt->close();
                    
                    // Check if registration_constraints table exists and has the correct structure
                    $table_check = $mysqli1->query("
                        SHOW COLUMNS FROM registration_constraints LIKE 'registration_id'
                    ");
                    
                    if ($table_check->num_rows > 0) {
                        // Table exists with registration_id column
                        $constraint_stmt = $mysqli1->prepare("
                            INSERT INTO registration_constraints (
                                registration_id, student_id, semester_id, college_id, 
                                section_id, program_id, batch_id, created_at, updated_at
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        
                        // Get batch_id from student
                        $batch_stmt = $mysqli1->prepare("SELECT batch_id FROM students WHERE student_id = ?");
                        $batch_stmt->bind_param("s", $student_id);
                        $batch_stmt->execute();
                        $batch_result = $batch_stmt->get_result()->fetch_assoc();
                        $batch_id = $batch_result['batch_id'] ?? null;
                        $batch_stmt->close();
                        
                        $constraint_stmt->bind_param(
                            "isiisii",
                            $registration_id,
                            $student['student_id'],
                            $semester_id,
                            $student['college_id'],
                            $student['section_id'],
                            $student['program_id'],
                            $batch_id
                        );
                        
                        $constraint_stmt->execute();
                        $constraint_stmt->close();
                    } else {
                        // Table doesn't exist or doesn't have registration_id column
                        // Let's create the table if it doesn't exist
                        $create_table_sql = "
                            CREATE TABLE IF NOT EXISTS registration_constraints (
                                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                                registration_id BIGINT UNSIGNED NOT NULL,
                                student_id VARCHAR(50) NOT NULL,
                                semester_id INT NOT NULL,
                                college_id INT,
                                section_id INT,
                                program_id INT,
                                batch_id INT,
                                created_at TIMESTAMP NULL DEFAULT NULL,
                                updated_at TIMESTAMP NULL DEFAULT NULL,
                                INDEX idx_registration_id (registration_id),
                                INDEX idx_student_id (student_id),
                                INDEX idx_semester_id (semester_id)
                            )
                        ";
                        $mysqli1->query($create_table_sql);
                        
                        // Now insert the constraint record
                        $constraint_stmt = $mysqli1->prepare("
                            INSERT INTO registration_constraints (
                                registration_id, student_id, semester_id, college_id, 
                                section_id, program_id, batch_id, created_at, updated_at
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        
                        // Get batch_id from student
                        $batch_stmt = $mysqli1->prepare("SELECT batch_id FROM students WHERE student_id = ?");
                        $batch_stmt->bind_param("s", $student_id);
                        $batch_stmt->execute();
                        $batch_result = $batch_stmt->get_result()->fetch_assoc();
                        $batch_id = $batch_result['batch_id'] ?? null;
                        $batch_stmt->close();
                        
                        $constraint_stmt->bind_param(
                            "isiisii",
                            $registration_id,
                            $student['student_id'],
                            $semester_id,
                            $student['college_id'],
                            $student['section_id'],
                            $student['program_id'],
                            $batch_id
                        );
                        
                        $constraint_stmt->execute();
                        $constraint_stmt->close();
                    }
                    
                    $registration_count++;
                }
                
                // Commit transaction
                $mysqli1->commit();
                
                $success_message = "تم تسجيل {$registration_count} طالب بنجاح في الفصل الدراسي المحدد";
                if ($duplicate_count > 0) {
                    $success_message .= " (تم تخطي {$duplicate_count} طالب لديهم تسجيلات سابقة في هذا الفصل)";
                }
                
            } catch (Exception $e) {
                // Rollback transaction on error
                $mysqli1->rollback();
                $error_message = "حدث خطأ أثناء التسجيل: " . $e->getMessage();
                
                // Log detailed error for debugging
                error_log("Registration Error: " . $e->getMessage());
                error_log("SQL Error: " . $mysqli1->error);
            }
        }
    }
}

// Get ALL filtered students WITHOUT ANY CONSTRAINTS
$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.profile_completed, s.interview_status, s.medically_fit,
        s.program_fees, s.registration_fees, s.insurance_fees,
        c.name AS college_name,
        sec.name AS section_name,
        p.name AS program_name,
        b.value AS batch_name,
        (SELECT COUNT(*) FROM registrations r WHERE r.student_id = s.student_id AND r.deleted_at IS NULL) as registration_count
    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 3000
";

$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 semesters for dropdown
$semesters_stmt = $mysqli1->prepare("SELECT id, name, code FROM semesters WHERE deleted_at IS NULL ORDER BY id DESC");
$semesters_stmt->execute();
$semesters = $semesters_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$semesters_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 based on selected college
if ($filter_college_id && !empty($filter_college_id)) {
    $sections_stmt = $mysqli1->prepare("
        SELECT DISTINCT s.id, s.name 
        FROM sections s 
        INNER JOIN students st ON s.id = st.section_id 
        WHERE st.college_id = ? AND s.deleted_at IS NULL 
        ORDER BY s.name
    ");
    $sections_stmt->bind_param("i", $filter_college_id);
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
} else {
    $sections_stmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
    $sections_stmt->execute();
    $sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $sections_stmt->close();
}

// Get programs based on selected college and section
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();

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;
        }
        .registration-count {
            font-size: 0.8rem;
        }
        .status-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .date-inputs {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
        }
        .fees-badge {
            font-size: 0.7rem;
            padding: 0.2rem 0.4rem;
        }
        .registration-card {
            border-left: 4px solid #3b82f6;
            transition: all 0.3s ease;
        }
        .registration-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .paid-badge {
            background-color: #10b981;
        }
        .unpaid-badge {
            background-color: #ef4444;
        }
        .warning-alert {
            border-right: 4px solid #f59e0b;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold">إدارة تسجيلات الطلاب</h3>
            <div class="ms-auto">
                <a class="btn btn-outline-secondary" href="committee_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <?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; ?>

        <!-- Last Registrations Warning -->
        <?php if (!empty($last_registrations)): ?>
     
        <?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>
                                عرض جميع الطلاب
                            </span>
                        </div>
                    </div>
                    
                    <form method="get" class="row g-3 align-items-end">
                        <!-- College Filter (only for users who can view all) -->
                        <?php if ($canAll): ?>
                        <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="this.form.submit()">
                                        <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>
                        <?php endif; ?>
                        
                        <!-- 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" onchange="this.form.submit()">
                                        <option value="">جميع الأقسام</option>
                                        <?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; ?>
                                    </select>
                                    <span class="input-group-text bg-light border-start-0">
                                        <i class="fas fa-building"></i>
                                    </span>
                                </div>
                            </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" onchange="this.form.submit()">
                                        <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>
                        
                        <!-- 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="registration.php" class="btn btn-outline-secondary btn-sm px-3">
                                    <i class="fas fa-sync-alt me-1"></i>
                                    إعادة تعيين
                                </a>
                            </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 text-primary"></i>
                            <span class="fw-semibold">ملخص التصفية</span>
                        </div>
                        <div class="small">
                            <div class="mb-1">عدد الطلاب: <strong><?= count($students) ?></strong></div>
                            
                            <!-- Last Semester with Enrollments -->
                            <?php
                            // Get last semester with enrollments based on current filters
                            $last_semester_sql = "
                                SELECT s.id, s.name, s.code, MAX(r.created_at) as last_registration
                                FROM semesters s
                                INNER JOIN registrations r ON s.id = r.semester_id
                                INNER JOIN students st ON r.student_id = st.student_id
                                WHERE r.deleted_at IS NULL
                                AND st.college_id " . ($filter_college_id ? "= " . intval($filter_college_id) : "IS NOT NULL")
                                . ($filter_section_id ? " AND st.section_id = " . intval($filter_section_id) : "")
                                . ($filter_program_id ? " AND st.program_id = " . intval($filter_program_id) : "")
                                . ($filter_batch_id ? " AND st.batch_id = " . intval($filter_batch_id) : "")
                                . " GROUP BY s.id, s.name, s.code
                                ORDER BY last_registration DESC
                                LIMIT 1
                            ";
                            
                            $last_semester_result = $mysqli1->query($last_semester_sql);
                            $last_semester = $last_semester_result->fetch_assoc();
                            $last_semester_result->close();
                            ?>
                            
                            <?php if ($last_semester): ?>
                            <div class="mb-2 p-2 bg-primary bg-opacity-10 rounded">
                                <div class="fw-semibold text-primary mb-1">
                                    <i class="fas fa-calendar-check me-1"></i>
                                    آخر فصل دراسي مسجل
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <span><?= e($last_semester['name']) ?> (<?= e($last_semester['code']) ?>)</span>
                                    <small class="text-muted">
                                        <?= date('Y-m-d', strtotime($last_semester['last_registration'])) ?>
                                    </small>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <div class="mb-1">شروط التصفية:</div>
                            <ul class="small mb-0 ps-3">
                                <li>جميع الطلاب</li>
                                <li>بغض النظر عن حالة الملف</li>
                                <li>بغض النظر عن حالة المقابلة</li>
                                <li>بغض النظر عن الحالة الطبية</li>
                                <?php if (!$canAll && $scopeCollege !== null): ?>
                                    <li>نطاق الكلية محدود</li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Registration Form -->
        <?php if (!empty($students)): ?>
        <div class="card card-arabic p-4 mb-4">
            <div class="d-flex align-items-center mb-3">
                <h6 class="fw-bold mb-0">تسجيل الطلاب في فصل دراسي</h6>
                <span class="badge bg-primary ms-2"><?= count($students) ?> طالب متاح</span>
                <?php if (!empty($last_registrations)): ?>
                    <span class="badge bg-warning ms-2">
                        <i class="fas fa-exclamation-triangle me-1"></i>
                        يوجد تسجيلات سابقة
                    </span>
                <?php endif; ?>
            </div>
            
            <form method="post" id="registrationForm">
                <!-- Semester and Dates Section -->
                <div class="date-inputs mb-4">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">اختر الفصل الدراسي:</label>
                            <select class="form-control" name="semester_id" required>
                                <option value="">-- اختر الفصل الدراسي --</option>
                                <?php foreach ($semesters as $semester): ?>
                                    <option value="<?= $semester['id'] ?>">
                                        <?= e($semester['name']) ?> (<?= e($semester['code']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">تاريخ بداية التسجيل:</label>
                            <input type="date" class="form-control" name="start_date" required 
                                   min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d') ?>">
                            <small class="text-muted">تاريخ بداية فترة التسجيل</small>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">تاريخ نهاية التسجيل:</label>
                            <input type="date" class="form-control" name="end_date" required 
                                   min="<?= date('Y-m-d', strtotime('+1 day')) ?>" 
                                   value="<?= date('Y-m-d', strtotime('+30 days')) ?>">
                            <small class="text-muted">تاريخ نهاية فترة التسجيل</small>
                        </div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="row g-3 align-items-end mb-3">
                    <div class="col-md-6">
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-outline-primary" onclick="selectAllStudents()">
                                <i class="fas fa-check-square me-1"></i>تحديد الكل
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="deselectAllStudents()">
                                <i class="fas fa-times-circle me-1"></i>إلغاء الكل
                            </button>
                            <button type="submit" name="register_students" class="btn btn-success">
                                <i class="fas fa-user-plus me-1"></i>تسجيل الطلاب المحددين
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6 text-start">
                        <div class="text-muted small">
                            <i class="fas fa-info-circle me-1"></i>
                            سيتم إنشاء رقم مرجعي فريد لكل تسجيل تلقائياً
                            <?php if (!empty($last_registrations)): ?>
                                <br>
                                <i class="fas fa-exclamation-triangle me-1 text-warning"></i>
                                <span class="text-warning">يوجد تسجيلات سابقة بنفس التصفية</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Students Table -->
                <div class="table-responsive mt-4">
                    <table class="table table-striped student-table">
                       <!-- Updated thead section with serial number -->
<thead>
    <tr>
        <th class="checkbox-cell">
            <input type="checkbox" id="selectAll" onchange="toggleAllStudents(this)">
        </th>
        <th>#</th> <!-- Serial Number Column -->
        <th>الرقم الجامعي</th>
        <th>اسم الطالب</th>
        <th>الكلية</th>
        <th>القسم</th>
        <th>البرنامج</th>
        <th>الدفعة</th>
        <th>الرسوم</th>
        <th>التسجيلات السابقة</th>
    </tr>
</thead>

<!-- Updated tbody section with serial number -->
<tbody>
    <?php $counter = 1; ?>
    <?php foreach ($students as $student): ?>
        <?php
        // Calculate total fees for display
        $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;
        ?>
        <tr>
            <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> <!-- Serial Number -->
            <td><code><?= e($student['student_id']) ?></code></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['section_name']) ?></td>
            <td><?= e($student['program_name']) ?></td>
            <td>
                <span class="badge bg-secondary batch-badge"><?= e($student['batch_name']) ?></span>
            </td>
            <td>
                <div class="d-flex flex-column gap-1">
                    <?php if ($study_fees > 0): ?>
                        <span class="badge bg-info fees-badge" title="رسوم الدراسة">
                            <i class="fas fa-book me-1"></i><?= number_format($study_fees, 2) ?>
                        </span>
                    <?php endif; ?>
                    <?php if ($registration_fees > 0): ?>
                        <span class="badge bg-warning fees-badge" title="رسوم التسجيل">
                            <i class="fas fa-edit me-1"></i><?= number_format($registration_fees, 2) ?>
                        </span>
                    <?php endif; ?>
                    <?php if ($insurance_fees > 0): ?>
                        <span class="badge bg-success fees-badge" title="رسوم التأمين">
                            <i class="fas fa-shield-alt me-1"></i><?= number_format($insurance_fees, 2) ?>
                        </span>
                    <?php endif; ?>
                    <span class="badge bg-primary fees-badge" title="المجموع">
                        <i class="fas fa-calculator me-1"></i><?= number_format($total_fees, 2) ?>
                    </span>
                </div>
            </td>
            <td>
                <div class="d-flex align-items-center gap-2">
                    <span class="registration-count <?= $student['registration_count'] > 0 ? 'text-success' : 'text-muted' ?>">
                        <i class="fas fa-clipboard-list me-1"></i>
                        <?= $student['registration_count'] ?> تسجيل
                    </span>
                    <?php if ($student['registration_count'] > 0): ?>
                        <a href="https://admission.tanob.edu.sd/committee_student_profile.php?student_id=<?= urlencode($student['student_id']) ?>" 
                           class="btn btn-sm btn-outline-info" 
                           target="_blank"
                           title="عرض التفاصيل">
                            <i class="fas fa-external-link-alt"></i>
                        </a>
                    <?php else: ?>
                        <span class="btn btn-sm btn-outline-secondary disabled" title="لا توجد تسجيلات سابقة">
                            <i class="fas fa-external-link-alt"></i>
                        </span>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
</tbody>
                    </table>
                </div>
            </form>
        </div>
        <?php else: ?>
            <div class="card card-arabic p-5 text-center">
                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">لا توجد طلاب</h5>
                <p class="text-muted mb-0">لم يتم العثور على طلاب بناءً على عوامل التصفية المحددة</p>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function toggleAllStudents(selectAll) {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
        }
        
        function selectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            document.getElementById('selectAll').checked = true;
        }
        
        function deselectAllStudents() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
        }
        
        // Update select all checkbox when individual checkboxes change
        document.querySelectorAll('.student-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const allChecked = document.querySelectorAll('.student-checkbox:checked').length === document.querySelectorAll('.student-checkbox').length;
                document.getElementById('selectAll').checked = allChecked;
            });
        });
        
        // Form submission confirmation and date validation
        document.getElementById('registrationForm').addEventListener('submit', function(e) {
            const selectedCount = document.querySelectorAll('.student-checkbox:checked').length;
            const startDate = document.querySelector('input[name="start_date"]').value;
            const endDate = document.querySelector('input[name="end_date"]').value;
            const hasPreviousRegistrations = <?= !empty($last_registrations) ? 'true' : 'false' ?>;
            
            if (selectedCount === 0) {
                e.preventDefault();
                alert('يرجى اختيار طالب واحد على الأقل للتسجيل');
                return;
            }
            
            if (!startDate || !endDate) {
                e.preventDefault();
                alert('يرجى تحديد تاريخي البداية والنهاية');
                return;
            }
            
            if (new Date(endDate) <= new Date(startDate)) {
                e.preventDefault();
                alert('تاريخ النهاية يجب أن يكون بعد تاريخ البداية');
                return;
            }
            
            let confirmationMessage = `هل أنت متأكد من تسجيل ${selectedCount} طالب في الفصل الدراسي المحدد؟`;
            
            if (hasPreviousRegistrations) {
                confirmationMessage += '\n\n⚠️ تنبيه: توجد تسجيلات سابقة بنفس عوامل التصفية. يرجى التأكد من عدم التكرار.';
            }
            
            if (!confirm(confirmationMessage)) {
                e.preventDefault();
            }
        });
        
        // Set minimum end date based on start date
        document.querySelector('input[name="start_date"]').addEventListener('change', function() {
            const startDate = this.value;
            const endDateInput = document.querySelector('input[name="end_date"]');
            if (startDate) {
                const minEndDate = new Date(startDate);
                minEndDate.setDate(minEndDate.getDate() + 1);
                endDateInput.min = minEndDate.toISOString().split('T')[0];
                
                // If current end date is before new min date, update it
                if (endDateInput.value && new Date(endDateInput.value) <= new Date(startDate)) {
                    endDateInput.value = minEndDate.toISOString().split('T')[0];
                }
            }
        });
    </script>
</body>
</html>