<?php
// Start session
session_start();
// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
header('Location: ../login.php');
exit();
}
// Include database connection
require_once('../config/database.php');
// Include Razorpay configuration
require_once('../enroll/includes/razorpay_config.php');
// Get student ID from session
$student_id = $_SESSION['user_id'];
// Check for required parameters
if (!isset($_GET['type']) || !isset($_GET['course_id']) || !isset($_GET['amount'])) {
$_SESSION['error_message'] = "Invalid payment request. Missing required parameters.";
header('Location: certificates.php');
exit();
}
$payment_type = $_GET['type'];
$course_id = intval($_GET['course_id']);
$amount = floatval($_GET['amount']);
$return_url = isset($_GET['return_url']) ? $_GET['return_url'] : 'certificates.php';
$cert_id = isset($_GET['cert_id']) ? intval($_GET['cert_id']) : 0;
// Validate amount
if ($amount <= 0) {
$_SESSION['error_message'] = "Invalid payment amount.";
header('Location: certificates.php');
exit();
}
// Verify enrollment
$stmt = $conn->prepare("
SELECT e.*, e.payment_plan, c.title, c.duration, c.price, c.discount_price,
CONCAT(u.first_name, ' ', u.last_name) AS name, u.email, u.phone,
u.first_name, u.last_name
FROM enrollments e
JOIN courses c ON e.course_id = c.id
JOIN users u ON e.user_id = u.id
WHERE e.user_id = ? AND e.course_id = ?
");
$stmt->bind_param('ii', $student_id, $course_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
$_SESSION['error_message'] = "You are not enrolled in this course";
header('Location: certificates.php');
exit();
}
$enrollment = $result->fetch_assoc();
// Get site settings for institute information
$settings_query = "SELECT * FROM site_settings WHERE setting_key IN ('site_name', 'site_address', 'contact_phone', 'contact_email', 'site_logo', 'site_url')";
$settings_result = $conn->query($settings_query);
$settings = [];
if ($settings_result) {
while ($row = $settings_result->fetch_assoc()) {
$settings[$row['setting_key']] = $row['setting_value'];
}
}
// School/Institute information for receipt
$school = [
'site_name' => $settings['site_name'] ?? $razorpay_company_name,
'site_address' => $settings['site_address'] ?? '',
'contact_phone' => $settings['contact_phone'] ?? '',
'contact_email' => $settings['contact_email'] ?? '',
'site_logo' => $settings['site_logo'] ?? $razorpay_company_logo,
'site_url' => $settings['site_url'] ?? ''
];
// Generate a unique receipt ID (will not be stored in database)
$receipt_id = 'rcpt_' . time() . '_' . $student_id;
// Parse course duration to determine payment schedule (similar to enrollment_success.php)
$duration_parts = explode(' ', $enrollment['duration']);
$duration_value = isset($duration_parts[0]) ? intval($duration_parts[0]) : 3; // Default to 3 if not specified
$duration_unit = isset($duration_parts[1]) ? strtolower($duration_parts[1]) : 'months'; // Default to months
// Normalize to months for calculation
$duration_in_months = $duration_value;
if ($duration_unit === 'days') {
$duration_in_months = max(1, ceil($duration_value / 30)); // Convert days to months (minimum 1 month)
} else if ($duration_unit === 'weeks') {
$duration_in_months = max(1, ceil($duration_value / 4)); // Convert weeks to months (minimum 1 month)
} else if ($duration_unit === 'years') {
$duration_in_months = $duration_value * 12; // Convert years to months
}
// Calculate half duration in months
$half_duration_months = max(1, ceil($duration_in_months / 2));
// Get the final price
$price = $enrollment['discount_price'] > 0 && $enrollment['discount_price'] < $enrollment['price']
? $enrollment['discount_price']
: $enrollment['price'];
// Calculate payment plan details based on payment plan
$payment_plan = $enrollment['payment_plan'] ?? 'full';
if ($payment_plan === 'monthly') {
$total_installments = $duration_in_months;
$payment_amount = round($price / $total_installments, 2);
$payment_plan_display = "Monthly Plan ({$total_installments} payments)";
$next_payment_date = date('d M Y', strtotime('+1 month'));
} else if ($payment_plan === 'half_duration' || $payment_plan === 'six_month') {
$total_installments = $half_duration_months;
$payment_amount = round($price / $total_installments, 2);
$payment_plan_display = "Installment Plan ({$total_installments} payments)";
$next_payment_date = date('d M Y', strtotime('+2 months'));
} else {
$total_installments = 1;
$payment_amount = $price;
$payment_plan_display = "Full Payment (One-time)";
}
// Prepare additional notes for Razorpay
$additional_notes = [
'course_id' => $course_id,
'student_id' => $student_id,
'payment_for' => $payment_type,
'installment_number' => isset($_GET['installment_number']) ? $_GET['installment_number'] : '1',
'total_installments' => $total_installments,
'course_title' => $enrollment['title']
];
// Debug information
error_log("Creating Razorpay order: Amount=$amount, Plan=$payment_plan, Receipt=$receipt_id");
// Generate a Razorpay order ID (format it like a real order ID)
// We'll use this for display only since we can't create a real order without the SDK
$fake_order_id = 'order_' . md5(time() . $receipt_id . $student_id);
// Create checkout config directly for client-side checkout
$checkout_config = [
'key' => $razorpay_key_id,
'amount' => $amount * 100, // Amount in paise
'currency' => $razorpay_currency,
'name' => $razorpay_company_name,
'description' => $payment_type . ' - ' . $enrollment['title'],
'prefill' => [
'name' => $enrollment['first_name'] . ' ' . $enrollment['last_name'],
'email' => $enrollment['email'],
'contact' => $enrollment['phone'] ?? ''
],
'notes' => $additional_notes,
'theme' => [
'color' => $razorpay_theme_color
]
];
// Include header
include_once 'includes/header.php';
?>
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card shadow">
<div class="card-header bg-primary text-white">
<h4 class="mb-0">Complete Payment</h4>
</div>
<div class="card-body">
<div class="text-center mb-4">
<img src="../assets/img/razorpay-logo.png" alt="Razorpay" height="50" class="mb-3">
<h5 class="mb-3">Payment Summary</h5>
<div class="table-responsive mb-4">
<table class="table table-bordered">
<tr>
<th>Course:</th>
<td><?php echo htmlspecialchars($enrollment['title']); ?></td>
</tr>
<tr>
<th>Student Name:</th>
<td><?php echo htmlspecialchars($enrollment['name']); ?></td>
</tr>
<tr>
<th>Payment For:</th>
<td><?php echo htmlspecialchars($payment_type); ?></td>
</tr>
<tr>
<th>Payment Plan:</th>
<td><?php echo htmlspecialchars($payment_plan_display); ?></td>
</tr>
<tr>
<th>Amount:</th>
<td class="text-primary fw-bold">₹<?php echo number_format($amount, 2); ?></td>
</tr>
</table>
</div>
<p class="text-muted mb-4">Click the button below to complete your payment securely</p>
<button id="rzp-button" class="btn btn-primary btn-lg">
<i class="fas fa-credit-card me-2"></i> Pay Now
</button>
</div>
<div class="alert alert-info">
<div class="d-flex">
<div class="me-3">
<i class="fas fa-info-circle fa-2x"></i>
</div>
<div>
<h6>Secure Payment</h6>
<p class="mb-0 small">Your payment is secure with Razorpay. You can pay using UPI, Debit/Credit Card, Net Banking, or Wallet.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var options = <?php echo json_encode($checkout_config); ?>;
// Add the handler for success
options.handler = function(response) {
// On successful payment, redirect to callback URL with response data
window.location.href = "payment_callback.php?razorpay_payment_id=" + response.razorpay_payment_id +
"&razorpay_order_id=" + response.razorpay_order_id +
"&razorpay_signature=" + response.razorpay_signature +
"&course_id=<?php echo $course_id; ?>" +
"&amount=<?php echo $amount; ?>" +
"&payment_for=<?php echo urlencode($payment_type); ?>" +
"&payment_plan=<?php echo urlencode($payment_plan); ?>" +
"&receipt=<?php echo $receipt_id; ?>";
};
document.getElementById('rzp-button').onclick = function(e) {
var rzp = new Razorpay(options);
rzp.open();
e.preventDefault();
}
});
</script>
<?php include_once 'includes/footer.php'; ?>