<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";

// Include PHPMailer with proper namespaces
require '../email/src/Exception.php';
require '../email/src/PHPMailer.php';
require '../email/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$userlogin = $_SESSION['email'];
$userrole = $_SESSION['role'];
$intake = $_SESSION['department'];

if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit;
}

// Process bulk email sending if form is submitted
$emailResult = '';
$selectedStudents = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['send_bulk_reminder'])) {
        // Get selected student IDs
        $student_ids = $_POST['student_ids'] ?? [];
        
        if (empty($student_ids)) {
            $emailResult = "<div class='alert alert-warning'>Please select at least one student to send reminders to.</div>";
        } else {
            $successCount = 0;
            $errorCount = 0;
            $errorMessages = [];
            
            // Get school info
            $school_query = mysqli_query($conn, "SELECT sname FROM admin LIMIT 1");
            $school = mysqli_fetch_assoc($school_query);
            $school_name = $school['sname'] ?? '';
            
            foreach ($student_ids as $student_id) {
                // Get student details
                $student_query = mysqli_query($conn, "SELECT * FROM students WHERE id = '$student_id'");
                if ($student = mysqli_fetch_assoc($student_query)) {
                    $studentid = $student['studentid'];
                    $email = $student['email'];
                    $student_name = $student['studentname'];
                    
                    // Calculate balance
                    $paid_query = mysqli_query($conn, "SELECT SUM(amount) as total_paid FROM payments WHERE studentid = '$studentid'");
                    $paid_data = mysqli_fetch_assoc($paid_query);
                    $total_paid = $paid_data['total_paid'] ?? 0;
                    
                    $balance_query = mysqli_query($conn, "SELECT SUM(amount) as total_balance FROM balances WHERE program = '{$student['program']}' AND intake = '{$student['intake']}'");
                    $balance_data = mysqli_fetch_assoc($balance_query);
                    $total_balance = $balance_data['total_balance'] ?? 0;
                    
                    $owing = $total_balance - $total_paid;
                    
                    if ($owing > 0) {
                        // Send email using PHPMailer
                        $mail = new PHPMailer(true);
                        try {
                            // SMTP Configuration
                            $mail->isSMTP();
                            $mail->Host       = 'unicohsuniversity.com';
                            $mail->SMTPAuth   = true;
                            $mail->Username   = 'portal@unicohsuniversity.com';
                            $mail->Password   = '@mypass1996';
                            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                            $mail->Port       = 587;
                            
                            // Sender
                            $mail->setFrom('portal@unicohsuniversity.com', $school_name . ' Finance');
                            $mail->addAddress($email, $student_name);
                            
                            // Email content
                            $mail->isHTML(true);
                            $mail->Subject = 'Payment Reminder - ' . $school_name;
                            $mail->Body    = "
                                <div style='max-width:600px; margin:0 auto; font-family:Arial,sans-serif;'>
                                    <div style='background:#4a6cf7; color:white; padding:20px; text-align:center;'>
                                        <h2 style='margin:0;'>$school_name</h2>
                                    </div>
                                    <div style='padding:30px; background:#f9f9f9;'>
                                        <p>Dear <strong>$student_name</strong>,</p>
                                        <div style='background:white; padding:20px; border-left:4px solid #dc3545; margin:20px 0;'>
                                            <p>Your account has an outstanding balance of:</p>
                                            <p style='font-size:24px; font-weight:bold; color:#dc3545;'>K" . number_format($owing, 2) . "</p>
                                        </div>
                                        <p>Please make payment to avoid service interruptions.</p>
                                        <p>Best regards,<br>Finance Department<br>$school_name</p>
                                    </div>
                                </div>
                            ";
                            
                            $mail->AltBody = "Dear $student_name,\n\nYou owe K" . number_format($owing, 2) . ".\n\nPlease pay to avoid service interruptions.\n\nBest regards,\nFinance Department\n$school_name";

                            if ($mail->send()) {
                                $successCount++;
                                
                                // Log the email in database
                                mysqli_query($conn, "INSERT INTO email_logs (student_id, student_name, email, amount, sent_date) 
                                                    VALUES ('$studentid', '$student_name', '$email', '$owing', NOW())");
                            } else {
                                $errorCount++;
                                $errorMessages[] = "Failed to send email to $student_name ($studentid)";
                            }
                        } catch (Exception $e) {
                            $errorCount++;
                            $errorMessages[] = "Error sending to $student_name: " . $e->getMessage();
                        }
                    }
                }
                
                // Small delay
                usleep(100000);
            }
            
            // Prepare result message
            if ($successCount > 0) {
                $emailResult = "<div class='alert alert-success'><i class='bi bi-check-circle'></i> Sent $successCount payment reminder(s).</div>";
            }
            
            if ($errorCount > 0) {
                $errorDetails = implode("<br>", $errorMessages);
                $emailResult .= "<div class='alert alert-danger mt-3'><i class='bi bi-exclamation-circle'></i> Failed to send $errorCount email(s):<br>$errorDetails</div>";
            }
        }
    } elseif (isset($_POST['select_students'])) {
        // Store selected students for bulk action
        $selectedStudents = $_POST['student_select'] ?? [];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Balance Report</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        :root {
            --primary: var(--primary);
            --primary-light: #34a37e;
            --primary-dark: #1c6b4d;
            --secondary: #17cc27;
            --light: #f8f9fa;
            --dark: #343a40;
            --gray: #6c757d;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #ffc107;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
            color: #333;
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }
        
        .content {
            margin-left: 200px;
            padding: 20px;
            transition: all 0.3s;
        }
        
        @media (max-width: 992px) {
            .content {
                margin-left: 0;
            }
        }
        
        .balance-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .balance-header {
            background: var(--primary) ;
            color: white;
            padding: 20px 25px;
        }
        
        .balance-body {
            padding: 25px;
        }
        
        .balance-header h2 {
            font-weight: 700;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .balance-header p {
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .search-box {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .bulk-actions {
            background: white;
            padding: 15px 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .summary-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s;
        }
        
        .summary-card:hover {
            transform: translateY(-5px);
        }
        
        .summary-card h3 {
            margin: 0;
            font-size: 28px;
            color: var(--primary);
            font-weight: 700;
        }
        
        .summary-card p {
            margin: 8px 0 0;
            color: var(--gray);
            font-weight: 500;
        }
        
        .balance-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        .balance-table th {
            background: var(--primary);
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
        }
        
        .balance-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .balance-table tr:last-child td {
            border-bottom: none;
        }
        
        .balance-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .balance-high {
            background-color: #ffdddd;
        }
        
        .balance-medium {
            background-color: #fff4dd;
        }
        
        .balance-low {
            background-color: #ddffdd;
        }
        
        .btn-email {
            background: linear-gradient(135deg, #17cc27 0%, #14a721 100%);
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            color: white;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 5px;
            transition: all 0.3s;
        }
        
        .btn-email:hover {
            transform: translateY(-2px);
            box-shadow: 0 3px 8px rgba(23, 204, 39, 0.3);
        }
        
        .btn-bulk {
            background: linear-gradient(135deg, #6f42c1 0%, #5a2d95 100%);
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            color: white;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-bulk:hover {
            background: linear-gradient(135deg, #5a2d95 0%, #4a247c 100%);
        }
        
        .modal-content {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
        }
        
        .email-template {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            border-left: 4px solid var(--primary);
        }
        
        .selected-count {
            background-color: var(--primary);
            color: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }
        
        .table-checkbox {
            width: 20px;
            height: 20px;
        }
    </style>
</head>
<body>
<?php include "../include/nav.php";?>

<div class="content" style="padding:15px">
    <div class="balance-card">
        <div class="balance-header">
            <h2><i class="bi bi-credit-card-2-front"></i> Student Balance Report</h2>
            <p>View student payment status and send payment reminders</p>
        </div>

        <div class="balance-body">
            <?php echo $emailResult; ?>
            
            <div class="search-box">
                <div class="row">
                    <div class="col-md-8">
                        <div class="input-group">
                            <span class="input-group-text"><i class="bi bi-search"></i></span>
                            <input type="text" id="searchInput" class="form-control" placeholder="Search students by name, ID, program...">
                            <button class="btn btn-primary" type="button" id="searchButton">
                                <i class="bi bi-search"></i> Search
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <button class="btn btn-success" onclick="exportToExcel()">
                            <i class="bi bi-download"></i> Export to Excel
                        </button>
                    </div>
                </div>
            </div>
            
            <form method="post" id="bulkForm">
                <div class="bulk-actions">
                    <span class="me-2"><strong>Bulk Actions:</strong></span>
                    <button type="button" class="btn btn-bulk" data-bs-toggle="modal" data-bs-target="#bulkEmailModal">
                        <i class="bi bi-envelope-plus"></i> Send Bulk Reminders
                        <?php if (!empty($selectedStudents)): ?>
                            <span class="selected-count"><?php echo count($selectedStudents); ?></span>
                        <?php endif; ?>
                    </button>
                    <button type="submit" name="select_students" class="btn btn-outline-secondary">
                        <i class="bi bi-check2-square"></i> Update Selection
                    </button>
                    <button type="button" class="btn btn-outline-danger" onclick="clearSelection()">
                        <i class="bi bi-x-circle"></i> Clear All
                    </button>
                </div>
            
                <div class="summary-cards">
                    <div class="summary-card">
                        <h3 id="totalStudents">0</h3>
                        <p><i class="bi bi-people"></i> Total Students</p>
                    </div>
                    <div class="summary-card">
                        <h3 id="totalOwing">K0.00</h3>
                        <p><i class="bi bi-cash-stack"></i> Total Owing</p>
                    </div>
                    <div class="summary-card">
                        <h3 id="avgBalance">K0.00</h3>
                        <p><i class="bi bi-graph-up"></i> Average Balance</p>
                    </div>
                    <div class="summary-card">
                        <h3 id="owingStudents">0</h3>
                        <p><i class="bi bi-exclamation-triangle"></i> Students Owing</p>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="balance-table">
                        <thead>
                            <tr>
                                <th width="30px">
                                    <input type="checkbox" id="selectAll" class="table-checkbox">
                                </th>
                                <th>Student ID</th>
                                <th>Name</th>
                                <th>Program</th>
                                <th>Intake</th>
                                <th>Total Paid</th>
                                <th>Balance Owing</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // Get all students
                            $students_query = mysqli_query($conn, "SELECT `id`, `studentid`, `studentname`, `email`, `intake`, `program` FROM `students` ORDER BY studentname");
                            $total_students = 0;
                            $total_owing = 0;
                            $owing_students = 0;
                            
                            while ($student = mysqli_fetch_assoc($students_query)) {
                                $student_id = $student['id'];
                                $studentid = $student['studentid'];
                                $email = $student['email'];
                                
                                // Calculate total paid
                                $paid_query = mysqli_query($conn, "SELECT SUM(amount) as total_paid FROM payments WHERE studentid = '$studentid'");
                                $paid_data = mysqli_fetch_assoc($paid_query);
                                $total_paid = $paid_data['total_paid'] ?? 0;
                                
                                // Calculate total balance
                                $balance_query = mysqli_query($conn, "SELECT SUM(amount) as total_balance FROM balances WHERE program = '{$student['program']}' AND intake = '{$student['intake']}'");
                                $balance_data = mysqli_fetch_assoc($balance_query);
                                $total_balance = $balance_data['total_balance'] ?? 0;
                                
                                // Calculate owing amount
                                $owing = $total_balance - $total_paid;
                                
                                // Determine status class
                                $status_class = '';
                                if ($owing > 1000) {
                                    $status_class = 'balance-high';
                                    $status_text = 'High Balance';
                                } elseif ($owing > 0) {
                                    $status_class = 'balance-medium';
                                    $status_text = 'Medium Balance';
                                    $owing_students++;
                                } else {
                                    $status_class = 'balance-low';
                                    $status_text = 'Paid Up';
                                }
                                
                                $total_students++;
                                $total_owing += $owing;
                                
                                // Check if student is selected
                                $isChecked = in_array($student_id, $selectedStudents) ? 'checked' : '';
                            ?>
                            <tr class="<?php echo $status_class; ?>">
                                <td>
                                    <?php if ($owing > 0): ?>
                                    <input type="checkbox" name="student_select[]" value="<?php echo $student_id; ?>" 
                                           class="table-checkbox student-checkbox" <?php echo $isChecked; ?>>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo $studentid; ?></td>
                                <td><?php echo $student['studentname']; ?></td>
                                <td><?php echo $student['program']; ?></td>
                                <td><?php echo $student['intake']; ?></td>
                                <td>K<?php echo number_format($total_paid, 2); ?></td>
                                <td>K<?php echo number_format($owing, 2); ?></td>
                                <td><span class="badge bg-<?php echo $status_text == 'Paid Up' ? 'success' : ($status_text == 'Medium Balance' ? 'warning' : 'danger'); ?>"><?php echo $status_text; ?></span></td>
                                <td>
                                    <?php if ($owing > 0): ?>
                                    <button type="button" class="btn-email" data-bs-toggle="modal" data-bs-target="#emailModal" 
                                            data-studentid="<?php echo $studentid; ?>" 
                                            data-email="<?php echo $email; ?>" 
                                            data-name="<?php echo $student['studentname']; ?>" 
                                            data-amount="<?php echo $owing; ?>">
                                        <i class="bi bi-envelope"></i> Remind
                                    </button>
                                    <?php else: ?>
                                    <span class="text-muted">No action needed</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php } ?>
                            
                            <script>
                                // Update summary cards
                                document.getElementById('totalStudents').textContent = '<?php echo $total_students; ?>';
                                document.getElementById('totalOwing').textContent = 'K<?php echo number_format($total_owing, 2); ?>';
                                document.getElementById('avgBalance').textContent = 'K<?php echo $total_students > 0 ? number_format($total_owing / $total_students, 2) : "0.00"; ?>';
                                document.getElementById('owingStudents').textContent = '<?php echo $owing_students; ?>';
                            </script>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Single Email Modal -->
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="emailModalLabel"><i class="bi bi-envelope"></i> Send Payment Reminder</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Student ID</label>
                        <input type="text" class="form-control" id="modal_studentid" name="student_id" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Student Name</label>
                        <input type="text" class="form-control" id="modal_name" name="student_name" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email Address</label>
                        <input type="email" class="form-control" id="modal_email" name="email" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount Owing</label>
                        <input type="text" class="form-control" id="modal_amount" name="amount_owing" readonly>
                    </div>
                    
                    <div class="email-template">
                        <h6><i class="bi bi-chat-text"></i> Email Preview</h6>
                        <hr>
                        <div id="emailPreview"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="send_reminder" class="btn btn-primary">Send Reminder</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Email Modal -->
<div class="modal fade" id="bulkEmailModal" tabindex="-1" aria-labelledby="bulkEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="bulkEmailModalLabel"><i class="bi bi-envelope-plus"></i> Send Bulk Payment Reminders</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> You are about to send payment reminders to <span id="selectedCount">0</span> selected students.
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Selected Students</label>
                        <div id="selectedStudentsList" class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                            <!-- Selected students will be listed here -->
                        </div>
                    </div>
                    
                    <div class="email-template">
                        <h6><i class="bi bi-chat-text"></i> Email Preview</h6>
                        <hr>
                        <div id="bulkEmailPreview"></div>
                    </div>
                    
                    <!-- Hidden field to store selected student IDs -->
                    <div id="selectedStudentsInputs">
                        <!-- Selected student IDs will be added here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="send_bulk_reminder" class="btn btn-primary">Send Bulk Reminders</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Search functionality
    document.getElementById('searchButton').addEventListener('click', function() {
        var filter = document.getElementById('searchInput').value.toLowerCase();
        var rows = document.querySelectorAll('.balance-table tbody tr');
        
        rows.forEach(function(row) {
            var cells = row.getElementsByTagName('td');
            var matchFound = false;
            
            for (var i = 1; i < cells.length; i++) { // Start from 1 to skip checkbox column
                if (cells[i].textContent.toLowerCase().indexOf(filter) > -1) {
                    matchFound = true;
                    break;
                }
            }
            
            if (matchFound) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
    
    // Select all functionality
    document.getElementById('selectAll').addEventListener('change', function() {
        var checkboxes = document.querySelectorAll('.student-checkbox');
        checkboxes.forEach(function(checkbox) {
            checkbox.checked = document.getElementById('selectAll').checked;
        });
        updateSelectedCount();
    });
    
    // Update selected count when checkboxes change
    document.querySelectorAll('.student-checkbox').forEach(function(checkbox) {
        checkbox.addEventListener('change', updateSelectedCount);
    });
    
    function updateSelectedCount() {
        var selectedCount = document.querySelectorAll('.student-checkbox:checked').length;
        var selectedCountElement = document.querySelector('.selected-count');
        
        if (selectedCount > 0) {
            if (!selectedCountElement) {
                selectedCountElement = document.createElement('span');
                selectedCountElement.className = 'selected-count';
                document.querySelector('.btn-bulk').appendChild(selectedCountElement);
            }
            selectedCountElement.textContent = selectedCount;
        } else if (selectedCountElement) {
            selectedCountElement.remove();
        }
    }
    
    // Clear selection
    function clearSelection() {
        document.querySelectorAll('.student-checkbox').forEach(function(checkbox) {
            checkbox.checked = false;
        });
        document.getElementById('selectAll').checked = false;
        updateSelectedCount();
    }
    
    // Single email modal functionality
    var emailModal = document.getElementById('emailModal');
    emailModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var studentid = button.getAttribute('data-studentid');
        var email = button.getAttribute('data-email');
        var name = button.getAttribute('data-name');
        var amount = button.getAttribute('data-amount');
        
        var modal = this;
        modal.querySelector('#modal_studentid').value = studentid;
        modal.querySelector('#modal_name').value = name;
        modal.querySelector('#modal_email').value = email;
        modal.querySelector('#modal_amount').value = 'K' + parseFloat(amount).toLocaleString(undefined, {minimumFractionDigits: 2});
        
        // Generate email preview
        var emailPreview = `
            <p><strong>Subject:</strong> Payment Reminder</p>
            <p><strong>To:</strong> ${name} &lt;${email}&gt;</p>
            <hr>
            <p>Dear ${name},</p>
            <p>This is a friendly reminder that your student account has an outstanding balance of <strong>K${parseFloat(amount).toLocaleString(undefined, {minimumFractionDigits: 2})}</strong>.</p>
            <p>Please make payment at your earliest convenience to avoid any interruptions to your academic services.</p>
            <p>Best regards,<br>Finance Department<br></p>
        `;
        
        modal.querySelector('#emailPreview').innerHTML = emailPreview;
    });
    
    // Bulk email modal functionality
    var bulkEmailModal = document.getElementById('bulkEmailModal');
    bulkEmailModal.addEventListener('show.bs.modal', function () {
        var selectedCheckboxes = document.querySelectorAll('.student-checkbox:checked');
        var selectedCount = selectedCheckboxes.length;
        var selectedStudentsList = '';
        var selectedStudentsInputs = '';
        
        // Update selected count
        document.getElementById('selectedCount').textContent = selectedCount;
        
        // Build list of selected students and hidden inputs
        selectedCheckboxes.forEach(function(checkbox) {
            var row = checkbox.closest('tr');
            var studentId = row.cells[1].textContent;
            var studentName = row.cells[2].textContent;
            var amountOwing = row.cells[6].textContent;
            
            selectedStudentsList += `<div class="mb-2"><strong>${studentName}</strong> (${studentId}) - ${amountOwing}</div>`;
            selectedStudentsInputs += `<input type="hidden" name="student_ids[]" value="${checkbox.value}">`;
        });
        
        document.getElementById('selectedStudentsList').innerHTML = selectedStudentsList || '<div class="text-muted">No students selected</div>';
        document.getElementById('selectedStudentsInputs').innerHTML = selectedStudentsInputs;
        
        // Generate bulk email preview
        var bulkEmailPreview = `
            <p><strong>Subject:</strong> Payment Reminder - </p>
            <p><strong>Recipients:</strong> ${selectedCount} student(s)</p>
            <hr>
            <p>Dear [Student Name],</p>
            <p>This is a friendly reminder that your student account has an outstanding balance of <strong>[Amount Owing]</strong>.</p>
            <p>Please make payment at your earliest convenience to avoid any interruptions to your academic services.</p>
            <p>Best regards,<br>Finance Department<br></p>
            <div class="mt-3 p-2 bg-light rounded">
                <small><i class="bi bi-info-circle"></i> Each student will receive a personalized email with their specific balance information.</small>
            </div>
        `;
        
        document.getElementById('bulkEmailPreview').innerHTML = bulkEmailPreview;
    });
    
    // Export to Excel function
    function exportToExcel() {
        alert("Export to Excel functionality would download a spreadsheet of the current student balances.");
    }
    
    // Initialize selected count on page load
    document.addEventListener('DOMContentLoaded', updateSelectedCount);
</script>
</body>
</html>