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

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

// Check if enrollment ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo '<div class="alert alert-danger">Invalid enrollment ID.</div>';
    require_once 'includes/footer.php';
    exit;
}

$enrollment_id = intval($_GET['id']);

// Get enrollment details
$enrollment_query = "SELECT e.*, 
                    u.first_name, u.last_name, u.email, 
                    c.title as course_title, c.price, c.discount_price
                    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($enrollment_query);
$stmt->bind_param("i", $enrollment_id);
$stmt->execute();
$enrollment = $stmt->get_result()->fetch_assoc();

if (!$enrollment) {
    echo '<div class="alert alert-danger">Enrollment not found.</div>';
    require_once 'includes/footer.php';
    exit;
}

// Calculate total amount paid
$payments_query = "SELECT SUM(amount) as total_paid FROM payments WHERE user_id = ? AND course_id = ?";
$stmt = $conn->prepare($payments_query);
$stmt->bind_param("ii", $enrollment['user_id'], $enrollment['course_id']);
$stmt->execute();
$payment_result = $stmt->get_result()->fetch_assoc();
$total_paid = $payment_result['total_paid'] ?? 0;

// Get all payments
$all_payments_query = "SELECT * FROM payments 
                       WHERE user_id = ? AND course_id = ?
                       ORDER BY payment_date DESC";
$stmt = $conn->prepare($all_payments_query);
$stmt->bind_param("ii", $enrollment['user_id'], $enrollment['course_id']);
$stmt->execute();
$payments = $stmt->get_result();

// Calculate course price
$course_price = $enrollment['discount_price'] > 0 && $enrollment['discount_price'] < $enrollment['price'] 
                ? $enrollment['discount_price'] : $enrollment['price'];

// Calculate remaining amount
$remaining_amount = max(0, $course_price - $total_paid);

// Process new payment
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_payment'])) {
    $amount = floatval($_POST['amount']);
    $payment_method = $_POST['payment_method'];
    $transaction_id = $_POST['transaction_id'];
    $payment_details = $_POST['payment_details'];
    
    if ($amount <= 0) {
        $error_message = "Payment amount must be greater than zero.";
    } elseif (empty($transaction_id)) {
        $error_message = "Transaction ID is required.";
    } else {
        // Check if transaction ID already exists
        $check_query = "SELECT id FROM payments WHERE transaction_id = ?";
        $stmt = $conn->prepare($check_query);
        $stmt->bind_param("s", $transaction_id);
        $stmt->execute();
        
        if ($stmt->get_result()->num_rows > 0) {
            $error_message = "Transaction ID already exists. Please use a unique transaction ID.";
        } else {
            // Add payment
            $insert_query = "INSERT INTO payments (user_id, course_id, amount, payment_method, transaction_id, status, payment_details, payment_date, marked_by) 
                           VALUES (?, ?, ?, ?, ?, 'completed', ?, NOW(), ?)";
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("iidsssi", $enrollment['user_id'], $enrollment['course_id'], $amount, $payment_method, $transaction_id, $payment_details, $_SESSION['user_id']);
            
            if ($stmt->execute()) {
                $success_message = "Payment of ₹" . number_format($amount, 2) . " added successfully.";
                
                // Log the payment
                $log_message = "Payment of ₹" . number_format($amount, 2) . " added for enrollment #" . $enrollment_id;
                logger($_SESSION['user_id'], 'payment_added', $log_message);
                
                // Redirect to refresh the page
                header("Location: enrollment_payment.php?id=" . $enrollment_id . "&success=1");
                exit;
            } else {
                $error_message = "Failed to add payment: " . $conn->error;
            }
        }
    }
}

// Handle success message from redirect
if (isset($_GET['success']) && $_GET['success'] == '1') {
    $success_message = "Payment added successfully.";
}
?>

<!-- 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 Payments</h1>
        <a href="enrollments.php" class="d-none d-sm-inline-block btn btn-sm btn-secondary shadow-sm">
            <i class="fas fa-arrow-left fa-sm text-white-50"></i> Back to Enrollments
        </a>
    </div>

    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $success_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $error_message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- Enrollment Details 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 Details</h6>
            <span class="badge bg-<?php echo ($enrollment['status'] === 'active') ? 'success' : 
                                        (($enrollment['status'] === 'cancelled') ? 'danger' : 
                                        (($enrollment['status'] === 'completed') ? 'info' : 'warning')); ?>">
                <?php echo ucfirst($enrollment['status']); ?>
            </span>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h5 class="font-weight-bold">Student Information</h5>
                    <p><strong>Name:</strong> <?php echo htmlspecialchars($enrollment['first_name'] . ' ' . $enrollment['last_name']); ?></p>
                    <p><strong>Email:</strong> <?php echo htmlspecialchars($enrollment['email']); ?></p>
                    <p><strong>Enrollment Date:</strong> <?php echo date('M d, Y', strtotime($enrollment['enrollment_date'])); ?></p>
                </div>
                <div class="col-md-6">
                    <h5 class="font-weight-bold">Course Information</h5>
                    <p><strong>Course:</strong> <?php echo htmlspecialchars($enrollment['course_title']); ?></p>
                    <p><strong>Price:</strong> ₹<?php echo number_format($course_price, 2); ?></p>
                    <p><strong>Total Paid:</strong> ₹<?php echo number_format($total_paid, 2); ?></p>
                    <p><strong>Remaining:</strong> <span class="<?php echo ($remaining_amount > 0) ? 'text-danger' : 'text-success'; ?>">
                        ₹<?php echo number_format($remaining_amount, 2); ?>
                    </span></p>
                </div>
            </div>
            <div class="mt-3">
                <div class="progress" style="height: 25px;">
                    <?php 
                    $percentage_paid = ($course_price > 0) ? min(100, ($total_paid / $course_price) * 100) : 100;
                    ?>
                    <div class="progress-bar <?php echo ($percentage_paid < 100) ? 'bg-warning' : 'bg-success'; ?>" 
                         role="progressbar" 
                         style="width: <?php echo $percentage_paid; ?>%;" 
                         aria-valuenow="<?php echo $percentage_paid; ?>" 
                         aria-valuemin="0" 
                         aria-valuemax="100">
                        <?php echo number_format($percentage_paid, 0); ?>% Paid
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Content Row -->
    <div class="row">
        <!-- Add Payment Card -->
        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Add Payment</h6>
                </div>
                <div class="card-body">
                    <form method="post" action="">
                        <div class="mb-3">
                            <label for="amount" class="form-label">Amount (₹)</label>
                            <input type="number" class="form-control" id="amount" name="amount" step="0.01" min="0.01" 
                                  value="<?php echo $remaining_amount; ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="payment_method" class="form-label">Payment Method</label>
                            <select class="form-select" id="payment_method" name="payment_method" required>
                                <option value="">Select Method</option>
                                <option value="cash">Cash</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="upi">UPI</option>
                                <option value="check">Check/Cheque</option>
                                <option value="card">Credit/Debit Card</option>
                                <option value="online">Online Payment</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="transaction_id" class="form-label">Transaction ID</label>
                            <input type="text" class="form-control" id="transaction_id" name="transaction_id" required>
                            <small class="form-text text-muted">
                                Unique identifier for this payment. For cash payments, use receipt number or date-studentID.
                            </small>
                        </div>
                        
                        <div class="mb-3">
                            <label for="payment_details" class="form-label">Payment Details (Optional)</label>
                            <textarea class="form-control" id="payment_details" name="payment_details" rows="3"></textarea>
                        </div>
                        
                        <button type="submit" name="add_payment" class="btn btn-primary w-100">
                            <i class="fas fa-plus-circle mr-1"></i> Add Payment
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Payment History Card -->
        <div class="col-lg-8">
            <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">Payment History</h6>
                    <span class="badge bg-primary"><?php echo $payments->num_rows; ?> Payment(s)</span>
                </div>
                <div class="card-body">
                    <?php if ($payments->num_rows > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-bordered" id="paymentsTable" width="100%" cellspacing="0">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Amount</th>
                                    <th>Method</th>
                                    <th>Transaction ID</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($payment = $payments->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo date('M d, Y H:i', strtotime($payment['payment_date'])); ?></td>
                                    <td class="text-right">
                                        ₹<?php echo number_format($payment['amount'], 2); ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-info">
                                            <?php echo ucfirst($payment['payment_method']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small><?php echo htmlspecialchars($payment['transaction_id']); ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo ($payment['status'] === 'completed') ? 'success' : 
                                                (($payment['status'] === 'refunded') ? 'warning' : 'secondary'); 
                                        ?>">
                                            <?php echo ucfirst($payment['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-info payment-details" 
                                                data-payment-id="<?php echo $payment['id']; ?>"
                                                data-bs-toggle="modal" 
                                                data-bs-target="#paymentDetailsModal">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <?php if ($payment['status'] === 'completed'): ?>
                                        <button class="btn btn-sm btn-warning refund-payment" 
                                                data-payment-id="<?php echo $payment['id']; ?>"
                                                data-amount="<?php echo $payment['amount']; ?>"
                                                data-bs-toggle="modal" 
                                                data-bs-target="#refundModal">
                                            <i class="fas fa-undo"></i>
                                        </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i> No payments have been recorded for this enrollment.
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /.container-fluid -->

<!-- Payment Details Modal -->
<div class="modal fade" id="paymentDetailsModal" tabindex="-1" aria-labelledby="paymentDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="paymentDetailsModalLabel">Payment Details</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="paymentDetailsContent">
                    <div class="text-center p-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading payment details...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Refund Modal -->
<div class="modal fade" id="refundModal" tabindex="-1" aria-labelledby="refundModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h5 class="modal-title" id="refundModalLabel">Refund Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="refundForm" method="post" action="ajax/process_refund.php">
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle mr-2"></i> Are you sure you want to refund this payment?
                    </div>
                    
                    <input type="hidden" id="refundPaymentId" name="payment_id">
                    <input type="hidden" name="enrollment_id" value="<?php echo $enrollment_id; ?>">
                    
                    <div class="mb-3">
                        <label for="refundAmount" class="form-label">Refund Amount (₹)</label>
                        <input type="number" class="form-control" id="refundAmount" name="amount" step="0.01" min="0.01" required readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label for="refundReason" class="form-label">Reason for Refund</label>
                        <textarea class="form-control" id="refundReason" name="reason" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Process Refund</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Payment details modal
$(document).ready(function() {
    // Initialize DataTable
    $('#paymentsTable').DataTable({
        "order": [[0, "desc"]],
        "pageLength": 10
    });
    
    // Payment details click
    $('.payment-details').on('click', function() {
        var paymentId = $(this).data('payment-id');
        
        // Reset content
        $('#paymentDetailsContent').html('<div class="text-center p-4"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-2">Loading payment details...</p></div>');
        
        // Load payment details via AJAX
        $.ajax({
            url: 'ajax/get_payment_details.php',
            type: 'GET',
            data: { payment_id: paymentId },
            success: function(response) {
                $('#paymentDetailsContent').html(response);
            },
            error: function() {
                $('#paymentDetailsContent').html('<div class="alert alert-danger">Failed to load payment details.</div>');
            }
        });
    });
    
    // Refund payment click
    $('.refund-payment').on('click', function() {
        var paymentId = $(this).data('payment-id');
        var amount = $(this).data('amount');
        
        $('#refundPaymentId').val(paymentId);
        $('#refundAmount').val(amount);
    });
    
    // Form submission via AJAX
    $('#refundForm').on('submit', function(e) {
        e.preventDefault();
        
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            beforeSend: function() {
                $('#refundForm button[type="submit"]').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...').attr('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    // Hide modal
                    $('#refundModal').modal('hide');
                    
                    // Show success message and reload page
                    alert('Payment refunded successfully!');
                    window.location.reload();
                } else {
                    alert('Error: ' + response.message);
                    $('#refundForm button[type="submit"]').html('Process Refund').attr('disabled', false);
                }
            },
            error: function() {
                alert('An error occurred while processing your request.');
                $('#refundForm button[type="submit"]').html('Process Refund').attr('disabled', false);
            }
        });
    });
});
</script>

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