Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : /home/vishqocm//pcib.in/admin/enrollment_applications.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 actions
$success_message = '';
$error_message = '';

// Handle enrollment application updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_application'])) {
    $application_id = intval($_POST['application_id']);
    $status = $_POST['status'];
    $admin_notes = $_POST['admin_notes'] ?? '';
    
    // Update application status
    $update_query = "UPDATE enrollment_applications SET status = ?, admin_notes = ? WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("ssi", $status, $admin_notes, $application_id);
    
    if ($stmt->execute()) {
        $success_message = "Application status updated successfully.";
        
        // If status is 'completed', create enrollment record if it doesn't exist
        if ($status === 'completed') {
            // Get application details
            $app_query = "SELECT * FROM enrollment_applications WHERE id = ?";
            $stmt = $conn->prepare($app_query);
            $stmt->bind_param("i", $application_id);
            $stmt->execute();
            $app_result = $stmt->get_result();
            $application = $app_result->fetch_assoc();
            
            if ($application) {
                // Check if enrollment record exists
                $check_query = "SELECT * FROM enrollments WHERE user_id = ? AND course_id = ?";
                $stmt = $conn->prepare($check_query);
                $stmt->bind_param("ii", $application['user_id'], $application['course_id']);
                $stmt->execute();
                $check_result = $stmt->get_result();
                
                if ($check_result->num_rows === 0) {
                    // Create enrollment record
                    $enroll_query = "INSERT INTO enrollments (course_id, user_id, status, verification_token) 
                                    VALUES (?, ?, 'active', ?)";
                    $stmt = $conn->prepare($enroll_query);
                    $stmt->bind_param("iis", $application['course_id'], $application['user_id'], $application['verification_token']);
                    if ($stmt->execute()) {
                        $success_message .= " Enrollment created successfully.";
                    } else {
                        $error_message = "Failed to create enrollment record: " . $conn->error;
                    }
                } else {
                    $success_message .= " Student already enrolled in this course.";
                }
            }
        }
    } else {
        $error_message = "Failed to update application status: " . $conn->error;
    }
}

// Handle direct enrollment creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_enrollment'])) {
    $user_id = intval($_POST['user_id']);
    $course_id = intval($_POST['course_id']);
    $status = $_POST['status'] ?? 'active';
    
    // Generate a verification token
    $verification_token = bin2hex(random_bytes(16));
    
    // Check if enrollment already exists
    $check_query = "SELECT * FROM enrollments WHERE user_id = ? AND course_id = ?";
    $stmt = $conn->prepare($check_query);
    $stmt->bind_param("ii", $user_id, $course_id);
    $stmt->execute();
    $check_result = $stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        // Create enrollment record
        $enroll_query = "INSERT INTO enrollments (course_id, user_id, status, verification_token) 
                        VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($enroll_query);
        $stmt->bind_param("iiss", $course_id, $user_id, $status, $verification_token);
        
        if ($stmt->execute()) {
            $success_message = "Enrollment created successfully.";
        } else {
            $error_message = "Failed to create enrollment: " . $conn->error;
        }
    } else {
        $error_message = "Student is already enrolled in this course.";
    }
}

// Get all enrollment applications
$applications_query = "SELECT ea.*, u.first_name, u.last_name, u.email, c.title as course_title, c.price, c.discount_price,
                       (SELECT status FROM payments WHERE user_id = ea.user_id ORDER BY payment_date DESC LIMIT 1) as payment_status
                       FROM enrollment_applications ea
                       JOIN users u ON ea.user_id = u.id
                       JOIN courses c ON ea.course_id = c.id
                       ORDER BY ea.application_date DESC";
$applications_result = $conn->query($applications_query);

// Get all active enrollments
$enrollments_query = "SELECT e.*, u.first_name, u.last_name, u.email, 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
                      ORDER BY e.id DESC";
$enrollments_result = $conn->query($enrollments_query);

// Get all users who can be enrolled
$users_query = "SELECT id, username, first_name, last_name, email FROM users WHERE role = 'student' ORDER BY first_name";
$users_result = $conn->query($users_query);

// Get all courses
$courses_query = "SELECT id, title FROM courses ORDER BY title";
$courses_result = $conn->query($courses_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>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#createEnrollmentModal">
            <i class="fas fa-plus"></i> Create Enrollment
        </button>
    </div>
    
    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show"><?php echo $success_message; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show"><?php echo $error_message; ?>
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    <?php endif; ?>

    <!-- Content Row -->
    <div class="row">
        <div class="col-12">
            <!-- Enrollment Applications Card -->
            <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">Enrollment Applications</h6>
                    <div class="dropdown no-arrow">
                        <a class="dropdown-toggle" href="#" role="button" id="applicationsDropdown"
                           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="applicationsDropdown">
                            <div class="dropdown-header">Filter Applications:</div>
                            <a class="dropdown-item filter-app-status" href="#" data-status="all">All Applications</a>
                            <a class="dropdown-item filter-app-status" href="#" data-status="pending">Pending</a>
                            <a class="dropdown-item filter-app-status" href="#" data-status="payment_pending">Payment Pending</a>
                            <a class="dropdown-item filter-app-status" href="#" data-status="completed">Completed</a>
                            <a class="dropdown-item filter-app-status" href="#" data-status="rejected">Rejected</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="applicationsTable" width="100%" cellspacing="0">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Student</th>
                                    <th>Course</th>
                                    <th>Applied On</th>
                                    <th>Status</th>
                                    <th>Payment</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($applications_result && $applications_result->num_rows > 0): ?>
                                    <?php while ($row = $applications_result->fetch_assoc()): ?>
                                        <tr class="application-row" data-status="<?php echo $row['status']; ?>">
                                            <td><?php echo $row['id']; ?></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['application_date'])); ?></td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo ($row['status'] === 'completed') ? 'success' : 
                                                        (($row['status'] === 'rejected') ? 'danger' : 
                                                        (($row['status'] === 'payment_pending') ? 'info' : 'warning')); 
                                                ?>">
                                                    <?php echo ucwords(str_replace('_', ' ', $row['status'])); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($row['payment_status']): ?>
                                                    <span class="badge badge-<?php 
                                                        echo ($row['payment_status'] === 'completed') ? 'success' : 
                                                            (($row['payment_status'] === 'failed') ? 'danger' : 'warning'); 
                                                    ?>">
                                                        <?php echo ucfirst($row['payment_status']); ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge badge-secondary">Not Paid</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button type="button" class="btn btn-primary" 
                                                            data-toggle="modal" 
                                                            data-target="#viewApplicationModal"
                                                            data-application-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-personal-details="<?php echo htmlspecialchars($row['personal_details'] ?? ''); ?>"
                                                            data-verification-token="<?php echo $row['verification_token']; ?>"
                                                            data-status="<?php echo $row['status']; ?>"
                                                            data-notes="<?php echo htmlspecialchars($row['admin_notes'] ?? ''); ?>">
                                                        <i class="fas fa-edit"></i> Manage
                                                    </button>
                                                    <?php if ($row['status'] === 'pending' || $row['status'] === 'payment_pending'): ?>
                                                    <button type="button" class="btn btn-success quick-approve-btn"
                                                            data-application-id="<?php echo $row['id']; ?>"
                                                            data-student-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>">
                                                        <i class="fas fa-check"></i> Approve
                                                    </button>
                                                    <?php endif; ?>
                                                    <a href="payments.php?user_id=<?php echo $row['user_id']; ?>" class="btn btn-info">
                                                        <i class="fas fa-money-bill"></i> Payments
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center">No applications found</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Active Enrollments Card -->
            <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">Active Enrollments</h6>
                    <div class="dropdown no-arrow">
                        <a class="dropdown-toggle" href="#" role="button" id="enrollmentsDropdown"
                           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="enrollmentsDropdown">
                            <div class="dropdown-header">Filter Enrollments:</div>
                            <a class="dropdown-item filter-enroll-status" href="#" data-status="all">All Enrollments</a>
                            <a class="dropdown-item filter-enroll-status" href="#" data-status="active">Active</a>
                            <a class="dropdown-item filter-enroll-status" href="#" data-status="completed">Completed</a>
                            <a class="dropdown-item filter-enroll-status" href="#" data-status="suspended">Suspended</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>Student</th>
                                    <th>Course</th>
                                    <th>Status</th>
                                    <th>Enrolled On</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($enrollments_result && $enrollments_result->num_rows > 0): ?>
                                    <?php while ($row = $enrollments_result->fetch_assoc()): ?>
                                        <tr class="enrollment-row" data-status="<?php echo $row['status']; ?>">
                                            <td><?php echo $row['id']; ?></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']); ?></td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo ($row['status'] === 'active') ? 'success' : 
                                                        (($row['status'] === 'suspended') ? 'danger' : 'info'); 
                                                ?>">
                                                    <?php echo ucfirst($row['status']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo isset($row['enrolled_date']) ? date('M d, Y', strtotime($row['enrolled_date'])) : 'N/A'; ?></td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button type="button" class="btn btn-primary enrollment-action-btn" 
                                                            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-status="<?php echo $row['status']; ?>">
                                                        <i class="fas fa-edit"></i> Manage
                                                    </button>
                                                    <?php if ($row['status'] !== 'active'): ?>
                                                    <button type="button" class="btn btn-success quick-activate-btn"
                                                            data-enrollment-id="<?php echo $row['id']; ?>"
                                                            data-student-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>">
                                                        <i class="fas fa-check"></i> Activate
                                                    </button>
                                                    <?php endif; ?>
                                                    <?php if ($row['status'] !== 'suspended'): ?>
                                                    <button type="button" class="btn btn-warning quick-suspend-btn"
                                                            data-enrollment-id="<?php echo $row['id']; ?>"
                                                            data-student-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>">
                                                        <i class="fas fa-pause"></i> Suspend
                                                    </button>
                                                    <?php endif; ?>
                                                    <a href="../course.php?id=<?php echo $row['course_id']; ?>" target="_blank" class="btn btn-info">
                                                        <i class="fas fa-eye"></i> View Course
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="6" class="text-center">No enrollments found</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View/Manage Application Modal -->
<div class="modal fade" id="viewApplicationModal" tabindex="-1" role="dialog" 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">Manage Application</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" action="">
                <div class="modal-body">
                    <input type="hidden" name="application_id" id="app_id">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <h6 class="font-weight-bold">Student:</h6>
                            <p id="app_student_name"></p>
                        </div>
                        <div class="col-md-6">
                            <h6 class="font-weight-bold">Course:</h6>
                            <p id="app_course_title"></p>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="app_status" class="font-weight-bold">Application Status:</label>
                        <select class="form-control" name="status" id="app_status">
                            <option value="pending">Pending</option>
                            <option value="payment_pending">Payment Pending</option>
                            <option value="completed">Completed</option>
                            <option value="rejected">Rejected</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="app_admin_notes" class="font-weight-bold">Admin Notes:</label>
                        <textarea class="form-control" name="admin_notes" id="app_admin_notes" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">Verification Token:</label>
                        <div class="bg-light p-2 rounded border">
                            <code id="app_verification_token" class="font-weight-bold"></code>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">Personal Details:</label>
                        <div id="app_personal_details_container" class="bg-light p-3 rounded border">
                            <!-- Personal details will be populated by JavaScript -->
                        </div>
                    </div>
                    
                    <!-- Document Section -->
                    <div class="form-group">
                        <label class="font-weight-bold">Student Documents:</label>
                        <div id="documentsList" class="border rounded p-3">
                            <div class="text-center my-2">
                                <i>Documents will load here when available</i>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Section -->
                    <div class="form-group">
                        <label class="font-weight-bold">Payment Information:</label>
                        <div id="paymentInfo" class="border rounded p-3">
                            <div class="text-center my-2">
                                <i>Payment details will load here when available</i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary" name="update_application">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create Enrollment Modal -->
<div class="modal fade" id="createEnrollmentModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Create New Enrollment</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" action="">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="user_id" class="font-weight-bold">Student:</label>
                        <select class="form-control" name="user_id" id="user_id" required>
                            <option value="">Select Student</option>
                            <?php if ($users_result && $users_result->num_rows > 0): 
                                while ($user = $users_result->fetch_assoc()): ?>
                                <option value="<?php echo $user['id']; ?>">
                                    <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name'] . ' (' . $user['email'] . ')'); ?>
                                </option>
                            <?php endwhile; endif; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="course_id" class="font-weight-bold">Course:</label>
                        <select class="form-control" name="course_id" id="course_id" required>
                            <option value="">Select Course</option>
                            <?php if ($courses_result && $courses_result->num_rows > 0): 
                                while ($course = $courses_result->fetch_assoc()): ?>
                                <option value="<?php echo $course['id']; ?>">
                                    <?php echo htmlspecialchars($course['title']); ?>
                                </option>
                            <?php endwhile; endif; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="enrollment_status" class="font-weight-bold">Status:</label>
                        <select class="form-control" name="status" id="enrollment_status">
                            <option value="active">Active</option>
                            <option value="pending">Pending</option>
                            <option value="suspended">Suspended</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" name="create_enrollment">Create Enrollment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create a new modal for managing enrollments -->
<!-- Manage Enrollment Modal -->
<div class="modal fade" id="manageEnrollmentModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Manage Enrollment</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="post" id="manage-enrollment-form">
                <div class="modal-body">
                    <input type="hidden" name="enrollment_id" id="manage_enrollment_id">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <h6 class="font-weight-bold">Student:</h6>
                            <p id="manage_student_name"></p>
                        </div>
                        <div class="col-md-6">
                            <h6 class="font-weight-bold">Course:</h6>
                            <p id="manage_course_title"></p>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="manage_status" class="font-weight-bold">Enrollment Status:</label>
                        <select class="form-control" name="status" id="manage_status">
                            <option value="active">Active</option>
                            <option value="pending">Pending</option>
                            <option value="suspended">Suspended</option>
                            <option value="completed">Completed</option>
                        </select>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-1"></i> 
                        Changing the enrollment status affects the student's access to the course.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="save-enrollment-status">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create a new modal for uploading documents -->
<!-- Upload Document Modal -->
<div class="modal fade" id="uploadDocumentModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Upload Document for Student</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="uploadDocumentForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="upload_user_id">
                    
                    <div class="form-group">
                        <label for="document_type" class="font-weight-bold">Document Type <span class="text-danger">*</span></label>
                        <select class="form-control" name="document_type" id="document_type" required>
                            <option value="">Select Document Type</option>
                            <option value="id_proof">ID Proof</option>
                            <option value="educational_certificate">Educational Certificate</option>
                            <option value="photograph">Photograph</option>
                            <option value="address_proof">Address Proof</option>
                            <option value="other">Other Document</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="document_description" class="font-weight-bold">Document Description</label>
                        <input type="text" class="form-control" name="document_description" id="document_description" placeholder="E.g., 'Aadhar Card', 'High School Certificate'">
                    </div>
                    
                    <div class="form-group">
                        <label for="document_file" class="font-weight-bold">Document File <span class="text-danger">*</span></label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" name="document_file" id="document_file" required>
                            <label class="custom-file-label" for="document_file">Choose file</label>
                        </div>
                        <small class="form-text text-muted">Allowed formats: JPG, PNG, GIF, PDF, DOC, DOCX. Max size: 5MB</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="document_status" class="font-weight-bold">Status</label>
                        <select class="form-control" name="status" id="document_status">
                            <option value="pending">Pending Verification</option>
                            <option value="verified">Verified</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_notes" class="font-weight-bold">Admin Notes</label>
                        <textarea class="form-control" name="admin_notes" id="admin_notes" rows="2" placeholder="Any notes about this document"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="uploadDocumentBtn">Upload Document</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTables
    $('#applicationsTable').DataTable({
        "order": [[0, "desc"]]
    });
    
    $('#enrollmentsTable').DataTable({
        "order": [[0, "desc"]]
    });
    
    // Filter applications by status
    $('.filter-app-status').click(function(e) {
        e.preventDefault();
        var status = $(this).data('status');
        
        if (status === 'all') {
            $('.application-row').show();
        } else {
            $('.application-row').hide();
            $('.application-row[data-status="' + status + '"]').show();
        }
    });
    
    // Filter enrollments by status
    $('.filter-enroll-status').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();
        }
    });
    
    // Populate application modal
    $('#viewApplicationModal').on('show.bs.modal', function(e) {
        var button = $(e.relatedTarget);
        var applicationId = button.data('application-id');
        var studentName = button.data('student-name');
        var courseTitle = button.data('course-title');
        var personalDetails = button.data('personal-details');
        var verificationToken = button.data('verification-token');
        var status = button.data('status');
        var notes = button.data('notes');
        
        $('#app_id').val(applicationId);
        $('#app_student_name').text(studentName);
        $('#app_course_title').text(courseTitle);
        $('#app_verification_token').text(verificationToken);
        $('#app_status').val(status);
        $('#app_admin_notes').val(notes);
        
        // Parse and display personal details
        var detailsContainer = $('#app_personal_details_container');
        detailsContainer.empty();
        
        try {
            var details = JSON.parse(personalDetails);
            var detailsHtml = '<dl class="row mb-0">';
            
            for (var key in details) {
                if (details.hasOwnProperty(key)) {
                    var label = key.replace(/_/g, ' ');
                    label = label.charAt(0).toUpperCase() + label.slice(1);
                    detailsHtml += '<dt class="col-sm-4">' + label + ':</dt>';
                    detailsHtml += '<dd class="col-sm-8">' + details[key] + '</dd>';
                }
            }
            
            detailsHtml += '</dl>';
            detailsContainer.html(detailsHtml);
        } catch (e) {
            detailsContainer.html('<p class="text-muted mb-0">No personal details available</p>');
        }
        
        // Load student documents
        loadDocuments(applicationId);
        
        // Load payment information
        loadPaymentInfo(applicationId);
    });
    
    // Modify application status form to use AJAX
    $('#viewApplicationModal form').submit(function(e) {
        e.preventDefault();
        
        var applicationId = $('#app_id').val();
        var status = $('#app_status').val();
        var adminNotes = $('#app_admin_notes').val();
        
        // Validate inputs
        if (!applicationId || !status) {
            showNotification('Invalid input data. Please check your form.', 'error');
            return false;
        }
        
        // Confirm major status changes
        if ((status === 'completed' || status === 'rejected') && !confirm('Are you sure you want to mark this application as ' + status + '?')) {
            return false;
        }
        
        // Disable submit button and show loading
        var submitBtn = $(this).find('button[type="submit"]');
        var originalBtnText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Saving...');
        submitBtn.prop('disabled', true);
        
        // Show processing overlay
        if ($('#processingOverlay').length === 0) {
            $('body').append('<div id="processingOverlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;"><div class="bg-white p-4 rounded"><i class="fas fa-spinner fa-spin fa-3x mb-3"></i><p class="mb-0">Processing your request...</p></div></div>');
        } else {
            $('#processingOverlay').show();
        }
        
        // Send AJAX request
        $.ajax({
            url: 'ajax/update_application_status.php',
            type: 'POST',
            data: {
                application_id: applicationId,
                status: status,
                admin_notes: adminNotes
            },
            success: function(response) {
                $('#processingOverlay').hide();
                
                if (response === 'success') {
                    // Show success message and reload the page
                    $('#viewApplicationModal').modal('hide');
                    showNotification('Application status updated successfully');
                    refreshPage();
                } else {
                    // Show error message
                    showNotification('Error: ' + response, 'error');
                    submitBtn.html(originalBtnText);
                    submitBtn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                $('#processingOverlay').hide();
                showNotification('Server error occurred: ' + (xhr.responseText || error), 'error');
                submitBtn.html(originalBtnText);
                submitBtn.prop('disabled', false);
            }
        });
    });
    
    // Populate enrollment management modal
    $('.enrollment-action-btn').click(function() {
        var enrollmentId = $(this).data('enrollment-id');
        var studentName = $(this).data('student-name');
        var courseTitle = $(this).data('course-title');
        var status = $(this).data('status');
        
        if (!enrollmentId) {
            alert('Error: Invalid enrollment ID');
            return;
        }
        
        $('#manage_enrollment_id').val(enrollmentId);
        $('#manage_student_name').text(studentName);
        $('#manage_course_title').text(courseTitle);
        $('#manage_status').val(status);
        
        $('#manageEnrollmentModal').modal('show');
    });
    
    // Handle enrollment status update
    $('#save-enrollment-status').click(function() {
        var enrollmentId = $('#manage_enrollment_id').val();
        var status = $('#manage_status').val();
        
        if (!enrollmentId) {
            showNotification('Error: Invalid enrollment ID', 'error');
            return;
        }
        
        // Confirm major status changes
        if ((status === 'completed' || status === 'suspended') && !confirm('Are you sure you want to change this enrollment status to ' + status + '?')) {
            return;
        }
        
        // Show loading state
        var btn = $(this);
        var originalText = btn.html();
        btn.html('<i class="fas fa-spinner fa-spin"></i> Saving...');
        btn.prop('disabled', true);
        
        // Show processing overlay
        if ($('#processingOverlay').length === 0) {
            $('body').append('<div id="processingOverlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;"><div class="bg-white p-4 rounded"><i class="fas fa-spinner fa-spin fa-3x mb-3"></i><p class="mb-0">Processing your request...</p></div></div>');
        } else {
            $('#processingOverlay').show();
        }
        
        // AJAX call to update enrollment status
        $.ajax({
            url: 'ajax/update_enrollment_status.php',
            type: 'POST',
            data: {
                enrollment_id: enrollmentId,
                status: status
            },
            success: function(response) {
                $('#processingOverlay').hide();
                
                if (response === 'success') {
                    // Close modal and reload page
                    $('#manageEnrollmentModal').modal('hide');
                    showNotification('Enrollment status updated successfully');
                    refreshPage();
                } else {
                    showNotification('Error: ' + response, 'error');
                    btn.html(originalText);
                    btn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                $('#processingOverlay').hide();
                showNotification('Server error: ' + (xhr.responseText || error), 'error');
                btn.html(originalText);
                btn.prop('disabled', false);
            }
        });
    });
    
    // Quick approve button for applications
    $('.quick-approve-btn').click(function() {
        var applicationId = $(this).data('application-id');
        var studentName = $(this).data('student-name');
        
        if (!applicationId) {
            showNotification('Error: Invalid application ID', 'error');
            return;
        }
        
        // Use SweetAlert if available for better UX
        if (typeof Swal !== "undefined") {
            Swal.fire({
                title: 'Approve Application',
                html: 'Are you sure you want to approve this application' + 
                      (studentName ? ' for <strong>' + studentName + '</strong>' : '') + '?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, approve it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    processQuickAction(applicationId, $(this), 'application');
                }
            });
        } else if (confirm('Are you sure you want to approve this application?')) {
            processQuickAction(applicationId, $(this), 'application');
        }
    });
    
    // Quick activate button for enrollments
    $('.quick-activate-btn').click(function() {
        var enrollmentId = $(this).data('enrollment-id');
        var studentName = $(this).data('student-name');
        
        if (!enrollmentId) {
            showNotification('Error: Invalid enrollment ID', 'error');
            return;
        }
        
        // Use SweetAlert if available
        if (typeof Swal !== "undefined") {
            Swal.fire({
                title: 'Activate Enrollment',
                html: 'Are you sure you want to activate this enrollment' + 
                      (studentName ? ' for <strong>' + studentName + '</strong>' : '') + '?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, activate it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    processQuickAction(enrollmentId, $(this), 'enrollment', 'active');
                }
            });
        } else if (confirm('Are you sure you want to activate this enrollment?')) {
            processQuickAction(enrollmentId, $(this), 'enrollment', 'active');
        }
    });
    
    // Quick suspend button for enrollments
    $('.quick-suspend-btn').click(function() {
        var enrollmentId = $(this).data('enrollment-id');
        var studentName = $(this).data('student-name');
        
        if (!enrollmentId) {
            showNotification('Error: Invalid enrollment ID', 'error');
            return;
        }
        
        // Use SweetAlert if available
        if (typeof Swal !== "undefined") {
            Swal.fire({
                title: 'Suspend Enrollment',
                html: 'Are you sure you want to suspend this enrollment' + 
                      (studentName ? ' for <strong>' + studentName + '</strong>' : '') + '?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, suspend it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    processQuickAction(enrollmentId, $(this), 'enrollment', 'suspended');
                }
            });
        } else if (confirm('Are you sure you want to suspend this enrollment?')) {
            processQuickAction(enrollmentId, $(this), 'enrollment', 'suspended');
        }
    });
    
    // Function to handle quick actions
    function processQuickAction(id, btn, type, status) {
        var originalHtml = btn.html();
        var url, data;
        
        // Configure based on action type
        if (type === 'application') {
            url = 'ajax/update_application_status.php';
            data = {
                application_id: id,
                status: 'completed',
                admin_notes: 'Automatically approved by admin'
            };
        } else if (type === 'enrollment') {
            url = 'ajax/update_enrollment_status.php';
            data = {
                enrollment_id: id,
                status: status
            };
        } else {
            showNotification('Unknown action type', 'error');
            return;
        }
        
        // Show loading state
        btn.html('<i class="fas fa-spinner fa-spin"></i>');
        btn.prop('disabled', true);
        
        // Show processing overlay
        if ($('#processingOverlay').length === 0) {
            $('body').append('<div id="processingOverlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;"><div class="bg-white p-4 rounded"><i class="fas fa-spinner fa-spin fa-3x mb-3"></i><p class="mb-0">Processing your request...</p></div></div>');
        } else {
            $('#processingOverlay').show();
        }
        
        // Send AJAX request
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            success: function(response) {
                $('#processingOverlay').hide();
                
                if (response === 'success') {
                    showNotification(
                        type === 'application' ? 'Application approved successfully!' : 
                        'Enrollment ' + status + ' successfully!'
                    );
                    refreshPage();
                } else {
                    showNotification('Error: ' + response, 'error');
                    btn.html(originalHtml);
                    btn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                $('#processingOverlay').hide();
                showNotification('Server error: ' + (xhr.responseText || error), 'error');
                btn.html(originalHtml);
                btn.prop('disabled', false);
            }
        });
    }
    
    // Global functions for document and payment loading
    window.loadDocuments = function(applicationId) {
        if (!applicationId) return;
        
        $('#documentsList').html('<div class="text-center my-3"><i class="fas fa-spinner fa-spin fa-2x"></i><p class="mt-2">Loading documents...</p></div>');
        
        $.ajax({
            url: 'ajax/get_student_documents.php',
            type: 'GET',
            data: { application_id: applicationId },
            success: function(response) {
                $('#documentsList').html(response);
                // Initialize tooltips
                $('[data-toggle="tooltip"]').tooltip();
            },
            error: function() {
                $('#documentsList').html('<div class="alert alert-danger">Failed to load documents</div>');
            }
        });
    };
    
    window.loadPaymentInfo = function(applicationId) {
        if (!applicationId) return;
        
        $('#paymentInfo').html('<div class="text-center my-3"><i class="fas fa-spinner fa-spin fa-2x"></i><p class="mt-2">Loading payment info...</p></div>');
        
        $.ajax({
            url: 'ajax/get_payment_info.php',
            type: 'GET',
            data: { application_id: applicationId },
            success: function(response) {
                $('#paymentInfo').html(response);
            },
            error: function() {
                $('#paymentInfo').html('<div class="alert alert-danger">Failed to load payment information</div>');
            }
        });
    };
    
    // Function to refresh the page with optional delay
    window.refreshPage = function(delay = 1000) {
        setTimeout(function() {
            location.reload();
        }, delay);
    };
    
    // Global function to show status updates
    window.showNotification = function(message, type = 'success') {
        if (typeof toastr !== "undefined") {
            toastr[type](message);
        } else if (typeof Swal !== "undefined") {
            Swal.fire({
                title: type.charAt(0).toUpperCase() + type.slice(1),
                text: message,
                icon: type,
                timer: 2000,
                showConfirmButton: false
            });
        } else {
            alert(message);
        }
    };
    
    // Handle file input change to display filename
    $(document).on('change', '.custom-file-input', function() {
        var fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').html(fileName);
    });
    
    // Initialize Upload Document Modal
    $('#uploadDocumentModal').on('show.bs.modal', function(e) {
        var button = $(e.relatedTarget);
        var userId = button.data('user-id');
        
        $('#upload_user_id').val(userId);
        $('#uploadDocumentForm').trigger('reset');
        $('.custom-file-label').html('Choose file');
    });
    
    // Handle document upload form submission
    $('#uploadDocumentForm').submit(function(e) {
        e.preventDefault();
        
        // Validate form
        if (!this.checkValidity()) {
            e.stopPropagation();
            $(this).addClass('was-validated');
            return;
        }
        
        // Create form data
        var formData = new FormData(this);
        
        // Disable submit button and show loading
        var submitBtn = $('#uploadDocumentBtn');
        var originalBtnText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Uploading...');
        submitBtn.prop('disabled', true);
        
        // Show processing overlay
        if ($('#processingOverlay').length === 0) {
            $('body').append('<div id="processingOverlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;"><div class="bg-white p-4 rounded"><i class="fas fa-spinner fa-spin fa-3x mb-3"></i><p class="mb-0">Uploading document...</p></div></div>');
        } else {
            $('#processingOverlay').show();
        }
        
        // Send AJAX request
        $.ajax({
            url: 'ajax/upload_document.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                $('#processingOverlay').hide();
                
                try {
                    var data = JSON.parse(response);
                    
                    if (data.status === 'success') {
                        // Close modal and show success message
                        $('#uploadDocumentModal').modal('hide');
                        
                        if (typeof Swal !== "undefined") {
                            Swal.fire({
                                title: 'Success!',
                                text: data.message,
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else if (typeof toastr !== "undefined") {
                            toastr.success(data.message);
                        } else {
                            alert(data.message);
                        }
                        
                        // Reload documents if application modal is open
                        var applicationId = $('#app_id').val();
                        if (applicationId) {
                            loadDocuments(applicationId);
                        }
                    } else {
                        // Show error message
                        if (typeof Swal !== "undefined") {
                            Swal.fire('Error', data.message, 'error');
                        } else if (typeof toastr !== "undefined") {
                            toastr.error(data.message);
                        } else {
                            alert('Error: ' + data.message);
                        }
                        
                        submitBtn.html(originalBtnText);
                        submitBtn.prop('disabled', false);
                    }
                } catch (e) {
                    // Show error for invalid JSON
                    if (typeof toastr !== "undefined") {
                        toastr.error('Invalid response from server');
                    } else {
                        alert('Invalid response from server');
                    }
                    
                    submitBtn.html(originalBtnText);
                    submitBtn.prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                $('#processingOverlay').hide();
                
                if (typeof toastr !== "undefined") {
                    toastr.error('Server error: ' + error);
                } else {
                    alert('Server error: ' + error);
                }
                
                submitBtn.html(originalBtnText);
                submitBtn.prop('disabled', false);
            }
        });
    });
});
</script>

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