Path : /home/vishqocm/pcib.in/student/
File Upload :
Current File : /home/vishqocm/pcib.in/student/certificate_payment.php

<?php
$pageTitle = "Certificate Payment";
include_once('includes/header.php');

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    header("Location: ../login.php");
    exit();
}

// Get student ID
$student_id = $_SESSION['user_id'];

// Get parameters from URL
$course_id = isset($_GET['course_id']) ? intval($_GET['course_id']) : 0;
$amount = isset($_GET['amount']) ? floatval($_GET['amount']) : 0;
$cert_id = isset($_GET['cert_id']) ? intval($_GET['cert_id']) : 0;

// Validate parameters
if ($course_id == 0 || $amount == 0 || $cert_id == 0) {
    $_SESSION['error_message'] = "Invalid payment parameters";
    header("Location: certificates.php");
    exit();
}

// Get course information
$course_query = "SELECT title FROM courses WHERE id = ?";
$stmt = $conn->prepare($course_query);
$stmt->bind_param("i", $course_id);
$stmt->execute();
$course_result = $stmt->get_result();

if ($course_result->num_rows == 0) {
    $_SESSION['error_message'] = "Course not found";
    header("Location: certificates.php");
    exit();
}

$course = $course_result->fetch_assoc();
$course_name = $course['title'];

// Get certificate information
$cert_query = "SELECT certificate_number FROM unified_certificates WHERE id = ? AND user_id = ?";
$stmt = $conn->prepare($cert_query);
$stmt->bind_param("ii", $cert_id, $student_id);
$stmt->execute();
$cert_result = $stmt->get_result();

if ($cert_result->num_rows == 0) {
    $_SESSION['error_message'] = "Certificate not found";
    header("Location: certificates.php");
    exit();
}

$cert = $cert_result->fetch_assoc();
$certificate_number = $cert['certificate_number'];

// Get student information
$student_query = "SELECT first_name, last_name, email, phone FROM users WHERE id = ?";
$stmt = $conn->prepare($student_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student_result = $stmt->get_result();
$student = $student_result->fetch_assoc();

// Razorpay Configuration
$razorpay_key_id = "rzp_test_fIHlD0EzBUuvzc"; // Replace with your actual Razorpay Key ID in production
$razorpay_key_secret = "YI15P7Cf7NoFMIewK3i5QKV2"; // Replace with your actual Razorpay Key Secret in production

// Get settings from database if available
$settings_query = "SELECT * FROM site_settings WHERE setting_key IN ('razorpay_key_id', 'razorpay_key_secret', 'institute_name')";
$settings_result = $conn->query($settings_query);
$settings = [];

if ($settings_result) {
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}

// Use settings from database if available
$razorpay_key_id = $settings['razorpay_key_id'] ?? $razorpay_key_id;
$institute_name = $settings['institute_name'] ?? "Popular Computer Institute";

// Generate unique receipt ID
$receipt_id = "PCIB" . date("YmdHis") . rand(100, 999);

// Create Razorpay Order - Required for API v2
$api_url = 'https://api.razorpay.com/v1/orders';
$amount_in_paisa = $amount * 100; // Convert to paisa

// API credentials
$auth = base64_encode($razorpay_key_id . ':' . $razorpay_key_secret);

// Prepare order data
$order_data = array(
    'amount' => $amount_in_paisa,
    'currency' => 'INR',
    'receipt' => $receipt_id,
    'notes' => array(
        'certificate_id' => $cert_id,
        'course_id' => $course_id,
        'student_id' => $student_id
    )
);

// Create cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic ' . $auth,
    'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($order_data));

// Execute cURL session
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Check for errors
if ($http_status != 200) {
    error_log('Razorpay Order API Error: ' . $response);
    $error_message = "Payment gateway error. Please try again later.";
    $order_id = null;
} else {
    // Process response
    $order_data = json_decode($response, true);
    $order_id = $order_data['id'];
}

curl_close($ch);

// Check if order was created successfully
if (!$order_id) {
    $error_message = "Failed to create payment order. Please try again later.";
}

// Razorpay Options - These will be passed to the Razorpay checkout
$razorpay_options = array(
    "key" => $razorpay_key_id,
    "amount" => $amount * 100, // Razorpay amount is in paisa (multiply by 100)
    "currency" => "INR",
    "name" => $institute_name,
    "description" => "Certificate Fee for " . $course_name,
    "image" => "../assets/img/logo.png",
    "prefill" => array(
        "name" => $student['first_name'] . ' ' . $student['last_name'],
        "email" => $student['email'],
        "contact" => $student['phone'] ?? ""
    ),
    "notes" => array(
        "certificate_id" => $cert_id,
        "certificate_number" => $certificate_number,
        "course_id" => $course_id,
        "student_id" => $student_id
    ),
    "theme" => array(
        "color" => "#4e73df"
    ),
    "order_id" => $order_id,
    "callback_url" => "payment_callback.php?cert_id=$cert_id&course_id=$course_id&amount=$amount&payment_for=Certificate+Fee&receipt=$receipt_id",
    "redirect" => true
);

// If form submitted, process the payment
$success_message = "";
$error_message = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['payment_method'])) {
    $payment_method = $_POST['payment_method'];
    $payment_note = isset($_POST['payment_note']) ? $_POST['payment_note'] : '';
    
    // Setup common data for both payment methods
    $transaction_id = "TXN" . date("YmdHis") . rand(1000, 9999);
    $payment_details = "Certificate Payment for " . $course_name;
    
    // Handle different payment methods
    if ($payment_method === 'razorpay') {
        // For Razorpay online payment
        // In a real implementation, you would integrate with Razorpay API here
        // For demo, we'll simulate a successful online payment
        
        $payment_status = "completed";
        $payment_details .= " (Online Payment via Razorpay)";
        
        // Insert payment record
        $payment_query = "INSERT INTO payments 
                        (user_id, course_id, amount, payment_method, transaction_id, 
                         status) 
                        VALUES (?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($payment_query);
        $stmt->bind_param("iidsss", $student_id, $course_id, $amount, $payment_method, 
                         $transaction_id, $payment_status);
    
    if ($stmt->execute()) {
        // Update certificate payment status
        $update_cert = "UPDATE unified_certificates 
                       SET payment_status = 'completed', payment_date = NOW(), 
                           payment_reference = ? 
                       WHERE id = ? AND user_id = ?";
        
        $stmt = $conn->prepare($update_cert);
        $stmt->bind_param("sii", $transaction_id, $cert_id, $student_id);
        
        if ($stmt->execute()) {
                $_SESSION['success_message'] = "Online payment completed successfully. Your certificate is now available for download.";
            header("Location: certificates.php?payment_complete=1&cert_id=" . $cert_id);
            exit();
        } else {
            $error_message = "Payment was successful but there was an error updating certificate status.";
        }
    } else {
            $error_message = "Error processing online payment. Please try again.";
        }
    } else if ($payment_method === 'cash') {
        // For cash payment at institute
        $payment_status = "pending"; // For cash payments, status starts as pending
        $payment_details .= " (Cash Payment at Institute)";
        if (!empty($payment_note)) {
            $payment_details .= " Note: " . $payment_note;
        }
        
        // Insert payment record
        $payment_query = "INSERT INTO payments 
                        (user_id, course_id, amount, payment_method, transaction_id, 
                         status) 
                        VALUES (?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($payment_query);
        $stmt->bind_param("iidsss", $student_id, $course_id, $amount, $payment_method, 
                         $transaction_id, $payment_status);
        
        if ($stmt->execute()) {
            // For cash payment, mark certificate as "verification_pending"
            $update_cert = "UPDATE unified_certificates 
                           SET payment_status = 'verification_pending', payment_date = NOW(), 
                               payment_reference = ? 
                           WHERE id = ? AND user_id = ?";
            
            $stmt = $conn->prepare($update_cert);
            $stmt->bind_param("sii", $transaction_id, $cert_id, $student_id);
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Cash payment request confirmed. Please visit the institute with the payment amount. Your certificate will be available after payment verification.";
                header("Location: certificates.php?payment_registered=1&cert_id=" . $cert_id);
                exit();
            } else {
                $error_message = "Payment was registered but there was an error updating certificate status.";
            }
        } else {
            $error_message = "Error registering cash payment. Please try again.";
        }
    } else {
        $error_message = "Invalid payment method selected. Please try again.";
    }
}
?>

<div class="container py-4">
    <h2 class="mb-4">Certificate Payment</h2>
    
    <?php if (!empty($success_message)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i> <?php echo $success_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($error_message)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <div class="row">
        <div class="col-md-8">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">Payment Details</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6>Student Information</h6>
                            <p class="mb-1"><strong>Name:</strong> <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></p>
                            <p class="mb-1"><strong>Email:</strong> <?php echo htmlspecialchars($student['email']); ?></p>
                            <?php if (!empty($student['phone'])): ?>
                            <p class="mb-0"><strong>Phone:</strong> <?php echo htmlspecialchars($student['phone']); ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <h6>Payment Information</h6>
                            <p class="mb-1"><strong>Course:</strong> <?php echo htmlspecialchars($course_name); ?></p>
                            <p class="mb-1"><strong>Certificate Number:</strong> <?php echo htmlspecialchars($certificate_number); ?></p>
                            <p class="mb-1"><strong>Order ID:</strong> <?php echo htmlspecialchars($order_id); ?></p>
                            <p class="mb-1"><strong>Certificate Type:</strong> <span class="badge bg-info">Unified Certificate</span></p>
                            <p class="mb-0"><strong>Amount:</strong> <span class="text-primary fw-bold">₹<?php echo number_format($amount, 2); ?></span></p>
                        </div>
                    </div>
                    
                    <form method="post" action="" id="paymentForm">
                        <div class="mb-4">
                            <h5 class="mb-3">Select Payment Method</h5>
                            
                            <div class="payment-methods">
                                <div class="form-check payment-method-option mb-3">
                                    <input class="form-check-input" type="radio" name="payment_method" id="razorpay" value="razorpay" checked>
                                    <label class="form-check-label w-100" for="razorpay">
                                        <div class="d-flex align-items-center">
                                            <div class="me-3">
                                                <i class="fas fa-globe fa-2x text-primary"></i>
                                            </div>
                                            <div>
                                                <span class="d-block fw-bold">Razorpay Online Payment</span>
                                                <small class="text-muted">Pay securely online using Credit/Debit Card, UPI, or Net Banking</small>
                                                <div class="mt-2">
                                                    <img src="../assets/img/razorpay-logo.png" alt="Razorpay" style="height: 20px;" onerror="this.src='https://razorpay.com/assets/razorpay-logo.svg'; this.onerror='';">
                                                    <span class="badge bg-info ms-2">Recommended</span>
                                                </div>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                                
                                <div class="form-check payment-method-option mb-3">
                                    <input class="form-check-input" type="radio" name="payment_method" id="cash" value="cash">
                                    <label class="form-check-label w-100" for="cash">
                                        <div class="d-flex align-items-center">
                                            <div class="me-3">
                                                <i class="fas fa-money-bill-wave fa-2x text-success"></i>
                                            </div>
                                            <div>
                                                <span class="d-block fw-bold">Cash at Institute</span>
                                                <small class="text-muted">Pay in cash at Popular Computer Institute, Bhimpura No.1, Ballia, UP</small>
                                                <div class="alert alert-warning p-2 mt-2 mb-0">
                                                    <small><i class="fas fa-info-circle me-1"></i> Certificate will be issued after payment verification</small>
                                            </div>
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <div id="razorpay-container" class="mb-4 payment-details">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i> Click the Pay button below to proceed with Razorpay secure payment gateway.
                            </div>
                            
                            <!-- Hidden form for Razorpay -->
                            <div class="razorpay-details">
                                <p class="mb-2"><strong>Payment Details:</strong></p>
                                <ul class="list-unstyled mb-3">
                                    <li class="mb-1"><i class="fas fa-check-circle text-success me-2"></i> Secure Online Payment</li>
                                    <li class="mb-1"><i class="fas fa-check-circle text-success me-2"></i> Instant Certificate Access</li>
                                    <li class="mb-1"><i class="fas fa-check-circle text-success me-2"></i> Multiple Payment Options</li>
                                </ul>
                                
                                <div class="payment-methods-icons text-center mb-3">
                                    <img src="https://razorpay.com/assets/razorpay-logo.svg" alt="Razorpay" height="30" class="me-3">
                                    <i class="fab fa-cc-visa fa-2x text-primary me-2"></i>
                                    <i class="fab fa-cc-mastercard fa-2x text-danger me-2"></i>
                                    <i class="fab fa-cc-amex fa-2x text-info me-2"></i>
                                    <i class="fas fa-mobile-alt fa-2x text-success me-2"></i>
                                    <i class="fas fa-university fa-2x text-dark"></i>
                                </div>
                            </div>
                            
                            <input type="hidden" name="razorpay_payment_id" id="razorpay_payment_id">
                            <input type="hidden" name="razorpay_order_id" id="razorpay_order_id" value="<?php echo $order_id; ?>">
                            <input type="hidden" name="razorpay_signature" id="razorpay_signature">
                        </div>
                        
                        <div id="cash-container" class="mb-4 payment-details d-none">
                            <div class="alert alert-info">
                                <div class="d-flex align-items-start">
                                    <i class="fas fa-info-circle me-2 mt-1"></i>
                                    <div>
                                        <p class="mb-2">Instructions for Cash Payment:</p>
                                        <ol class="mb-0">
                                            <li>Visit Popular Computer Institute during working hours (9 AM - 6 PM)</li>
                                            <li>Show your certificate number to the staff: <strong><?php echo htmlspecialchars($certificate_number); ?></strong></li>
                                            <li>Pay the amount: <strong>₹<?php echo number_format($amount, 2); ?></strong></li>
                                            <li>Get payment receipt from the institute</li>
                                            <li>Your certificate will be available within 24 hours after payment verification</li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group mb-3">
                                <label for="payment_note" class="form-label">Add a note (optional):</label>
                                <textarea class="form-control" id="payment_note" name="payment_note" rows="2" placeholder="Any specific information or preferred time to visit"></textarea>
                            </div>
                        </div>
                        
                        <div class="text-end">
                            <a href="certificates.php" class="btn btn-outline-secondary me-2">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-primary" id="payButton">
                                <i class="fas fa-lock me-1"></i> Pay ₹<?php echo number_format($amount, 2); ?>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-light">
                    <h5 class="mb-0">Secure Payment</h5>
                </div>
                <div class="card-body">
                    <div class="secure-payment-info">
                        <div class="d-flex align-items-center mb-3">
                            <div class="me-3">
                                <i class="fas fa-lock text-success"></i>
                            </div>
                            <div>
                                <strong>100% Secure Payments</strong>
                                <p class="mb-0 small">All payment information is encrypted</p>
                            </div>
                        </div>
                        
                        <div class="d-flex align-items-center mb-3">
                            <div class="me-3">
                                <i class="fas fa-shield-alt text-primary"></i>
                            </div>
                            <div>
                                <strong>Trusted Payment Methods</strong>
                                <p class="mb-0 small">We support all major payment options</p>
                            </div>
                        </div>
                        
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <i class="fas fa-certificate text-warning"></i>
                            </div>
                            <div>
                                <strong>Instant Certificate Access</strong>
                                <p class="mb-0 small">Get access to your certificate immediately after payment</p>
                            </div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="payment-summary">
                        <h6 class="mb-3">Payment Summary</h6>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Certificate Fee:</span>
                            <span>₹<?php echo number_format($amount, 2); ?></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Tax:</span>
                            <span>₹0.00</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between fw-bold">
                            <span>Total Amount:</span>
                            <span>₹<?php echo number_format($amount, 2); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.payment-method-option {
    padding: 15px;
    border: 1px solid #dee2e6;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.payment-method-option:hover {
    border-color: #adb5bd;
    background-color: #f8f9fa;
}

.form-check-input:checked + .form-check-label .payment-method-option {
    border-color: #0d6efd;
    background-color: #e7f1ff;
}
</style>

<!-- Include Razorpay SDK -->
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Form validation
    const paymentForm = document.getElementById('paymentForm');
    const razorpayRadio = document.getElementById('razorpay');
    const cashRadio = document.getElementById('cash');
    const razorpayContainer = document.getElementById('razorpay-container');
    const cashContainer = document.getElementById('cash-container');
    const payButton = document.getElementById('payButton');
    
    // Razorpay options
    const razorpayOptions = <?php echo json_encode($razorpay_options); ?>;
    
    // Set up payment method toggling
    function togglePaymentMethod() {
        if (razorpayRadio.checked) {
            razorpayContainer.classList.remove('d-none');
            cashContainer.classList.add('d-none');
            payButton.innerHTML = '<i class="fas fa-lock me-1"></i> Pay Online ₹<?php echo number_format($amount, 2); ?>';
            payButton.classList.remove('btn-success');
            payButton.classList.add('btn-primary');
        } else if (cashRadio.checked) {
            razorpayContainer.classList.add('d-none');
            cashContainer.classList.remove('d-none');
            payButton.innerHTML = '<i class="fas fa-check me-1"></i> Confirm Cash Payment ₹<?php echo number_format($amount, 2); ?>';
            payButton.classList.remove('btn-primary');
            payButton.classList.add('btn-success');
        }
    }
    
    // Initialize Razorpay
    function initRazorpay() {
        <?php if ($order_id): ?>
        const razorpay = new Razorpay({
            key: razorpayOptions.key,
            amount: razorpayOptions.amount,
            currency: razorpayOptions.currency,
            name: razorpayOptions.name,
            description: razorpayOptions.description,
            image: razorpayOptions.image,
            order_id: razorpayOptions.order_id,
            handler: function (response) {
                // Redirect to callback URL with payment response
                window.location.href = razorpayOptions.callback_url 
                    + "&razorpay_payment_id=" + response.razorpay_payment_id 
                    + "&razorpay_order_id=" + response.razorpay_order_id
                    + "&razorpay_signature=" + (response.razorpay_signature || '');
            },
            prefill: razorpayOptions.prefill,
            notes: razorpayOptions.notes,
            theme: razorpayOptions.theme
        });
        
        return razorpay;
        <?php else: ?>
        alert('Payment gateway initialization failed. Please try again later.');
        payButton.disabled = false;
        payButton.innerHTML = '<i class="fas fa-lock me-1"></i> Pay Online ₹<?php echo number_format($amount, 2); ?>';
        return null;
        <?php endif; ?>
    }
    
    // Initial state
    togglePaymentMethod();
    
    // Add event listeners
    razorpayRadio.addEventListener('change', togglePaymentMethod);
    cashRadio.addEventListener('change', togglePaymentMethod);
    
    if (paymentForm) {
        paymentForm.addEventListener('submit', function(e) {
            const paymentMethod = document.querySelector('input[name="payment_method"]:checked');
            
            if (!paymentMethod) {
                e.preventDefault();
                alert('Please select a payment method');
                return false;
            }
            
            if (paymentMethod.value === 'razorpay') {
                // Prevent default form submission
                e.preventDefault();
                
                <?php if ($order_id): ?>
                // Open Razorpay checkout
                const razorpay = initRazorpay();
                if (razorpay) {
                    // Disable button while payment is processing
                    payButton.disabled = true;
                    payButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Opening Payment Gateway...';
                    
                    razorpay.open();
                }
                <?php else: ?>
                alert('Payment gateway initialization failed. Please try again later.');
                <?php endif; ?>
                
                return false; // Ensure form is not submitted
            } else if (paymentMethod.value === 'cash') {
                // For cash payment, just update the status and show confirmation
            payButton.disabled = true;
                payButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span> Confirming...';
                // Form submission continues as normal
            }
        });
    }
});
</script>

<?php include_once('includes/footer.php'); ?>