<?php
// Include database configuration
require_once '../database/db_config.php';
// Check if admin is logged in
session_start();
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director')) {
echo json_encode(['success' => false, 'message' => 'Access denied. Please log in as an administrator.']);
exit;
}
// Check if all required data is provided
if (!isset($_POST['payment_id']) || !isset($_POST['amount']) || !isset($_POST['reason'])) {
echo json_encode(['success' => false, 'message' => 'Missing required data.']);
exit;
}
$payment_id = intval($_POST['payment_id']);
$amount = floatval($_POST['amount']);
$reason = trim($_POST['reason']);
$enrollment_id = isset($_POST['enrollment_id']) ? intval($_POST['enrollment_id']) : 0;
// Validate data
if ($payment_id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid payment ID.']);
exit;
}
if ($amount <= 0) {
echo json_encode(['success' => false, 'message' => 'Refund amount must be greater than zero.']);
exit;
}
if (empty($reason)) {
echo json_encode(['success' => false, 'message' => 'Refund reason is required.']);
exit;
}
// Begin transaction
$conn->begin_transaction();
try {
// Get payment details
$query = "SELECT * FROM payments WHERE id = ? AND status = 'completed'";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $payment_id);
$stmt->execute();
$payment = $stmt->get_result()->fetch_assoc();
if (!$payment) {
throw new Exception("Payment not found or already refunded.");
}
// Update payment status
$update_query = "UPDATE payments SET status = 'refunded', updated_at = NOW() WHERE id = ?";
$stmt = $conn->prepare($update_query);
$stmt->bind_param("i", $payment_id);
if (!$stmt->execute()) {
throw new Exception("Failed to update payment status: " . $conn->error);
}
// Create refund record
$insert_query = "INSERT INTO refunds (payment_id, amount, reason, refunded_by, refund_date)
VALUES (?, ?, ?, ?, NOW())";
$stmt = $conn->prepare($insert_query);
$stmt->bind_param("idsi", $payment_id, $amount, $reason, $_SESSION['user_id']);
if (!$stmt->execute()) {
throw new Exception("Failed to create refund record: " . $conn->error);
}
// Log the refund
$log_message = "Payment ID #{$payment_id} refunded. Amount: ₹" . number_format($amount, 2) . ". Reason: " . $reason;
// Check if logger function exists
if (function_exists('logger')) {
logger($_SESSION['user_id'], 'payment_refunded', $log_message);
} else {
// Basic logging fallback
error_log($log_message);
}
// Commit the transaction
$conn->commit();
// Return success response
echo json_encode([
'success' => true,
'message' => 'Payment refunded successfully.',
'payment_id' => $payment_id,
'amount' => $amount,
'enrollment_id' => $enrollment_id
]);
} catch (Exception $e) {
// Rollback the transaction on error
$conn->rollback();
// Return error response
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>