<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$system_name = get_system_name($pdo);

$success_message = '';
$error_message = '';

// Get classes for dropdown
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $stmt->fetchAll();

// Get academic sessions for dropdown
$stmt = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC");
$sessions = $stmt->fetchAll();

// Get student groups for dropdown
$stmt = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name");
$groups = $stmt->fetchAll();

// Ensure fee_types table exists and fetch active fee types
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS fee_types (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(100) NOT NULL UNIQUE,
            default_amount DECIMAL(10,2) NULL,
            status ENUM('active','inactive') DEFAULT 'active',
            sort_order INT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");
    $stmt = $pdo->query("SELECT id, name, default_amount FROM fee_types WHERE status = 'active' ORDER BY sort_order, name");
    $fee_types = $stmt->fetchAll();
} catch (Exception $e) {
    $fee_types = [];
}

// AJAX handler for getting students
if (isset($_GET['ajax']) && $_GET['ajax'] == 'get_students') {
    header('Content-Type: application/json');
    
    try {
        $class_id = $_GET['class_id'] ?? '';
        $session = $_GET['session'] ?? '';
        $group_name = $_GET['group_name'] ?? null;
        
        $where_conditions = ["s.status = 'active'"];
        $params = [];
        
        if (!empty($class_id)) {
            $where_conditions[] = "s.class_id = ?";
            $params[] = $class_id;
        }
        
        if (!empty($session)) {
            $where_conditions[] = "s.session = ?";
            $params[] = $session;
        }
        
        // Handle group filtering properly
        if ($group_name !== null) {
            if ($group_name === '') {
                // Special case: "no group" selected (empty string)
                $where_conditions[] = "s.group_name IS NULL OR s.group_name = ''";
            } else {
                // Specific group selected
                $where_conditions[] = "s.group_name = ?";
                $params[] = $group_name;
            }
        }
        
        $where_clause = implode(' AND ', $where_conditions);
        
        $sql = "
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name as class_name, c.section as class_section,
            COALESCE(SUM(f.amount - f.paid_amount), 0) as pending_amount
            FROM students s
            JOIN classes c ON s.class_id = c.id
            LEFT JOIN fees f ON s.id = f.student_id AND f.status IN ('pending', 'partial', 'overdue')
            WHERE $where_clause
            GROUP BY s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name, c.section
            ORDER BY s.roll_number
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $students = $stmt->fetchAll();
        
        echo json_encode($students);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// Handle fee assignment to selected students
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['assign_selected_fees'])) {
    $selected_students = $_POST['selected_students'] ?? [];
    $fee_type = trim($_POST['fee_type']);
    $amount = (float)$_POST['amount'];
    $due_date = $_POST['due_date'];
    $academic_year = trim($_POST['academic_year']);
    $month = trim($_POST['month']);
    $remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';
    
    // Check which required fields are missing
    $missing_fields = [];
    if (empty($selected_students)) {
        $missing_fields[] = 'ছাত্র-ছাত্রীদের নির্বাচন করুন';
    }
    if (empty($fee_type)) {
        $missing_fields[] = 'ফি এর ধরন';
    }
    if ($amount <= 0) {
        $missing_fields[] = 'পরিমাণ (টাকা)';
    }
        
    if (empty($missing_fields)) {
        try {
            $pdo->beginTransaction();
                
            $stmt = $pdo->prepare(
                "INSERT INTO fees (student_id, fee_type, amount, due_date, academic_year, month, remarks) 
                VALUES (?, ?, ?, ?, ?, ?, ?)"
            );
                
            $assigned_count = 0;
            foreach ($selected_students as $student_id) {
                $student_id = (int)$student_id;
                if ($student_id > 0) {
                    // Check if fee already exists for this student, type, and month
                    $check_stmt = $pdo->prepare(
                        "SELECT COUNT(*) FROM fees 
                        WHERE student_id = ? AND fee_type = ? AND academic_year = ? AND month = ?"
                    );
                    $check_stmt->execute([$student_id, $fee_type, $academic_year, $month]);
                        
                    if ($check_stmt->fetchColumn() == 0) {
                        $stmt->execute([$student_id, $fee_type, $amount, $due_date, $academic_year, $month, $remarks]);
                        $assigned_count++;
                    }
                }
            }
                
            $pdo->commit();
            $success_message = "$assigned_count জন ছাত্র-ছাত্রীর জন্য ফি নির্ধারণ করা হয়েছে";
                
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'ফি নির্ধারণে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    } else {
        $missing_fields_str = implode(', ', $missing_fields);
        $error_message = "নিম্নলিখিত তথ্য পূরণ করা হয়নি: $missing_fields_str";
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>কাস্টম ফি নির্ধারণ - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f4f7f6;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #eee;
            font-weight: 600;
            font-size: 1.2rem;
            padding: 1rem 1.5rem;
            border-radius: 15px 15px 0 0 !important;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
        }
        .student-card {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .student-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .student-card.selected {
            border-color: #007bff;
            background-color: #f0f8ff;
        }
        .btn-assign {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 25px;
            padding: 0.75rem 2rem;
            font-weight: 600;
        }
        
        .form-control.is-invalid, .form-select.is-invalid {
            border-color: #dc3545 !important;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25) !important;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> <?php echo htmlspecialchars($system_name); ?>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <div class="navbar-nav ms-auto">
                    <a class="nav-link text-white" href="../index.php"><i class="fas fa-home"></i> হোম</a>
                    <a class="nav-link text-white" href="manage.php"><i class="fas fa-cog"></i> ফি ম্যানেজ</a>
                    <a class="nav-link text-white" href="student_fees.php"><i class="fas fa-money-bill-wave"></i> ফি কালেক্ট</a>
                    <a class="nav-link text-white" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?php echo $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"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Fee Assignment Form -->
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-user-plus"></i> নির্বাচিত শিক্ষার্থীদের জন্য ফি নির্ধারণ</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" id="feeAssignmentForm">
                            <input type="hidden" name="assign_selected_fees" value="1">
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label for="fee_type" class="form-label">ফি এর ধরন <span class="text-danger">*</span></label>
                                    <select class="form-select" id="fee_type" name="fee_type" required>
                                        <option value="">নির্বাচন করুন</option>
                                        <?php if (!empty($fee_types)) : ?>
                                            <?php foreach ($fee_types as $t): ?>
                                                <option value="<?php echo htmlspecialchars($t['name']); ?>" data-default="<?php echo htmlspecialchars($t['default_amount']); ?>">
                                                    <?php echo htmlspecialchars($t['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <option value="মাসিক বেতন">মাসিক বেতন</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label for="amount" class="form-label">পরিমাণ (টাকা) <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="amount" name="amount" min="0" step="0.01" required>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label for="academic_year" class="form-label">সেশন</label>
                                    <select class="form-select" id="academic_year" name="academic_year">
                                        <option value="">সেশন নির্বাচন করুন</option>
                                        <?php foreach ($sessions as $s): ?>
                                            <option value="<?php echo htmlspecialchars($s['session_name']); ?>">
                                                <?php echo htmlspecialchars($s['session_name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label for="month" class="form-label">মাস</label>
                                    <select class="form-select" id="month" name="month">
                                        <option value="">নির্বাচন করুন</option>
                                        <option value="জানুয়ারি">জানুয়ারি</option>
                                        <option value="ফেব্রুয়ারি">ফেব্রুয়ারি</option>
                                        <option value="মার্চ">মার্চ</option>
                                        <option value="এপ্রিল">এপ্রিল</option>
                                        <option value="মে">মে</option>
                                        <option value="জুন">জুন</option>
                                        <option value="জুলাই">জুলাই</option>
                                        <option value="আগস্ট">আগস্ট</option>
                                        <option value="সেপ্টেম্বর">সেপ্টেম্বর</option>
                                        <option value="অক্টোবর">অক্টোবর</option>
                                        <option value="নভেম্বর">নভেম্বর</option>
                                        <option value="ডিসেম্বর">ডিসেম্বর</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="due_date" class="form-label">শেষ তারিখ <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="due_date" name="due_date" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="remarks" class="form-label">বিবরণ</label>
                                    <input type="text" class="form-control" id="remarks" name="remarks" placeholder="যেমন: ২০২১ জানুয়ারি মাসিক বেতন">
                                </div>
                            </div>
                            
                            <hr>
                            
                            <!-- Student Selection Section -->
                            <h5 class="mb-3"><i class="fas fa-users"></i> শিক্ষার্থী নির্বাচন করুন</h5>
                            
                            <div class="filter-section mb-4">
                                <div class="row g-3">
                                    <div class="col-md-3">
                                        <label for="filter_session" class="form-label">সেশন</label>
                                        <select class="form-select" id="filter_session">
                                            <option value="">সব সেশন</option>
                                            <?php foreach ($sessions as $session): ?>
                                                <option value="<?php echo htmlspecialchars($session['session_name']); ?>">
                                                    <?php echo htmlspecialchars($session['session_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label for="filter_class" class="form-label">ক্লাস</label>
                                        <select class="form-select" id="filter_class">
                                            <option value="">সব ক্লাস</option>
                                            <?php foreach ($classes as $class): ?>
                                                <option value="<?php echo $class['id']; ?>">
                                                    <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label for="filter_group" class="form-label">গ্রুপ</label>
                                        <select class="form-select" id="filter_group">
                                            <option value="">সব গ্রুপ</option>
                                            <option value="__NO_GROUP__">কোন গ্রুপ নেই</option>
                                            <?php foreach ($groups as $group): ?>
                                                <option value="<?php echo htmlspecialchars($group['group_name']); ?>">
                                                    <?php echo htmlspecialchars($group['group_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="button" class="btn btn-primary w-100" onclick="loadStudents()">
                                            <i class="fas fa-search"></i> খুঁজুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-5">
                                    <div class="card">
                                        <div class="card-header">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <h6 class="mb-0"><i class="fas fa-list"></i> শিক্ষার্থী তালিকা</h6>
                                                <span class="badge bg-light text-dark" id="student-count">0 জন</span>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="mb-3">
                                                <div class="input-group">
                                                    <input type="text" class="form-control" id="student-search" placeholder="নাম, আইডি বা রোল দিয়ে খুঁজুন...">
                                                    <button class="btn btn-outline-secondary" type="button" id="search-button">
                                                        <i class="fas fa-search"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <div style="max-height: 400px; overflow-y: auto;">
                                                <div id="students-list">
                                                    <div class="text-center text-muted py-4">
                                                        <i class="fas fa-search fa-3x mb-3"></i>
                                                        <p>শিক্ষার্থী খুঁজতে উপরের ফিল্টার ব্যবহার করুন</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <nav class="mt-3">
                                                <ul class="pagination justify-content-center pagination-sm" id="pagination-controls"></ul>
                                            </nav>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-7">
                                    <div class="card">
                                        <div class="card-header">
                                            <h6 class="mb-0"><i class="fas fa-check-square"></i> নির্বাচিত শিক্ষার্থীরা</h6>
                                        </div>
                                        <div class="card-body">
                                            <div id="selected-students-area">
                                                <div class="text-center text-muted py-4">
                                                    <i class="fas fa-user-check fa-3x mb-3"></i>
                                                    <p>শিক্ষার্থী নির্বাচন করুন</p>
                                                </div>
                                            </div>
                                            
                                            <div class="mt-3 d-grid">
                                                <button type="submit" class="btn btn-assign" id="assignButton" disabled>
                                                    <i class="fas fa-save"></i> নির্বাচিত শিক্ষার্থীদের জন্য ফি নির্ধারণ করুন
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let allStudents = [];
        let filteredStudents = [];
        let selectedStudents = [];
        const studentsPerPage = 10;
        let currentPage = 1;

        function loadStudents() {
            const session = document.getElementById('filter_session').value;
            const classId = document.getElementById('filter_class').value;
            let groupName = document.getElementById('filter_group').value;

            // Build parameters object
            const paramsObj = { ajax: 'get_students' };
            
            if (session) paramsObj.session = session;
            if (classId) paramsObj.class_id = classId;
            
            // Handle group filtering
            if (groupName !== '') {
                if (groupName === '__NO_GROUP__') {
                    // Special case: "no group" selected
                    paramsObj.group_name = '';
                } else {
                    // Specific group selected
                    paramsObj.group_name = groupName;
                }
            }

            const params = new URLSearchParams(paramsObj);

            document.getElementById('students-list').innerHTML = '<div class="text-center text-muted py-4"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">লোড হচ্ছে...</p></div>';

            return fetch(`?${params}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // Check if the response contains an error
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    allStudents = data;
                    filterStudents();
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('students-list').innerHTML = '<div class="text-center text-danger py-4"><i class="fas fa-exclamation-triangle fa-3x mb-3"></i><p>শিক্ষার্থী লোড করতে সমস্যা হয়েছে: ' + error.message + '</p></div>';
                });
        }

        function filterStudents() {
            const searchTerm = document.getElementById('student-search').value.toLowerCase().trim();
            filteredStudents = (searchTerm === '') ? allStudents : allStudents.filter(s => 
                (s.first_name + ' ' + s.last_name).toLowerCase().includes(searchTerm) ||
                s.roll_number.toString().toLowerCase().includes(searchTerm) ||
                (s.student_id || '').toString().toLowerCase().includes(searchTerm)
            );
            currentPage = 1;
            renderPage(currentPage);
            setupPagination();
        }

        function renderPage(page) {
            currentPage = page;
            const container = document.getElementById('students-list');
            const countElement = document.getElementById('student-count');
            
            countElement.textContent = `${filteredStudents.length} জন`;

            if (filteredStudents.length === 0) {
                container.innerHTML = '<div class="text-center text-muted py-4"><i class="fas fa-user-slash fa-3x mb-3"></i><p>কোন শিক্ষার্থী পাওয়া যায়নি</p></div>';
                return;
            }

            const startIndex = (page - 1) * studentsPerPage;
            const endIndex = startIndex + studentsPerPage;
            container.innerHTML = generateStudentCards(filteredStudents.slice(startIndex, endIndex));
        }

        function setupPagination() {
            const paginationContainer = document.getElementById('pagination-controls');
            if (!paginationContainer) return;
            paginationContainer.innerHTML = '';
            
            const pageCount = Math.ceil(filteredStudents.length / studentsPerPage);
            if (pageCount <= 1) return;

            const createPageItem = (text, pageNum, isDisabled = false, isActive = false) => {
                const li = document.createElement('li');
                li.className = `page-item ${isDisabled ? 'disabled' : ''} ${isActive ? 'active' : ''}`;
                const a = document.createElement('a');
                a.className = 'page-link';
                a.href = '#';
                a.innerHTML = text;
                if (!isDisabled) {
                    a.addEventListener('click', (e) => { e.preventDefault(); renderPage(pageNum); });
                }
                li.appendChild(a);
                return li;
            };

            paginationContainer.appendChild(createPageItem('&laquo;', currentPage - 1, currentPage === 1));
            for (let i = 1; i <= pageCount; i++) {
                paginationContainer.appendChild(createPageItem(i, i, false, i === currentPage));
            }
            paginationContainer.appendChild(createPageItem('&raquo;', currentPage + 1, currentPage === pageCount));
        }

        function generateStudentCards(students) {
            let html = '';
            students.forEach(student => {
                const isSelected = selectedStudents.includes(parseInt(student.id));
                
                // Format the pending amount with proper number formatting
                const pendingAmount = parseFloat(student.pending_amount || 0);
                const formattedAmount = pendingAmount.toLocaleString('bn-BD', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
                
                html += `
                    <div class="student-card p-3 mb-2 ${isSelected ? 'selected' : ''}" 
                         onclick="toggleStudentSelection(${student.id}, '${student.first_name} ${student.last_name}', ${student.roll_number})">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h6 class="mb-1">${student.first_name} ${student.last_name}</h6>
                                <small class="text-muted">রোল: ${student.roll_number} | আইডি: ${student.student_id || 'N/A'}</small>
                                <div class="mt-1">
                                    <small class="text-info">বকেয়া ফি: ${formattedAmount} টাকা</small>
                                </div>
                                ${student.scholarship === 'yes' ? '<span class="badge bg-success mt-1">উপবৃত্তি</span>' : ''}
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" 
                                       id="student_${student.id}" 
                                       ${isSelected ? 'checked' : ''}>
                            </div>
                        </div>
                    </div>
                `;
            });
            return html;
        }

        function toggleStudentSelection(studentId, studentName, rollNumber) {
            studentId = parseInt(studentId);
            const index = selectedStudents.indexOf(studentId);
            
            if (index === -1) {
                // Add to selected students
                selectedStudents.push(studentId);
            } else {
                // Remove from selected students
                selectedStudents.splice(index, 1);
            }
            
            // Update UI
            updateSelectedStudentsDisplay();
            updateStudentCardUI(studentId);
            updateAssignButtonState();
            
            // Update checkbox state
            const checkbox = document.getElementById(`student_${studentId}`);
            if (checkbox) {
                checkbox.checked = index === -1;
            }
        }

        function updateStudentCardUI(studentId) {
            const studentCard = document.querySelector(`.student-card[onclick*="toggleStudentSelection(${studentId},"]`);
            if (studentCard) {
                const isSelected = selectedStudents.includes(parseInt(studentId));
                if (isSelected) {
                    studentCard.classList.add('selected');
                } else {
                    studentCard.classList.remove('selected');
                }
            }
        }

        function updateSelectedStudentsDisplay() {
            const container = document.getElementById('selected-students-area');
            
            if (selectedStudents.length === 0) {
                container.innerHTML = '<div class="text-center text-muted py-4"><i class="fas fa-user-check fa-3x mb-3"></i><p>শিক্ষার্থী নির্বাচন করুন</p></div>';
                return;
            }
            
            // Get student details for display
            const selectedStudentDetails = allStudents.filter(s => selectedStudents.includes(parseInt(s.id)));
            
            let html = '<div class="table-responsive"><table class="table table-striped table-bordered">';
            html += '<thead><tr><th>রোল</th><th>নাম</th><th>ক্লাস</th><th>অ্যাকশন</th></tr></thead><tbody>';
            
            selectedStudentDetails.forEach(student => {
                html += `
                    <tr>
                        <td>${student.roll_number}</td>
                        <td>${student.first_name} ${student.last_name}</td>
                        <td>${student.class_name} - ${student.class_section}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-danger" 
                                    onclick="removeStudentFromSelection(${student.id})">
                                <i class="fas fa-times"></i> সরান
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table></div>';
            html += `<div class="alert alert-info"><strong>মোট নির্বাচিত শিক্ষার্থী:</strong> ${selectedStudents.length} জন</div>`;
            
            container.innerHTML = html;
        }

        function removeStudentFromSelection(studentId) {
            studentId = parseInt(studentId);
            const index = selectedStudents.indexOf(studentId);
            
            if (index !== -1) {
                selectedStudents.splice(index, 1);
                updateSelectedStudentsDisplay();
                updateStudentCardUI(studentId);
                updateAssignButtonState();
                
                // Update checkbox state
                const checkbox = document.getElementById(`student_${studentId}`);
                if (checkbox) {
                    checkbox.checked = false;
                }
            }
        }

        function updateAssignButtonState() {
            const assignButton = document.getElementById('assignButton');
            assignButton.disabled = selectedStudents.length === 0;
        }
        
        // Add hidden inputs for selected students before form submission
        document.getElementById('feeAssignmentForm').addEventListener('submit', function(e) {
            // Remove any existing hidden inputs to avoid duplicates
            const existingInputs = document.querySelectorAll('input[name="selected_students[]"]');
            existingInputs.forEach(input => input.remove());
            
            // Add hidden inputs for each selected student
            selectedStudents.forEach(studentId => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selected_students[]';
                input.value = studentId;
                this.appendChild(input);
            });
        });

        function selectAllStudents() {
            // Select all currently displayed students
            const startIndex = (currentPage - 1) * studentsPerPage;
            const endIndex = startIndex + studentsPerPage;
            const currentPageStudents = filteredStudents.slice(startIndex, endIndex);
            
            currentPageStudents.forEach(student => {
                const studentId = parseInt(student.id);
                if (!selectedStudents.includes(studentId)) {
                    selectedStudents.push(studentId);
                }
            });
            
            updateSelectedStudentsDisplay();
            updateAssignButtonState();
            
            // Refresh the current page to update UI
            renderPage(currentPage);
        }

        function clearAllSelection() {
            selectedStudents = [];
            updateSelectedStudentsDisplay();
            updateAssignButtonState();
            
            // Refresh the current page to update UI
            renderPage(currentPage);
        }

        // Set default values
        document.addEventListener('DOMContentLoaded', function() {
            // Set current month as default
            const monthSelect = document.getElementById('month');
            if (monthSelect) {
                const currentMonth = new Date().getMonth();
                const months = ['জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 
                               'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'];
                if (months[currentMonth]) {
                    monthSelect.value = months[currentMonth];
                }
            }
            
            // Set due date to end of current month
            const dueDateInput = document.getElementById('due_date');
            if (dueDateInput) {
                const today = new Date();
                const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                dueDateInput.value = lastDay.toISOString().split('T')[0];
            }

            // Auto-fill amount from fee type defaults
            const feeTypeSelect = document.getElementById('fee_type');
            const amountInput = document.getElementById('amount');
            if (feeTypeSelect && amountInput) {
                feeTypeSelect.addEventListener('change', function() {
                    const opt = feeTypeSelect.selectedOptions[0];
                    if (!opt) return;
                    const def = opt.getAttribute('data-default');
                    if (def !== null && def !== '' && !isNaN(def)) {
                        amountInput.value = parseFloat(def).toFixed(2);
                    }
                });
            }

            // Setup search functionality
            document.getElementById('student-search').addEventListener('keyup', filterStudents);
            document.getElementById('search-button').addEventListener('click', filterStudents);
            document.getElementById('student-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    filterStudents();
                }
            });
        });
        
        // Add form validation
        document.getElementById('feeAssignmentForm').addEventListener('submit', function(e) {
            // Reset previous error highlights
            document.querySelectorAll('.form-control, .form-select').forEach(element => {
                element.classList.remove('is-invalid');
            });
            
            let isValid = true;
            
            // Check fee type
            const feeType = document.getElementById('fee_type');
            if (!feeType.value) {
                feeType.classList.add('is-invalid');
                isValid = false;
            }
            
            // Check amount
            const amount = document.getElementById('amount');
            if (!amount.value || parseFloat(amount.value) <= 0) {
                amount.classList.add('is-invalid');
                isValid = false;
            }
            
            // Check if students are selected
            if (selectedStudents.length === 0) {
                // Highlight the student selection area
                const selectedArea = document.getElementById('selected-students-area');
                if (selectedArea) {
                    selectedArea.style.border = '2px solid #dc3545';
                    selectedArea.style.borderRadius = '5px';
                    selectedArea.style.padding = '10px';
                    setTimeout(() => {
                        selectedArea.style.border = '';
                        selectedArea.style.borderRadius = '';
                        selectedArea.style.padding = '';
                    }, 3000);
                }
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
                alert('দয়া করে সমস্ত প্রয়োজনীয় তথ্য পূরণ করুন।');
                return false;
            }
        });
        
        // Clear invalid styling when user starts typing
        document.getElementById('fee_type').addEventListener('change', function() {
            this.classList.remove('is-invalid');
        });
        
        document.getElementById('amount').addEventListener('input', function() {
            this.classList.remove('is-invalid');
        });
    </script>
</body>
</html>