Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : /home/vishqocm/pcib.in/admin/enrollments.php

<?php
// Include header
require_once 'includes/header.php';

// Check if user has admin privileges
if ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director') {
    header('Location: ../login.php');
    exit;
}

// Process enrollment verification
$success_message = '';
$error_message = '';

// Mark enrollment as completed
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_completed'])) {
    $enrollment_id = intval($_POST['enrollment_id']);
    $admin_notes = isset($_POST['admin_notes']) ? $_POST['admin_notes'] : '';
    
    // Mark the enrollment as completed
    $complete_query = "UPDATE enrollments SET status = 'completed', completion_date = NOW() WHERE id = ?";
    $stmt = $conn->prepare($complete_query);
    $stmt->bind_param("i", $enrollment_id);
    
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        $success_message = "Enrollment marked as completed successfully.";
        
        // // Get enrollment details for notification
        // $enroll_query = "SELECT e.*, u.email, u.first_name, c.title as course_title
        //                  FROM enrollments e
        //                  JOIN users u ON e.user_id = u.id
        //                  JOIN courses c ON e.course_id = c.id
        //                  WHERE e.id = ?";
        // $stmt = $conn->prepare($enroll_query);
        // $stmt->bind_param("i", $enrollment_id);
        // $stmt->execute();
        // $enrollment = $stmt->get_result()->fetch_assoc();
        
        // // Send email notification if email functions are available
        // if (file_exists('../includes/email_functions.php')) {
        //     require_once '../includes/email_functions.php';
        //     if (function_exists('send_course_completion_email')) {
        //         send_course_completion_email(
        //             $enrollment['email'],
        //             $enrollment['first_name'],
        //             $enrollment['course_title']
        //         );
        //     }
        // }
        
        // Add admin notes if provided
        if (!empty($admin_notes)) {
            $notes_query = "UPDATE enrollments SET admin_notes = CONCAT(IFNULL(admin_notes, ''), ?\n', ?) 
                            WHERE id = ?";
            $note_with_date = "[" . date('Y-m-d H:i:s') . " - Completion] ";
            $stmt = $conn->prepare($notes_query);
            $stmt->bind_param("ssi", $note_with_date, $admin_notes, $enrollment_id);
            $stmt->execute();
        }
    } else {
        $error_message = "Failed to mark enrollment as completed.";
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_enrollment'])) {
    $enrollment_id = intval($_POST['enrollment_id']);
    $verification_token = $_POST['verification_token'];
    $admin_notes = $_POST['admin_notes'];
    
    // Verify the enrollment
    $verify_query = "UPDATE enrollments SET status = 'active', verification_date = NOW(), verified_by = ? WHERE id = ? AND verification_token = ?";
    $stmt = $conn->prepare($verify_query);
    $stmt->bind_param("iis", $_SESSION['user_id'], $enrollment_id, $verification_token);
    
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        $success_message = "Enrollment verified successfully.";
        
        // Get enrollment details
        $enroll_query = "SELECT e.*, u.email, u.first_name, c.title as course_title
                         FROM enrollments e
                         JOIN users u ON e.user_id = u.id
                         JOIN courses c ON e.course_id = c.id
                         WHERE e.id = ?";
        $stmt = $conn->prepare($enroll_query);
        $stmt->bind_param("i", $enrollment_id);
        $stmt->execute();
        $enrollment = $stmt->get_result()->fetch_assoc();
        
        // Send email notification if email functions are available
        if (file_exists('../includes/email_functions.php')) {
            require_once '../includes/email_functions.php';
            if (function_exists('send_enrollment_confirmation_email')) {
                send_enrollment_confirmation_email(
                    $enrollment['email'],
                    $enrollment['first_name'],
                    $enrollment['course_title']
                );
            }
        }
        
        // Add admin notes if provided
        if (!empty($admin_notes)) {
            $notes_query = "UPDATE enrollment_applications SET admin_notes = ? 
                            WHERE user_id = ? AND course_id = ? AND status = 'completed'";
            $stmt = $conn->prepare($notes_query);
            $stmt->bind_param("sii", $admin_notes, $enrollment['user_id'], $enrollment['course_id']);
            $stmt->execute();
        }
    } else {
        $error_message = "Failed to verify enrollment. Please check the verification token.";
    }
}

// Get all enrollments with user and course information
$query = "SELECT e.*, u.first_name, u.last_name, u.email, c.title as course_title, c.price, c.discount_price,
          (SELECT COUNT(*) FROM student_documents WHERE user_id = e.user_id AND status = 'verified') as verified_documents
          FROM enrollments e
          JOIN users u ON e.user_id = u.id
          JOIN courses c ON e.course_id = c.id
          ORDER BY e.enrollment_date DESC";
$result = $conn->query($query);
?>

<!-- Begin Page Content -->
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Enrollment Management</h1>
        <a href="enrollment_applications.php" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm">
            <i class="fas fa-clipboard-list fa-sm text-white-50"></i> View Applications
        </a>
    </div>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?php echo $success_message; ?></div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger"><?php echo $error_message; ?></div>
    <?php endif; ?>

    <!-- Content Row -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Student Enrollments</h6>
                    <div class="dropdown no-arrow">
                        <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in"
                            aria-labelledby="dropdownMenuLink">
                            <div class="dropdown-header">Filter By:</div>
                            <a class="dropdown-item filter-status" href="#" data-status="all">All Enrollments</a>
                            <a class="dropdown-item filter-status" href="#" data-status="active">Active Enrollments</a>
                            <a class="dropdown-item filter-status" href="#" data-status="pending">Pending Enrollments</a>
                            <a class="dropdown-item filter-status" href="#" data-status="completed">Completed Enrollments</a>
                            <a class="dropdown-item filter-status" href="#" data-status="cancelled">Cancelled Enrollments</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="enrollmentsTable" width="100%" cellspacing="0">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Enrollment #</th>
                                    <th>Student</th>
                                    <th>Course</th>
                                    <th>Enrollment Date</th>
                                    <th>Status</th>
                                    <th>Documents</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($result && $result->num_rows > 0): ?>
                                    <?php while ($row = $result->fetch_assoc()): ?>
                                        <tr class="enrollment-row" data-status="<?php echo $row['status']; ?>">
                                            <td><?php echo $row['id']; ?></td>
                                            <td><?php echo !empty($row['enrollment_number']) ? $row['enrollment_number'] : 'N/A'; ?></td>
                                            <td>
                                                <?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>
                                                <div class="small text-muted"><?php echo $row['email']; ?></div>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($row['course_title']); ?>
                                                <div class="small text-muted">
                                                    <?php 
                                                    $price = $row['discount_price'] > 0 && $row['discount_price'] < $row['price'] 
                                                            ? $row['discount_price'] : $row['price'];
                                                    echo '₹' . number_format($price, 2); 
                                                    ?>
                                                </div>
                                            </td>
                                            <td><?php echo date('M d, Y', strtotime($row['enrollment_date'])); ?></td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo ($row['status'] === 'active') ? 'success' : 
                                                        (($row['status'] === 'cancelled') ? 'danger' : 
                                                         (($row['status'] === 'completed') ? 'info' : 'warning')); 
                                                ?>">
                                                    <?php echo ucfirst($row['status']); ?>
                                                </span>
                                                <?php if($row['status'] === 'completed' && !empty($row['completion_date'])): ?>
                                                <div class="small text-muted mt-1">
                                                    Completed: <?php echo date('M d, Y', strtotime($row['completion_date'])); ?>
                                                </div>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php echo ($row['verified_documents'] >= 3) ? 'success' : 'warning'; ?>">
                                                    <?php echo $row['verified_documents']; ?> Verified
                                                </span>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <button type="button" class="btn btn-info btn-sm view-details" id="viewDetailsButton"
                                                            data-id="<?php echo $row['id']; ?>">
                                                        <i class="fas fa-eye"></i> Details
                                                    </button>
                                                    <?php if ($row['status'] !== 'active' && !empty($row['verification_token'])): ?>
                                                    <button type="button" class="btn btn-success btn-sm verify-btn" 
                                                            data-bs-toggle="modal" data-bs-target="#verifyModal"
                                                            data-enrollment-id="<?php echo $row['id']; ?>"
                                                            data-student-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>"
                                                            data-course-title="<?php echo htmlspecialchars($row['course_title']); ?>"
                                                            data-token="<?php echo $row['verification_token']; ?>">
                                                        <i class="fas fa-check-circle"></i> Verify
                                                    </button>
                                                    <?php endif; ?>
                                                    <?php if ($row['status'] === 'active'): ?>
                                                    <button type="button" class="btn btn-success btn-sm mark-completed-btn" 
                                                            data-bs-toggle="modal" data-bs-target="#markCompletedModal"
                                                            data-enrollment-id="<?php echo $row['id']; ?>"
                                                            data-student-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>"
                                                            data-course-title="<?php echo htmlspecialchars($row['course_title']); ?>">
                                                        <i class="fas fa-graduation-cap"></i> Mark Completed
                                                    </button>
                                                    <?php endif; ?>
                                                    <a href="enrollment_payment.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">
                                                        <i class="fas fa-money-bill"></i> Payments
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9" class="text-center">No enrollments found</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /.container-fluid -->

<!-- Enrollment Details Modal -->
<div class="modal fade" id="enrollment-details" tabindex="-1" role="dialog" aria-labelledby="enrollmentDetailsLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="enrollmentDetailsLabel">Enrollment Details</h5>
                <button type="button" class="close text-white" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading enrollment details...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <a href="#" id="viewStudentBtn" class="btn btn-info">
                    <i class="fas fa-user mr-1"></i> View Student Profile
                </a>
                <a href="#" id="viewCourseBtn" class="btn btn-primary">
                    <i class="fas fa-book mr-1"></i> View Course
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Verification Modal -->
<div class="modal fade" id="verifyModal" tabindex="-1" role="dialog" aria-labelledby="verifyModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="verifyModalLabel">Verify Enrollment</h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" action="">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i> Verifying an enrollment will change its status to 'active'.
                    </div>
                    
                    <p><strong>Student:</strong> <span id="verifyStudentName"></span></p>
                    <p><strong>Course:</strong> <span id="verifyCourseTitle"></span></p>
                    <p><strong>Enrollment Number:</strong> <span id="verifyEnrollmentNumber"></span></p>
                    
                    <input type="hidden" name="enrollment_id" id="enrollmentId">
                    
                    <div class="form-group">
                        <label for="verification_token">Verification Token</label>
                        <input type="text" class="form-control" id="verification_token" name="verification_token" required readonly>
                        <small class="form-text text-muted">This token is required to verify the enrollment.</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_notes">Admin Notes</label>
                        <textarea class="form-control" id="admin_notes" name="admin_notes" rows="3"></textarea>
                        <small class="form-text text-muted">Optional notes about this enrollment verification.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="verify_enrollment" class="btn btn-success">Verify Enrollment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Mark Completed Modal -->
<div class="modal fade" id="markCompletedModal" tabindex="-1" role="dialog" aria-labelledby="markCompletedModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="markCompletedModalLabel">Mark Enrollment as Completed</h5>
                <button type="button" class="close text-white" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" action="">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i> Marking an enrollment as completed will allow the student to generate certificates.
                    </div>
                    
                    <p><strong>Student:</strong> <span id="completeStudentName"></span></p>
                    <p><strong>Course:</strong> <span id="completeCourseTitle"></span></p>
                    
                    <input type="hidden" name="enrollment_id" id="completeEnrollmentId" >
                    
                    <div class="form-group">
                        <label for="admin_notes">Completion Notes (Optional)</label>
                        <textarea class="form-control" id="admin_notes" name="admin_notes" rows="3" placeholder="Enter any notes about this completion..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="mark_completed" class="btn btn-success">
                        <i class="fas fa-graduation-cap mr-1"></i> Mark as Completed
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // DataTable initialization
    $('#enrollmentsTable').DataTable({
        "order": [[3, "desc"]] // Sort by enrollment date by default
    });
    
    // Filter by status
    $('.filter-status').on('click', function(e) {
        e.preventDefault();
        var status = $(this).data('status');
        
        if (status === 'all') {
            $('.enrollment-row').show();
        } else {
            $('.enrollment-row').hide();
            $('.enrollment-row[data-status="' + status + '"]').show();
        }
    });
    
    // View details button click
    $('.view-details').on('click', function() {
        var enrollmentId = $(this).data('id');
        
        // Clear previous content
        $('#enrollment-details .modal-body').html('<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-2">Loading enrollment details...</p></div>');
        
        // Show modal
        var modalElement = document.getElementById('enrollment-details');
        var enrollmentModal = new bootstrap.Modal(modalElement);
        enrollmentModal.show();
        
        // Load enrollment details
        $.ajax({
            url: 'ajax/get_enrollment_details.php',
            type: 'GET',
            data: { enrollment_id: enrollmentId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var enrollment = response.data;
                    var statusBadgeClass = getStatusBadgeClass(enrollment.status);
                    
                    // Update modal content with enrollment details
                    var modalContent = `
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card mb-3">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Student Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>Name:</strong> ${enrollment.student_name}</p>
                                        <p><strong>Email:</strong> ${enrollment.student_email}</p>
                                        <p><strong>Enrollment Date:</strong> ${enrollment.enrollment_date}</p>
                                        <p><strong>Last Update:</strong> ${enrollment.last_updated}</p>
                                        <p><a href="user_profile.php?id=${enrollment.user_id}" class="btn btn-sm btn-info"><i class="fas fa-user"></i> View Profile</a></p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card mb-3">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0">Course Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>Course:</strong> ${enrollment.course_title}</p>
                                        <p><strong>Status:</strong> <span class="badge bg-${statusBadgeClass}">${capitalizeFirstLetter(enrollment.status)}</span></p>
                                        <p><strong>Verification Token:</strong> 
                                            <div class="input-group mb-3">
                                                <input type="text" class="form-control form-control-sm" id="verification-token" value="${enrollment.verification_token}" readonly>
                                                <button class="btn btn-outline-secondary btn-sm" type="button" id="copy-token"><i class="fas fa-copy"></i> Copy</button>
                                            </div>
                                        </p>
                                        <p><a href="course_details.php?id=${enrollment.course_id}" class="btn btn-sm btn-info"><i class="fas fa-book"></i> View Course</a></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <ul class="nav nav-tabs" id="myTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="documents-tab" data-bs-toggle="tab" data-bs-target="#documentsTab" type="button" role="tab" aria-controls="documentsTab" aria-selected="true">Documents</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="payment-tab" data-bs-toggle="tab" data-bs-target="#paymentTab" type="button" role="tab" aria-controls="paymentTab" aria-selected="false">Payment History</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="notes-tab" data-bs-toggle="tab" data-bs-target="#notesTab" type="button" role="tab" aria-controls="notesTab" aria-selected="false">Admin Notes</button>
                            </li>
                        </ul>
                        <div class="tab-content py-3" id="myTabContent">
                            <div class="tab-pane fade show active" id="documentsTab" role="tabpanel" aria-labelledby="documents-tab">
                                <div id="documentTabContent">
                                    <div class="d-flex justify-content-center">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="paymentTab" role="tabpanel" aria-labelledby="payment-tab">
                                <div id="paymentTabContent">
                                    <div class="text-center">
                                        <p>Click to load payment history</p>
                                        <button class="btn btn-primary" id="loadPaymentBtn">Load Payment History</button>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="notesTab" role="tabpanel" aria-labelledby="notes-tab">
                                <div class="card">
                                    <div class="card-body">
                                        <form id="adminNotesForm">
                                            <div class="mb-3">
                                                <label for="adminNotes" class="form-label">Admin Notes</label>
                                                <textarea class="form-control" id="adminNotes" rows="5">${enrollment.admin_notes || ''}</textarea>
                                            </div>
                                            <button type="submit" class="btn btn-primary">Save Notes</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    $('#enrollment-details .modal-body').html(modalContent);
                    
                    // Load documents
                    $.ajax({
                        url: 'ajax/get_student_documents.php',
                        type: 'GET',
                        data: { application_id: enrollment.application_id },
                        success: function(docResponse) {
                            $('#documentTabContent').html(docResponse);
                        },
                        error: function() {
                            $('#documentTabContent').html('<div class="alert alert-danger">Failed to load documents. Please try again.</div>');
                        }
                    });
                    
                    // Set up copy token button
                    $('#copy-token').on('click', function() {
                        var tokenInput = document.getElementById('verification-token');
                        tokenInput.select();
                        document.execCommand('copy');
                        $(this).html('<i class="fas fa-check"></i> Copied!');
                        setTimeout(function() {
                            $('#copy-token').html('<i class="fas fa-copy"></i> Copy');
                        }, 2000);
                    });
                    
                    // Set up payment tab click
                    $('#loadPaymentBtn').on('click', function() {
                        loadPaymentHistory(enrollmentId);
                    });
                    
                    // Payment tab click
                    $('#payment-tab').on('click', function() {
                        if ($('#paymentTabContent').find('.spinner-border').length === 0 && 
                            $('#paymentTabContent').find('.btn-primary').length > 0) {
                            loadPaymentHistory(enrollmentId);
                        }
                    });
                    
                    // Admin notes form submission
                    $('#adminNotesForm').on('submit', function(e) {
                        e.preventDefault();
                        var notes = $('#adminNotes').val();
                        
                        $.ajax({
                            url: 'ajax/update_enrollment_notes.php',
                            type: 'POST',
                            data: {
                                enrollment_id: enrollmentId,
                                notes: notes
                            },
                            dataType: 'json',
                            beforeSend: function() {
                                $('#adminNotesForm button').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...').prop('disabled', true);
                            },
                            success: function(response) {
                                if (response.success) {
                                    $('#adminNotesForm button').html('Saved!').addClass('btn-success').removeClass('btn-primary');
                                    setTimeout(function() {
                                        $('#adminNotesForm button').html('Save Notes').addClass('btn-primary').removeClass('btn-success').prop('disabled', false);
                                    }, 2000);
                                } else {
                                    alert('Failed to update notes: ' + response.message);
                                    $('#adminNotesForm button').html('Save Notes').prop('disabled', false);
                                }
                            },
                            error: function() {
                                alert('Failed to update notes due to a server error');
                                $('#adminNotesForm button').html('Save Notes').prop('disabled', false);
                            }
                        });
                    });
                } else {
                    $('#enrollment-details .modal-body').html('<div class="alert alert-danger">Error: ' + response.message + '</div>');
                }
            },
            error: function() {
                $('#enrollment-details .modal-body').html('<div class="alert alert-danger">Failed to load enrollment details. Please try again.</div>');
            }
        });
    });
    
    // Verify button click
    $('.verify-btn').on('click', function() {
        var enrollmentId = $(this).data('enrollment-id');
        var studentName = $(this).data('student-name');
        var courseTitle = $(this).data('course-title');
        var token = $(this).data('token');
        
        // Set modal content
        $('#enrollmentId').val(enrollmentId);
        $('#verifyStudentName').text(studentName);
        $('#verifyCourseTitle').text(courseTitle);
        $('#verification_token').val(token);
        
        // Get enrollment number asynchronously
        $.ajax({
            url: 'ajax/get_enrollment_details.php',
            type: 'GET',
            data: { enrollment_id: enrollmentId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#verifyEnrollmentNumber').text(response.data.enrollment_number || 'N/A');
                }
            }
        });
    });
    
    // Setup Mark Completed Modal
    $('.mark-completed-btn').click(function() {
        const enrollmentId = $(this).data('enrollment-id');
        const studentName = $(this).data('student-name');
        const courseTitle = $(this).data('course-title');
        
        $('#completeEnrollmentId').val(enrollmentId);
        $('#completeStudentName').text(studentName);
        $('#completeCourseTitle').text(courseTitle);
    });
    
    // Helper functions
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    
    function getStatusBadgeClass(status) {
        switch(status) {
            case 'active': return 'success';
            case 'pending': return 'warning';
            case 'completed': return 'info';
            case 'cancelled': return 'danger';
            default: return 'secondary';
        }
    }
});

// Add global function for loading payment history
window.loadPaymentHistory = function(enrollmentId) {
    if (!enrollmentId) return;
    
    $('#paymentTabContent').html('<div class="d-flex justify-content-center my-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>');
    
    $.ajax({
        url: 'ajax/get_payment_history.php',
        type: 'GET',
        data: { enrollment_id: enrollmentId },
        success: function(response) {
            $('#paymentTabContent').html(response);
        },
        error: function() {
            $('#paymentTabContent').html('<div class="alert alert-danger">Failed to load payment history. Please try again.</div>');
        }
    });
};
</script>

<?php
// Include footer
require_once 'includes/footer.php';
?>